file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/42/0x4290ee89b1E3Fe318eEbceBF24F939A0cC4287a1/sources/CyclopsBank.sol
amount in real tokens/wei if ether
function withdrawDepositsByProfile(uint32 profile_id) external { require(dp_id != BAD_DEPOSIT_PROFILE_ID, "10"); for(uint32 i=0; i < customers_deposits[index].dep_number; i++){ if (depositIsExtractable(customers_deposits[index].deposits[i]) && profile_id == customers_deposits[index].deposits[i].deposit_profile_id){ withdrawDepositById(i); } } emit CustomerWithdrawDepositsByProfileId(msg.sender, profile_id); for(uint32 i=0; i < customers_deposits[index].dep_number; i++){ if (depositIsExtractable(customers_deposits[index].deposits[i]) && profile_id == customers_deposits[index].deposits[i].deposit_profile_id){ withdrawDepositById(i); } } emit CustomerWithdrawDepositsByProfileId(msg.sender, profile_id); }
3,302,505
/* file: AssetBackedTokens.sol ver: 0.0.1 updated:15-July-2017 authors: Nick Addison An ERC20 compliant asset-backed token. The contract was based off Darryl Morris's ERC 20 token contract https://github.com/o0ragman0o/ERC20/blob/master/ERC20.sol This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See MIT Licence for further details. <https://opensource.org/licenses/MIT>. */ pragma solidity ^0.4.10; contract AssetBackedTokens { /* Constants */ bytes32 constant public VERSION = "0.0.1"; /* Structs */ struct TokenAccount { // available tokens to the token holder uint availableTokens; // asset holder of the token holder address assetHolder; // the amount someone else is allowed to transfer from this token holder mapping (address => uint) allowed; // flag to indicate if the struct has been initialised. Set to true if it has, otherwise it'll return false bool initialised; } struct AssetAccount { // the balance of the asset holder's assets held on deposit with the settlement institution uint settledAssets; // the amount of assets that is to be deposited or withdrawn from the asset holder's account the next time the settlement process is run int unsettledAssets; // total amount of tokens issued to token holders by this asset holder uint issuedTokens; // flag to indicate if the struct has been initialised. Set to true if it has, otherwise it'll return false bool initialised; } /* State Valiables */ /// @return Token symbol string public symbol; /// @return Token symbol uint8 public decimals; // Externally owned account (token holder's address) mapped to the token account details mapping (address => TokenAccount) public tokenAccounts; // Maps asset holder addresses to assets held at the settlement institution // One asset holder can have multiple addresses mapped to a single account at the settlement institution mapping (address => AssetAccount) public assetAccounts; // list of participating asset holders address[] assetHolders; // externally owned account (identity) of the settlement insitituion address settlementInstitution; // externally owned account (identity) of the scheme administrator address administrator; /* Enums */ /* Modifiers */ // check that the sender of the transaction is the scheme administrator modifier onlyAdministrator { require(administrator == msg.sender); _; } // check that the sender of the transaction is the settlement asset holder modifier onlySettlementInstitution { require(settlementInstitution == msg.sender); _; } // is the transaction originator a registered asset holder? modifier onlyAssetHolders { require(assetAccounts[msg.sender].initialised); _; } /* Events */ // Triggered when tokens are transferred. event Transfer( address indexed sendingTokenHolder, address indexed receivingTokenHolder, uint amount); // Triggered whenever approve(address _spender, uint _amount) is called. event Approval( address indexed tokenHolder, address indexed thirdParty, uint amount); event EmitTokenTransfer( address indexed tokenHolder, int amount, // amount of tokens being increased (positive) or decreased (negative) uint availableTokens); // token holder's available tokens after the update event EmitAssetTransfer( address assetHolder, int amount, // the amount of assets transfered to (positive) or from (negative) the asset holder int unsettledAssets, // the asset holder's unsettled assets after the asset transfer uint issuedTokens); // the asset holder's issued tokens after the asset transfer event EmitAssetUpdate( address indexed assetHolder, int amount, // amount of assets being increased (positive) or decreased (negative) int unsettledAssets); // the asset holder's unsettled assets after the update event EmitTokenUpdate( address indexed assetHolder, address indexed tokenHolder, int amount, // amount of tokens being increased (positive) or decreased (negative) uint availableTokens, // token holder's available tokens after the update uint issuedTokens); // asset holder's issued tokens after the update event EmitAssetSettlement( address indexed assetHolder, int settledAssetsInTransaction, // the amount of assets settled for a asset holder. Can be a negative value uint newSettledAssetBalance); // the asset holder's settled assets after the settlement /* Funtions Public */ // constructor function AssetBackedTokens(string _symbol, uint8 _decimals, address _settlementInstitution) { symbol = _symbol; decimals = _decimals; administrator = msg.sender; settlementInstitution = _settlementInstitution; } // balance of the token holder's available tokens function balanceOf(address _tokenHolder) public constant returns (uint) { return tokenAccounts[_tokenHolder].availableTokens; } // the amount of tokens a third party can transfer from a token holder function allowance(address tokenHolder, address thirdParty) public constant returns (uint) { return tokenAccounts[tokenHolder].allowed[thirdParty]; } // transfers tokens from transaction originator to another token holder function transfer(address receivingTokenHolder, uint amount) external { xfer(msg.sender, receivingTokenHolder, amount); } // transfer tokens from one tokenHolder to another where the sending token holder has allowed the transaction originator function transferFrom(address sendingTokenHolder, address receivingTokenHolder, uint amount) external { require(tokenAccounts[sendingTokenHolder].allowed[msg.sender] >= amount); tokenAccounts[sendingTokenHolder].allowed[msg.sender] -= amount; xfer(sendingTokenHolder, receivingTokenHolder, amount); } // Process a transfer internally. function xfer(address sendingTokenHolder, address receivingTokenHolder, uint amount) internal { // check the sender has the available tokens require(amount > 0 && tokenAccounts[sendingTokenHolder].availableTokens >= amount); // the receiving token holder already has a token account require(tokenAccounts[receivingTokenHolder].initialised); var sendingAssetHolder = tokenAccounts[sendingTokenHolder].assetHolder; var receivingAssetHolder = tokenAccounts[receivingTokenHolder].assetHolder; tokenAccounts[sendingTokenHolder].availableTokens -= amount; tokenAccounts[receivingTokenHolder].availableTokens += amount; // check for overflow assert(tokenAccounts[receivingTokenHolder].availableTokens > amount); // if assets are being transferred between asset holders if (sendingAssetHolder != receivingAssetHolder) { transferAssets(sendingAssetHolder, receivingAssetHolder, amount); } // Emit event Transfer(sendingTokenHolder, receivingTokenHolder, amount); // Emit event for sending token holder EmitTokenTransfer(sendingTokenHolder, -int(amount), tokenAccounts[sendingTokenHolder].availableTokens); // Emit event for receiving token holder EmitTokenTransfer(receivingTokenHolder, int(amount), tokenAccounts[receivingTokenHolder].availableTokens); } function transferAssets(address sendingAssetHolder, address receivingAssetHolder, uint amount) internal onlySettlementInstitution { // the asset holder of the sending token holder has enough assets and issued tokens require(int(assetAccounts[sendingAssetHolder].settledAssets) + assetAccounts[sendingAssetHolder].unsettledAssets >= int(amount) ); require(assetAccounts[sendingAssetHolder].issuedTokens >= amount); // decrease the assets for the sending asset holder assetAccounts[sendingAssetHolder].unsettledAssets -= int(amount); assetAccounts[sendingAssetHolder].issuedTokens -= amount; // increase the assets for the receiving asset holder assetAccounts[receivingAssetHolder].unsettledAssets += int(amount); assetAccounts[receivingAssetHolder].issuedTokens += amount; // check for overflows assert(assetAccounts[receivingAssetHolder].unsettledAssets > int(amount)); assert(assetAccounts[receivingAssetHolder].issuedTokens > amount); // Emit events to the sending and receiving asset holders EmitAssetTransfer(sendingAssetHolder, int(-amount), assetAccounts[sendingAssetHolder].unsettledAssets, assetAccounts[sendingAssetHolder].issuedTokens); EmitAssetTransfer(receivingAssetHolder, int(amount), assetAccounts[receivingAssetHolder].unsettledAssets, assetAccounts[receivingAssetHolder].issuedTokens); } // Sets the amount of tokens a third-party can transfer from the token holder function approve(address thirdParty, uint amount) external { tokenAccounts[msg.sender].allowed[thirdParty] = amount; Approval(msg.sender, thirdParty, amount); } // the scheme administrator updates the settlement institution function updateSettlementInstitution(address newSettlementInstitutionAddress) onlyAdministrator { settlementInstitution = newSettlementInstitutionAddress; } // the settlement institution increases (deposit) or decreases (withdrawal) a asset holder's assets on deposit with them // a positive amount is a deposit, a negative amount is a withdrawal function updateAssets(address assetHolder, int amount) onlySettlementInstitution { // if a asset account does not already exist for the asset holder if (assetAccounts[assetHolder].initialised == false) { // create a new asset account for the asset holder assetAccounts[assetHolder] = AssetAccount(0, 0, 0, true); // add to the list of asset holders assetHolders.push(assetHolder); } // the asset holder's remaining assets is required to be greater than or equal to the tokens issued by the asset holder assert( int(assetAccounts[assetHolder].settledAssets) + assetAccounts[assetHolder].unsettledAssets + amount >= int(assetAccounts[assetHolder].issuedTokens) ); // increase or decrease the unsettled assets assetAccounts[assetHolder].unsettledAssets += amount; if (amount > 0) { // check for overflow assert(assetAccounts[assetHolder].unsettledAssets > amount); } else { assert(assetAccounts[assetHolder].unsettledAssets > 0); } // Emit event for the update of the asset holder's unsettled assets EmitAssetUpdate(assetHolder, amount, assetAccounts[assetHolder].unsettledAssets); } // the settlement institution settles the assets between their asset holder accounts function settleAssets() onlySettlementInstitution { // for each asset holder for (uint i; i < assetHolders.length; i++) { var assetHolder = assetHolders[i]; var unsettledAssets = assetAccounts[assetHolder].unsettledAssets; // if the asset holder has unsettled assets if (unsettledAssets != 0) { // increase or decrease the settled assets by the number of unsettled assets if (unsettledAssets > 0) { assetAccounts[assetHolder].settledAssets += uint(unsettledAssets); // check for overflows assert(assetAccounts[assetHolder].settledAssets > uint(unsettledAssets)); } else { assert(assetAccounts[assetHolder].settledAssets >= uint(-unsettledAssets)); // convert the negative unsettled amount to a positive amount assetAccounts[assetHolder].settledAssets -= uint(-unsettledAssets); } // reset the unsettled assets back to zero assetAccounts[assetHolder].unsettledAssets = 0; // emit event EmitAssetSettlement(assetHolder, unsettledAssets, assetAccounts[assetHolder].settledAssets); } } } // returns the asset balances of an asset holder function getAssetBalances(address assetHolder) constant returns (uint settledAssets, int unsettledAssets, uint issuedTokens) { require(assetAccounts[assetHolder].initialised); settledAssets = assetAccounts[assetHolder].settledAssets; unsettledAssets = assetAccounts[assetHolder].unsettledAssets; issuedTokens = assetAccounts[assetHolder].issuedTokens; } // asset holder increases or decreases the token holder's available tokens and their own number of issued tokens function updateTokens(address tokenHolder, int amount) onlyAssetHolders { require(amount != 0); // if the token account does not already exist if (tokenAccounts[tokenHolder].initialised == false) { tokenAccounts[tokenHolder] = TokenAccount(0, msg.sender, true); } // is the transaction originator the asset holder of the token holder? require(tokenAccounts[tokenHolder].assetHolder == msg.sender); address assetHolder = msg.sender; uint uintAmount; // if increasing (depositing) tokens if (amount > 0) { uintAmount = uint(amount); // the asset holder has enough assets held at the settlement institution to issue more // tokens to the asset holder's token holders assert(int(assetAccounts[assetHolder].settledAssets) + assetAccounts[assetHolder].unsettledAssets >= int(assetAccounts[assetHolder].issuedTokens) + amount); assetAccounts[assetHolder].issuedTokens += uintAmount; tokenAccounts[tokenHolder].availableTokens += uintAmount; // check for overflows assert(assetAccounts[assetHolder].issuedTokens > uintAmount); assert(tokenAccounts[tokenHolder].availableTokens > uintAmount); } // decreasing (withdrawing) tokens else if (amount < 0) { uintAmount = uint(-amount); // the token holder's available tokens is required to be greater than the amount of tokens being withdrawn assert(assetAccounts[assetHolder].issuedTokens >= uintAmount); assert(tokenAccounts[tokenHolder].availableTokens >= uintAmount); assetAccounts[assetHolder].issuedTokens -= uintAmount; tokenAccounts[tokenHolder].availableTokens -= uintAmount; } EmitTokenUpdate( assetHolder, tokenHolder, amount, // amount of tokens tokenAccounts[tokenHolder].availableTokens, // updated value assetAccounts[assetHolder].issuedTokens); // updated value } // removes any asset holders from the list of asset holders if they have zero asset balances // this is done peridically rather than inline as it is an expensive operation function cleanAssetHolders() returns (uint numberOfCleanedAssetHolders) { address[] storage newassetHolders; // for each asset holder for (uint i; i < assetHolders.length; i++) { var assetHolder = assetHolders[i]; // if the asset holder no longer has any positive or negative balances if (assetAccounts[assetHolder].unsettledAssets == 0 && assetAccounts[assetHolder].settledAssets == 0 && assetAccounts[assetHolder].issuedTokens == 0) { // Do not add this old asset holder with zero balances to the list of new asset holders numberOfCleanedAssetHolders++; } else { // add the old asset holder into the list of new asset holders newassetHolders.push(assetHolder); } } assetHolders = newassetHolders; } // return list of asset holders function getAssetHolders() public constant returns (address[]) { return assetHolders; } }
balance of the token holder's available tokens
function balanceOf(address _tokenHolder) public constant returns (uint) { return tokenAccounts[_tokenHolder].availableTokens; }
1,812,388
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; contract ShortCircuit { function f1(bool b) public pure returns (bool) { // Computazione leggera return b; } function f2() public view returns (bool) { // Computazione pesante uint256 nonce = 0; uint256 randomnumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, nonce))) % 6; nonce++; if (randomnumber >= 3) return true; else return false; } function compare() public view returns (uint256) { uint256 result = 0; // Corto circuito sempre (144 gas) if (f1(true) || f2()) result = 1; // Corto circuito se f2()=true (665 gas), entrambe (671 gas) if (f2() || f1(true)) result = 2; // Corto circuito sempre (144 gas) if (f1(false) && f2()) result = 3; // Corto circuito se f2()=true (664 gas), entrambe (668 gas) if (f2() && f1(false)) result = 4; return result; } }
Computazione leggera
function f1(bool b) public pure returns (bool) { return b; }
5,386,184
/** *Submitted for verification at Etherscan.io on 2021-06-16 */ // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/Roles.sol pragma solidity ^0.8.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping(address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/PauserRole.sol pragma solidity ^0.8.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initPauserRole() internal { _addPauser(_msgSender()); } constructor() { _addPauser(_msgSender()); } modifier onlyPauser() { require( isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role" ); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: contracts/Pausable.sol pragma solidity ^0.8.0; contract Pausable is Context, PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; constructor() { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/WhitelistAdminRole.sol pragma solidity ^0.8.0; /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; function initWhiteListAdmin() internal { _addWhitelistAdmin(_msgSender()); } constructor() { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require( isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role" ); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // File: contracts/SafeMath.sol pragma solidity ^0.8.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: OVERFLOW"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } // File: contracts/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/IERC20.sol pragma solidity ^0.8.0; 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/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @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); _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/Wrap.sol pragma solidity ^0.8.0; contract Wrap { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public token; constructor(IERC20 _tokenAddress) { token = IERC20(_tokenAddress); } uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => uint256[]) public fixedBalances; mapping(address => uint256[]) public releaseTime; mapping(address => uint256) public fixedStakeLength; event WithdrawnFixedStake(address indexed user, uint256 amount); function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public virtual { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } function fixedStake (uint256 _day, uint256 _amount) public virtual { fixedBalances[msg.sender].push(_amount); uint256 time = block.timestamp + _day * 1 days; releaseTime[msg.sender].push(time); fixedStakeLength[msg.sender] += 1; _totalSupply = _totalSupply.add(_amount); IERC20(token).safeTransferFrom(msg.sender, address(this), _amount); } function withdraw(uint256 amount) public virtual { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); IERC20(token).safeTransfer(msg.sender, amount); } function _rescueScore(address account) internal { uint256 amount = _balances[account]; _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); IERC20(token).safeTransfer(account, amount); } function withdrawFixedStake(uint256 _index) public virtual { require(fixedBalances[msg.sender].length >= _index, "No Record Found"); require(fixedBalances[msg.sender][_index] != 0, "No Balance To Break"); require(releaseTime[msg.sender][_index] <= block.timestamp, "Time isn't up"); _totalSupply = _totalSupply.sub(fixedBalances[msg.sender][_index]); IERC20(token).safeTransfer(msg.sender, fixedBalances[msg.sender][_index]); emit WithdrawnFixedStake(msg.sender, fixedBalances[msg.sender][_index]); removeBalance(_index); removeReleaseTime(_index); fixedStakeLength[msg.sender] -= 1; } function removeBalance(uint index) internal { // Move the last element into the place to delete fixedBalances[msg.sender][index] = fixedBalances[msg.sender][fixedBalances[msg.sender].length - 1]; // Remove the last element fixedBalances[msg.sender].pop(); } function removeReleaseTime(uint index) internal { // Move the last element into the place to delete releaseTime[msg.sender][index] = releaseTime[msg.sender][releaseTime[msg.sender].length - 1]; // Remove the last element releaseTime[msg.sender].pop(); } } // File: contracts/MyIERC721.sol pragma solidity ^0.8.0; interface MyIERC721 { function mint(address _to) external; } // File: contracts/ERC721TokenReceiver.sol pragma solidity ^0.8.0; /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4); } // File: contracts/Stake.sol pragma solidity ^0.8.0; contract Stake is Wrap, Pausable, WhitelistAdminRole { struct Card { uint256 points; uint256 releaseTime; address erc721; uint256 supply; } using SafeMath for uint256; mapping(address => mapping(uint256 => Card)) public cards; mapping(address => uint256) public pendingWithdrawals; mapping(address => uint256) public points; mapping(address => uint256) public lastUpdateTime; uint256 public rewardRate = 8640; uint256 public periodStart; uint256 public minStake; uint256 public maxStake; uint256 public minStakeFixed; uint256 public maxStakeFixed; address public controller; bool public constructed = false; address public rescuer; uint256 public spentScore; uint256 public maxDay; event Staked(address indexed user, uint256 amount); event FixedStaked(address indexed user, uint256 indexed amount, uint256 indexed day); event Withdrawn(address indexed user, uint256 amount); event RescueRedeemed(address indexed user, uint256 amount); event Removed( address indexed erc1155, uint256 indexed card, address indexed recipient, uint256 amount ); event Redeemed( address indexed user, address indexed erc1155, uint256 indexed id, uint256 amount ); modifier updateReward(address account) { if (account != address(0)) { points[account] = earned(account); lastUpdateTime[account] = block.timestamp; } _; } constructor( uint256 _periodStart, uint256 _minStake, uint256 _maxStake, uint256 _minStakeFixed, uint256 _maxStakeFixed, uint256 _maxDay, address _controller, IERC20 _tokenAddress ) Wrap(_tokenAddress) { require( _minStake >= 0 && _maxStake > 0 && _maxStake >= _minStake, "Problem with min and max stake setup" ); constructed = true; periodStart = _periodStart; minStake = _minStake; maxStake = _maxStake; minStakeFixed = _minStakeFixed; maxStakeFixed = _maxStakeFixed; controller = _controller; rescuer = _controller; maxDay = _maxDay; // super.initWhiteListAdmin(); } function setRewardRate(uint256 _rewardRate) external onlyWhitelistAdmin { require(_rewardRate > 0, "Reward rate too low"); rewardRate = _rewardRate; } function setMaxDay(uint256 _day) external onlyWhitelistAdmin { require(_day > 0, "Reward rate too low"); maxDay = _day; } function setMinMaxStake(uint256 _minStake, uint256 _maxStake) external onlyWhitelistAdmin { require( _minStake >= 0 && _maxStake > 0 && _maxStake >= _minStake, "Problem with min and max stake setup" ); minStake = _minStake; maxStake = _maxStake; } function setMinMaxStakeFixed(uint256 _minStake, uint256 _maxStake) external onlyWhitelistAdmin { require( _minStake >= 0 && _maxStake > 0 && _maxStake >= _minStake, "Problem with min and max stake setup" ); minStake = _minStake; maxStake = _maxStake; } function setRescuer(address _rescuer) external onlyWhitelistAdmin { rescuer = _rescuer; } function earned(address account) public view returns (uint256) { return points[account].add(getCurrPoints(account)); } function getCurrPoints(address account) internal view returns (uint256) { uint256 blockTime = block.timestamp; return blockTime.sub(lastUpdateTime[account]).mul(balanceOf(account)).div( rewardRate ); } function stake(uint256 amount) public override updateReward(msg.sender) whenNotPaused() { require(block.timestamp >= periodStart, "Pool not open"); require( amount.add(balanceOf(msg.sender)) >= minStake, "Too few deposit" ); require( amount.add(balanceOf(msg.sender)) <= maxStake, "Deposit limit reached" ); super.stake(amount); emit Staked(msg.sender, amount); } function fixedStake (uint256 _day, uint256 _amount) public override whenNotPaused() { require(block.timestamp >= periodStart, "Pool not open"); require(_day > 0, "Can't stake for Zero days"); require(maxDay <= _day, "Stake Day Limit Exceeded"); require( _amount >= minStakeFixed, "Too few deposit" ); require( _amount <= maxStakeFixed, "Deposit limit reached" ); points[msg.sender] = points[msg.sender].add(_day.mul(_amount)); super.fixedStake(_day, _amount); emit FixedStaked(msg.sender, _amount, _day); } function withdraw(uint256 amount) public override updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function withdrawFixedStake(uint256 index) public override { super.withdrawFixedStake(index); } function exit() external { withdraw(balanceOf(msg.sender)); } function rescueScore(address account) external updateReward(account) returns (uint256) { require(msg.sender == rescuer, "!rescuer"); uint256 earnedPoints = points[account]; spentScore = spentScore.add(earnedPoints); points[account] = 0; if (balanceOf(account) > 0) { _rescueScore(account); } emit RescueRedeemed(account, earnedPoints); return earnedPoints; } function addNfts( uint256 _points, uint256 _releaseTime, address _erc721Address, uint256 _tokenId, uint256 _cardAmount ) public onlyWhitelistAdmin returns (uint256) { require(_tokenId > 0, "Invalid token id"); require(_cardAmount > 0, "Invalid card amount"); Card storage c = cards[_erc721Address][_tokenId]; c.points = _points; c.releaseTime = _releaseTime; c.erc721 = _erc721Address; c.supply = _cardAmount; return _tokenId; } function redeem(address _erc721Address, uint256 id) external updateReward(msg.sender) { require(cards[_erc721Address][id].points != 0, "Card not found"); require( block.timestamp >= cards[_erc721Address][id].releaseTime, "Card not released" ); require( points[msg.sender] >= cards[_erc721Address][id].points, "Redemption exceeds point balance" ); points[msg.sender] = points[msg.sender].sub( cards[_erc721Address][id].points ); spentScore = spentScore.add(cards[_erc721Address][id].points); MyIERC721(cards[_erc721Address][id].erc721).mint(msg.sender); emit Redeemed( msg.sender, cards[_erc721Address][id].erc721, id, cards[_erc721Address][id].points ); } }
Move the last element into the place to delete Remove the last element
function removeReleaseTime(uint index) internal { releaseTime[msg.sender][index] = releaseTime[msg.sender][releaseTime[msg.sender].length - 1]; releaseTime[msg.sender].pop(); }
10,918,060
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthentication { /** * @dev Returns the action identifier associated with the external function described by `selector`. */ function getActionId(bytes4 selector) external view returns (bytes32); } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // 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: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; uint256 internal constant DISABLED = 211; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; uint256 internal constant ERC20_BURN_EXCEEDS_BALANCE = 434; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/IAuthentication.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; import "./IBalancerToken.sol"; interface IBalancerTokenAdmin is IAuthentication { // solhint-disable func-name-mixedcase function INITIAL_RATE() external view returns (uint256); function RATE_REDUCTION_TIME() external view returns (uint256); function RATE_REDUCTION_COEFFICIENT() external view returns (uint256); function RATE_DENOMINATOR() external view returns (uint256); // solhint-enable func-name-mixedcase /** * @notice Returns the address of the Balancer Governance Token */ function getBalancerToken() external view returns (IBalancerToken); /** * @notice Returns the Balancer Vault. */ function getVault() external view returns (IVault); function activate() external; function rate() external view returns (uint256); function startEpochTimeWrite() external returns (uint256); function mint(address to, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IBalancerToken is IERC20 { function mint(address to, uint256 amount) external; function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; // solhint-disable-next-line func-name-mixedcase function DEFAULT_ADMIN_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function MINTER_ROLE() external view returns (bytes32); // solhint-disable-next-line func-name-mixedcase function SNAPSHOT_ROLE() external view returns (bytes32); function snapshot() external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "./BalancerErrors.sol"; import "./IAuthentication.sol"; /** * @dev Building block for performing access control on external functions. * * This contract is used via the `authenticate` modifier (or the `_authenticateCaller` function), which can be applied * to external functions to only make them callable by authorized accounts. * * Derived contracts must implement the `_canPerform` function, which holds the actual access control logic. */ abstract contract Authentication is IAuthentication { bytes32 private immutable _actionIdDisambiguator; /** * @dev The main purpose of the `actionIdDisambiguator` is to prevent accidental function selector collisions in * multi contract systems. * * There are two main uses for it: * - if the contract is a singleton, any unique identifier can be used to make the associated action identifiers * unique. The contract's own address is a good option. * - if the contract belongs to a family that shares action identifiers for the same functions, an identifier * shared by the entire family (and no other contract) should be used instead. */ constructor(bytes32 actionIdDisambiguator) { _actionIdDisambiguator = actionIdDisambiguator; } /** * @dev Reverts unless the caller is allowed to call this function. Should only be applied to external functions. */ modifier authenticate() { _authenticateCaller(); _; } /** * @dev Reverts unless the caller is allowed to call the entry point function. */ function _authenticateCaller() internal view { bytes32 actionId = getActionId(msg.sig); _require(_canPerform(actionId, msg.sender), Errors.SENDER_NOT_ALLOWED); } function getActionId(bytes4 selector) public view override returns (bytes32) { // Each external function is dynamically assigned an action identifier as the hash of the disambiguator and the // function selector. Disambiguation is necessary to avoid potential collisions in the function selectors of // multiple contracts. return keccak256(abi.encodePacked(_actionIdDisambiguator, selector)); } function _canPerform(bytes32 actionId, address user) internal view virtual returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "@balancer-labs/v2-solidity-utils/contracts/helpers/Authentication.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "@balancer-labs/v2-solidity-utils/contracts/math/Math.sol"; import "./interfaces/IBalancerTokenAdmin.sol"; // solhint-disable not-rely-on-time /** * @title Balancer Token Admin * @notice This contract holds all admin powers over the BAL token passing through calls * while delegating access control to the Balancer Authorizer * * In addition, calls to the mint function must respect the inflation schedule as defined in this contract. * As this contract is the only way to mint BAL tokens this ensures that the maximum allowed supply is enforced * @dev This contract exists as a consequence of the gauge systems needing to know a fixed inflation schedule * in order to know how much BAL a gauge is allowed to mint. As this does not exist within the BAL token itself * it is defined here, we must then wrap the token's minting functionality in order for this to be meaningful. */ contract BalancerTokenAdmin is IBalancerTokenAdmin, Authentication, ReentrancyGuard { using Math for uint256; // Initial inflation rate of 145k BAL per week. uint256 public constant override INITIAL_RATE = (145000 * 1e18) / uint256(1 weeks); // BAL has 18 decimals uint256 public constant override RATE_REDUCTION_TIME = 365 days; uint256 public constant override RATE_REDUCTION_COEFFICIENT = 1189207115002721024; // 2 ** (1/4) * 1e18 uint256 public constant override RATE_DENOMINATOR = 1e18; IVault private immutable _vault; IBalancerToken private immutable _balancerToken; event MiningParametersUpdated(uint256 rate, uint256 supply); // Supply Variables uint256 private _miningEpoch; uint256 private _startEpochTime = type(uint256).max; // Sentinel value for contract not being activated uint256 private _startEpochSupply; uint256 private _rate; constructor(IVault vault, IBalancerToken balancerToken) Authentication(bytes32(uint256(address(this)))) { // BalancerTokenAdmin is a singleton, so it simply uses its own address to disambiguate action identifiers _balancerToken = balancerToken; _vault = vault; } /** * @dev Returns the Balancer token. */ function getBalancerToken() external view override returns (IBalancerToken) { return _balancerToken; } /** * @notice Returns the Balancer Vault. */ function getVault() public view override returns (IVault) { return _vault; } /** * @notice Returns the Balancer Vault's current authorizer. */ function getAuthorizer() public view returns (IAuthorizer) { return getVault().getAuthorizer(); } /** * @notice Initiate BAL token inflation schedule * @dev Reverts if contract does not have sole minting powers over BAL (and no other minters can be added). */ function activate() external override nonReentrant authenticate { require(_startEpochTime == type(uint256).max, "Already activated"); // We need to check that this contract can't be bypassed to mint more BAL in the future. // If other addresses had minting rights over the BAL token then this inflation schedule // could be bypassed by minting new tokens directly on the BalancerGovernanceToken contract. // On the BalancerGovernanceToken contract the minter role's admin is the DEFAULT_ADMIN_ROLE. // No external function exists to change the minter role's admin so we cannot make the list of // minters immutable without revoking all access to DEFAULT_ADMIN_ROLE. bytes32 minterRole = _balancerToken.MINTER_ROLE(); bytes32 snapshotRole = _balancerToken.SNAPSHOT_ROLE(); bytes32 adminRole = _balancerToken.DEFAULT_ADMIN_ROLE(); require(_balancerToken.hasRole(adminRole, address(this)), "BalancerTokenAdmin is not an admin"); // All other minters must be removed to avoid inflation schedule enforcement being bypassed. uint256 numberOfMinters = _balancerToken.getRoleMemberCount(minterRole); for (uint256 i = 0; i < numberOfMinters; ++i) { address minter = _balancerToken.getRoleMember(minterRole, 0); _balancerToken.revokeRole(minterRole, minter); } // Give this contract minting rights over the BAL token _balancerToken.grantRole(minterRole, address(this)); // BalancerGovernanceToken exposes a role-restricted `snapshot` function for performing onchain voting. // We delegate control over this to the Balancer Authorizer by removing this role from all current addresses // and exposing a function which defers to the Authorizer for access control. uint256 numberOfSnapshotters = _balancerToken.getRoleMemberCount(snapshotRole); for (uint256 i = 0; i < numberOfSnapshotters; ++i) { address snapshotter = _balancerToken.getRoleMember(snapshotRole, 0); _balancerToken.revokeRole(snapshotRole, snapshotter); } // Give this contract snapshotting rights over the BAL token _balancerToken.grantRole(snapshotRole, address(this)); // BalancerTokenAdmin now is the only holder of MINTER_ROLE and SNAPSHOT_ROLE for BalancerGovernanceToken. // We can't prevent any other admins from granting other addresses these roles however. // This undermines the ability for BalancerTokenAdmin to enforce the correct inflation schedule. // The only way to prevent this is for BalancerTokenAdmin to be the only admin. We then remove all other admins. uint256 numberOfAdmins = _balancerToken.getRoleMemberCount(adminRole); uint256 skipSelf = 0; for (uint256 i = 0; i < numberOfAdmins; ++i) { address admin = _balancerToken.getRoleMember(adminRole, skipSelf); if (admin != address(this)) { _balancerToken.revokeRole(adminRole, admin); } else { // This contract is now the admin with index 0, we now delete the address with index 1 instead skipSelf = 1; } } // BalancerTokenAdmin doesn't actually need admin rights any more and won't grant rights to any more addresses // We then renounce our admin role to ensure that another address won't gain absolute minting powers. _balancerToken.revokeRole(adminRole, address(this)); // Perform sanity checks to make sure we're not leaving the roles in a broken state require(_balancerToken.getRoleMemberCount(adminRole) == 0, "Address exists with admin rights"); require(_balancerToken.hasRole(minterRole, address(this)), "BalancerTokenAdmin is not a minter"); require(_balancerToken.hasRole(snapshotRole, address(this)), "BalancerTokenAdmin is not a snapshotter"); require(_balancerToken.getRoleMemberCount(minterRole) == 1, "Multiple minters exist"); require(_balancerToken.getRoleMemberCount(snapshotRole) == 1, "Multiple snapshotters exist"); // As BAL inflation is now enforced by this contract we can initialise the relevant variables. _startEpochSupply = _balancerToken.totalSupply(); _startEpochTime = block.timestamp; _rate = INITIAL_RATE; emit MiningParametersUpdated(INITIAL_RATE, _startEpochSupply); } /** * @notice Mint BAL tokens subject to the defined inflation schedule * @dev Callable only by addresses defined in the Balancer Authorizer contract */ function mint(address to, uint256 amount) external override authenticate { // Check if we've passed into a new epoch such that we should calculate available supply with a smaller rate. if (block.timestamp >= _startEpochTime.add(RATE_REDUCTION_TIME)) { _updateMiningParameters(); } require( _balancerToken.totalSupply().add(amount) <= _availableSupply(), "Mint amount exceeds remaining available supply" ); _balancerToken.mint(to, amount); } /** * @notice Perform a snapshot of BAL token balances * @dev Callable only by addresses defined in the Balancer Authorizer contract */ function snapshot() external authenticate { _balancerToken.snapshot(); } /** * @notice Returns the current epoch number. */ function getMiningEpoch() external view returns (uint256) { return _miningEpoch; } /** * @notice Returns the start timestamp of the current epoch. */ function getStartEpochTime() external view returns (uint256) { return _startEpochTime; } /** * @notice Returns the start timestamp of the next epoch. */ function getFutureEpochTime() external view returns (uint256) { return _startEpochTime.add(RATE_REDUCTION_TIME); } /** * @notice Returns the available supply at the beginning of the current epoch. */ function getStartEpochSupply() external view returns (uint256) { return _startEpochSupply; } /** * @notice Returns the current inflation rate of BAL per second */ function getInflationRate() external view returns (uint256) { return _rate; } /** * @notice Maximum allowable number of tokens in existence (claimed or unclaimed) */ function getAvailableSupply() external view returns (uint256) { return _availableSupply(); } /** * @notice Get timestamp of the current mining epoch start while simultaneously updating mining parameters * @return Timestamp of the current epoch */ function startEpochTimeWrite() external override returns (uint256) { return _startEpochTimeWrite(); } /** * @notice Get timestamp of the next mining epoch start while simultaneously updating mining parameters * @return Timestamp of the next epoch */ function futureEpochTimeWrite() external returns (uint256) { return _startEpochTimeWrite().add(RATE_REDUCTION_TIME); } /** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ function updateMiningParameters() external { require(block.timestamp >= _startEpochTime.add(RATE_REDUCTION_TIME), "Epoch has not finished yet"); _updateMiningParameters(); } /** * @notice How much supply is mintable from start timestamp till end timestamp * @param start Start of the time interval (timestamp) * @param end End of the time interval (timestamp) * @return Tokens mintable from `start` till `end` */ function mintableInTimeframe(uint256 start, uint256 end) external view returns (uint256) { return _mintableInTimeframe(start, end); } // Internal functions function _canPerform(bytes32 actionId, address account) internal view override returns (bool) { return getAuthorizer().canPerform(actionId, account, address(this)); } /** * @notice Maximum allowable number of tokens in existence (claimed or unclaimed) */ function _availableSupply() internal view returns (uint256) { uint256 newSupplyFromCurrentEpoch = (block.timestamp.sub(_startEpochTime)).mul(_rate); return _startEpochSupply.add(newSupplyFromCurrentEpoch); } /** * @notice Get timestamp of the current mining epoch start while simultaneously updating mining parameters * @return Timestamp of the current epoch */ function _startEpochTimeWrite() internal returns (uint256) { uint256 startEpochTime = _startEpochTime; if (block.timestamp >= startEpochTime.add(RATE_REDUCTION_TIME)) { _updateMiningParameters(); return _startEpochTime; } return startEpochTime; } function _updateMiningParameters() internal { uint256 inflationRate = _rate; uint256 startEpochSupply = _startEpochSupply.add(inflationRate.mul(RATE_REDUCTION_TIME)); inflationRate = inflationRate.mul(RATE_DENOMINATOR).divDown(RATE_REDUCTION_COEFFICIENT); _miningEpoch = _miningEpoch.add(1); _startEpochTime = _startEpochTime.add(RATE_REDUCTION_TIME); _rate = inflationRate; _startEpochSupply = startEpochSupply; emit MiningParametersUpdated(inflationRate, startEpochSupply); } /** * @notice How much supply is mintable from start timestamp till end timestamp * @param start Start of the time interval (timestamp) * @param end End of the time interval (timestamp) * @return Tokens mintable from `start` till `end` */ function _mintableInTimeframe(uint256 start, uint256 end) internal view returns (uint256) { require(start <= end, "start > end"); uint256 currentEpochTime = _startEpochTime; uint256 currentRate = _rate; // It shouldn't be possible to over/underflow in here but we add checked maths to be safe // Special case if end is in future (not yet minted) epoch if (end > currentEpochTime.add(RATE_REDUCTION_TIME)) { currentEpochTime = currentEpochTime.add(RATE_REDUCTION_TIME); currentRate = currentRate.mul(RATE_DENOMINATOR).divDown(RATE_REDUCTION_COEFFICIENT); } require(end <= currentEpochTime.add(RATE_REDUCTION_TIME), "too far in future"); uint256 toMint = 0; for (uint256 epoch = 0; epoch < 999; ++epoch) { if (end >= currentEpochTime) { uint256 currentEnd = end; if (currentEnd > currentEpochTime.add(RATE_REDUCTION_TIME)) { currentEnd = currentEpochTime.add(RATE_REDUCTION_TIME); } uint256 currentStart = start; if (currentStart >= currentEpochTime.add(RATE_REDUCTION_TIME)) { // We should never get here but what if... break; } else if (currentStart < currentEpochTime) { currentStart = currentEpochTime; } toMint = toMint.add(currentRate.mul(currentEnd.sub(currentStart))); if (start >= currentEpochTime) { break; } } currentEpochTime = currentEpochTime.sub(RATE_REDUCTION_TIME); // double-division with rounding made rate a bit less => good currentRate = currentRate.mul(RATE_REDUCTION_COEFFICIENT).divDown(RATE_DENOMINATOR); assert(currentRate <= INITIAL_RATE); } return toMint; } // The below functions are duplicates of functions available above. // They are included for ABI compatibility with snake_casing as used in vyper contracts. // solhint-disable func-name-mixedcase function rate() external view override returns (uint256) { return _rate; } function available_supply() external view returns (uint256) { return _availableSupply(); } /** * @notice Get timestamp of the current mining epoch start while simultaneously updating mining parameters * @return Timestamp of the current epoch */ function start_epoch_time_write() external returns (uint256) { return _startEpochTimeWrite(); } /** * @notice Get timestamp of the next mining epoch start while simultaneously updating mining parameters * @return Timestamp of the next epoch */ function future_epoch_time_write() external returns (uint256) { return _startEpochTimeWrite().add(RATE_REDUCTION_TIME); } /** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ function update_mining_parameters() external { require(block.timestamp >= _startEpochTime.add(RATE_REDUCTION_TIME), "Epoch has not finished yet"); _updateMiningParameters(); } /** * @notice How much supply is mintable from start timestamp till end timestamp * @param start Start of the time interval (timestamp) * @param end End of the time interval (timestamp) * @return Tokens mintable from `start` till `end` */ function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { return _mintableInTimeframe(start, end); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow checks. * Adapted from OpenZeppelin's SafeMath library. */ library Math { /** * @dev Returns the absolute value of a signed integer. */ function abs(int256 a) internal pure returns (uint256) { return a > 0 ? uint256(a) : uint256(-a); } /** * @dev Returns the addition of two unsigned integers of 256 bits, reverting on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; _require(c >= a, Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the addition of two signed integers, reverting on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; _require((b >= 0 && c >= a) || (b < 0 && c < a), Errors.ADD_OVERFLOW); return c; } /** * @dev Returns the subtraction of two unsigned integers of 256 bits, reverting on overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { _require(b <= a, Errors.SUB_OVERFLOW); uint256 c = a - b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; _require((b >= 0 && c <= a) || (b < 0 && c > a), Errors.SUB_OVERFLOW); return c; } /** * @dev Returns the largest of two numbers of 256 bits. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers of 256 bits. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; _require(a == 0 || c / a == b, Errors.MUL_OVERFLOW); return c; } function div( uint256 a, uint256 b, bool roundUp ) internal pure returns (uint256) { return roundUp ? divUp(a, b) : divDown(a, b); } function divDown(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); return a / b; } function divUp(uint256 a, uint256 b) internal pure returns (uint256) { _require(b != 0, Errors.ZERO_DIVISION); if (a == 0) { return 0; } else { return 1 + (a - 1) / b; } } }
Update mining rate and supply at the start of the epoch Callable by any address, but only once per epoch Total supply becomes slightly larger if this function is called late/
function updateMiningParameters() external { require(block.timestamp >= _startEpochTime.add(RATE_REDUCTION_TIME), "Epoch has not finished yet"); _updateMiningParameters(); }
1,257,807
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./ITag.sol"; /// @title If you own an It, you're it /// @author jierlich /// @notice Until unlock this can only be transferred by the holder contract It is ERC721 { /// @dev number of Its minted uint public counter = 0; /// @dev count of number of transfers of any It uint public transfers = 0; /// @dev Tag tokens minted when an It is transferred uint public mintAmount = 420000000000000000000; /// @dev Tag tokens that must be burned to mint an It uint constant burnAmount = 420000000000000000000; /// @dev when true users can not approve others for transferring a token bool public locked = true; /// @dev address of the Tag token address public erc20; /// @dev contract owner address public owner; /// @param _name name of the ERC721 /// @param _symbol symbol of the ERC721 /// @param _erc20 address of the associated ERC20 constructor(string memory _name, string memory _symbol, address _erc20) ERC721(_name, _symbol) { erc20 = _erc20; owner = msg.sender; } /// @notice mints a new It /// @param to receiver of the newly minted It function mint(address to) public { require(counter < 10000, "Max mint reached"); ITag(erc20).burnFrom(msg.sender, burnAmount); counter++; super._safeMint(to, counter); } /// @notice hook before transfer events to block approved transfers by others before unlock /// @param from holder of token before transfer function _beforeTokenTransfer( address from, address /* to */, uint256 /* tokenId */ ) internal override view { /// @dev this condition is true when minting if (from == address(0)) { return; } /// @dev only let the holder send the token while lockd require(!locked || from == msg.sender, 'Only holder can transfer while locked'); } /// @notice Mints Tag tokens to the sender upon transfer /// @param from holder of token before transfer /// @param to holder of token after transfer /// @param tokenId id of the It to transfer function _transfer( address from, address to, uint256 tokenId ) internal override { super._transfer(from, to, tokenId); /// @dev reward transfer with tokens if there are remaining Its to mint if (counter < 10000) { ITag(erc20).mint(from, mintAmount); } transfers++; if (transfers == 1337) { mintAmount = 69000000000000000000; } } /// @notice change the owner of the contract /// @param _owner new owner function setOwner (address _owner) public { require(owner == msg.sender, 'Only owner can call this function'); owner = _owner; } /// @notice unlock the contract so It's can be approved for transfer function unlock () public { require(owner == msg.sender, 'Only owner can call this function'); locked = false; } }
unlock the contract so It's can be approved for transfer
function unlock () public { require(owner == msg.sender, 'Only owner can call this function'); locked = false; }
14,039,816
./partial_match/1/0x381e3c53380DB31aDc8F1d2eB6a5a8DdF793EDab/sources/contracts/UniStrategy.sol
This function returns the readjust threshold of a pool _pool: pool address/
function getReadjustThreshold(address _pool) external view override returns (int24 readjustThreshold) { readjustThreshold = poolStrategy[_pool].readjustThreshold; }
2,870,606
./full_match/1/0xac6F8dCfDa428E81d34986997020c33970195913/sources/src/utils/FeeOperator.sol
Internal function to transfer fees to the fee manager. fees The amount of fees being transferred./
function _transferFees(uint256 fees) internal { if (!success) { revert FeeTransferFailed(); } }
2,913,412
./full_match/80001/0xe3665Dd88482E29734DC4c247Cd2c8aF885b1d3C/sources/contracts/NFTMarketplace.sol
Mengembalikan hanya item yang telah didaftarkan pengguna /
function fetchItemsListed() public view returns (MarketItem[] memory) { uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; }
850,156
./full_match/1/0xBcbba981bFf1E9530CbcA0f40F67Aa85F8944038/sources/src/x-key/XRaffleBase.sol
set the winning token set the raffle stage set the deadline for claiming the reward the omission of the winning token is intentional
function _recordRoundWinner(uint8 _roundId, uint16 tokenId) internal { awaitingWinnerForRound = 0; _roundWinningToken[_roundId] = tokenId; raffles[_roundId].stage = RaffleStage.WinnerDrawn; nextClaimDeadline = SafeCast.toUint64(block.timestamp + CLAIM_DEADLINE); emit WinningToken(tokenId); emit WinnerDrawn(RequestType.Raffle, _roundId); }
9,610,596
pragma solidity >=0.5.11; //Represents the money being traded in this program contract Money { int amount; //Amount that this Money object holds constructor(int amt) public { amount = amt; } //Add additional Money function mergeMoney(Money m) public { amount = amount + m.getAmount(); } //Returns the amount of this Money function getAmount() public view returns (int) { return amount; } // DANGER: for internal use only! function addAmount(int amt) public { amount += amt; } //Use some amount of this Money function splitMoneyInto(int amt, Money otherMoney) public { if (amt > amount) { revert ("Can't split out more money than is available in a given Money object."); } else { amount = amount - amt; otherMoney.addAmount(amt); } } } //Represents the bet prediction of a Bettor contract BetPrediction { string public predictedOutcome; //the Bettor's prediction of the winning outcome int public betAmount; //the amount of money the Bettor put down on this BetPrediction constructor(string memory predOut, int amount) public { predictedOutcome = predOut; betAmount = amount; } } //Represents a person betting on a game contract Bettor { Money money; //Total Money the Bettor owns constructor(Money m) public { money = m; } //Take some Money out of the Bettor's total money function withdrawMoney(int amount) public returns (Money) { Money newMoney = new Money(0); money.splitMoneyInto(amount, newMoney); return newMoney; } //Adds Money to the Bettor's total money function receiveMoney(Money m) public { money.mergeMoney(m); } } //Represents a single bet contract Bet { Bettor public bettor; //The Bettor making the bet BetPrediction public prediction; //The BetPrediction for the winner constructor(Bettor b, BetPrediction p) public { bettor = b; prediction = p; } } //Represents a container of Bets contract BetList { Bet[] bets; //Add a new Bet to the end of the list function append(Bet newB) public { bets.push(newB); } //remove a Bet with a given Bettor reference, and return that Bet function popSpecific(Bettor bettor) public returns (Bet) { for (uint i = 0; i < bets.length; i++) { if (bets[i].bettor() == bettor) { Bet result = bets[i]; bets[i] = bets[bets.length - 1]; delete bets[bets.length - 1]; bets.length--; return result; } } revert("No matching bets in list"); } //returns true if a Bet has been placed by a Bettor function contains(Bettor bettor) public view returns (bool) { for (uint i = 0; i < bets.length; i++) { if (bets[i].bettor() == bettor) { return true; } } } } //Represents a generic game contract Game { enum State { BeforePlay, Playing, FinishedPlaying} State state; constructor() public { state = State.BeforePlay; } //Start the game function startPlaying() public { require(state == State.BeforePlay, "Wrong initial state."); state = State.Playing; } //Finish the game function finishPlaying() public { require(state == State.Playing, "Wrong initial state."); state = State.FinishedPlaying; } //Returns the outcome of the game function calculateOutcome() public view returns (string memory) { require(state == State.FinishedPlaying, "Wrong initial state."); //... return ""; //Always returns empty string for now } }
Returns the outcome of the game...
function calculateOutcome() public view returns (string memory) { require(state == State.FinishedPlaying, "Wrong initial state."); }
12,673,746
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); } /* * @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; } } /** * @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; } } contract TimeUtil { uint256 private constant blockPerSecNumerator = 1; uint256 private constant blockPerSecDenominator = 13; using SafeMath for uint256; function blocksFromCurrent(uint256 targetTime) public view returns (uint256) { return toBlocks(targetTime.sub(block.timestamp)); } function blocksFromBegin(uint256 targetTime) public view returns (uint256) { return blocksFromCurrent(targetTime).add(block.number); } function toBlocks(uint256 diffTime) public pure returns (uint256) { return diffTime.mul(blockPerSecNumerator).div(blockPerSecDenominator); } } /** * @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); } } } } /** * @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"); } } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @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; } } abstract contract AdminAccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _adminSet; constructor() internal { _adminSet.add(_msgSender()); } function getAdministrators() public view returns (address[] memory addresses) { addresses = new address[](_adminSet.length()); for (uint256 index = 0; index < addresses.length; ++index) addresses[index] = _adminSet.at(index); } function addAdministrator(address account) public onlyAdmin { require(_adminSet.add(account), "AccessControl: account already an administrator."); } function clearAdministrator(address account) public onlyAdmin { require(_adminSet.length() > 1, "AccessControl: cannot remove last administrator."); require(_adminSet.remove(account), "AccessControl: account not an administrator."); } modifier onlyAdmin() { require(_adminSet.contains(_msgSender()), "AccessControl: require administrator account"); _; } } contract StakingBase is ReentrancyGuard, AdminAccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // deposited amount uint256 rewardDebt; // reward debt for pending calculation uint256 exChanged; // total claimed token } // Info of each pool. struct PoolInfo { address tokenAddress; // address of sataking token uint256 poolPledged; // total pledged token per pool uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that token distribution occurs. uint256 accTokenPerShare; // Accumulated token per share, times 1e12. } struct PeriodeReleases { uint256 blockOffset; // number of block from mining begin uint256 tokenPerBlock; // number of tokens release per block } // How many allocation points assigned in total. uint256 public totalAllocPoint; // periodes PeriodeReleases[] public periodes; // Tokens that will be released uint256 public miningTotal; // the beginning block of mining uint256 public miningBeginBlock; // yao token IERC20 private _yao; bool public isEmergency; // abstraction pools, which might be an ERC1155 pool, an ERC20 pool, even a CFX pool // depens on inherition PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; event Withdraw(address indexed user, uint256 indexed pId, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pId, uint256 amount); constructor(IERC20 yao_) public { _yao = yao_; isEmergency = false; } function setEmergency(bool isEmergency_) public onlyAdmin { isEmergency = isEmergency_; } /** * @dev add new pool, with alloc point * any inherited contract should call this function to create the pool */ function _add(uint256 _allocPoint, address tokenAddress) internal onlyAdmin returns (uint256) { _updateAllPools(); uint256 pid = poolInfo.length; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({tokenAddress: tokenAddress, poolPledged: 0, allocPoint: _allocPoint, lastRewardBlock: miningBeginBlock, accTokenPerShare: 0})); return pid; } /** * @dev modify an pool's alloc point. * in order to minimize inaccuracy, it should call before the pool opens or as soon as a periode is advanced */ function setAllocPoint(uint256 pId, uint256 _allocPoint) public virtual onlyAdmin { _updateAllPools(); PoolInfo storage pool = poolInfo[pId]; totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(_allocPoint); pool.allocPoint = _allocPoint; } /** * @dev get the balance of owner's periode token */ function pendingToken(uint256 pId, address _user) external view returns (uint256) { PoolInfo memory pool = poolInfo[pId]; UserInfo memory user = userInfo[pId][_user]; uint256 accTokenPerShare = pool.accTokenPerShare; if (block.number > pool.lastRewardBlock && pool.poolPledged > 0) { uint256 yaoReward = getPoolReward(pool.lastRewardBlock, pool.allocPoint); accTokenPerShare = accTokenPerShare.add(yaoReward.mul(1e12).div(pool.poolPledged)); } return user.amount.mul(accTokenPerShare).div(1e12).sub(user.rewardDebt); } /** * @dev refresh all pool infomation, should be called before modification is maked for any pools */ function _updateAllPools() internal virtual { for (uint256 idxPool = 0; idxPool < poolInfo.length; ++idxPool) _updatePool(poolInfo[idxPool]); } /** * @dev Update reward variables of the given pool to be up-to-date. */ function _updatePool(PoolInfo storage pool) internal virtual { // if the mining is not started there is no needs to update if (block.number <= pool.lastRewardBlock) { return; } // if there is nothing in this pool if (pool.poolPledged == 0) { pool.lastRewardBlock = block.number; return; } // get reward uint256 yaoReward = getPoolReward(pool.lastRewardBlock, pool.allocPoint); // calcult accumulate token per share pool.accTokenPerShare = pool.accTokenPerShare.add(yaoReward.mul(1e12).div(pool.poolPledged)); // update pool last reward block pool.lastRewardBlock = block.number; } /** * @dev deposit token into pool * any inherited contract should call this function to make a deposit */ function _deposit(uint256 pId, uint256 _amount) internal nonReentrant returns (uint256) { PoolInfo storage pool = poolInfo[pId]; UserInfo storage user = userInfo[pId][_msgSender()]; _withdrawPool(pId, user); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); pool.poolPledged = pool.poolPledged.add(_amount); return user.amount; } /** * @dev withdraw staking token from pool * any inherited contract should call this function to make a withdraw */ function _withdraw(uint256 pId, uint256 _amount) internal nonReentrant returns (uint256) { PoolInfo storage pool = poolInfo[pId]; UserInfo storage user = userInfo[pId][_msgSender()]; require(user.amount >= _amount, "StakingBase: _withdraw needs amount > user.amount"); _withdrawPool(pId, user); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); pool.poolPledged = pool.poolPledged.sub(_amount); return user.amount; } /** * @dev withdraw without tokens, emergency only * any inherited contract should call this function to make a emergencyWithdraw */ function _emergencyWithdraw(uint256 pId) internal nonReentrant onEmergency returns (uint256) { PoolInfo storage pool = poolInfo[pId]; UserInfo storage user = userInfo[pId][_msgSender()]; if (user.amount > 0) { user.amount = 0; user.rewardDebt = 0; pool.poolPledged = pool.poolPledged.sub(user.amount); } } /** * @dev withdraw periode token from pool(in this case is Yao) */ function withdrawPool(uint256 pId) public nonReentrant { _withdrawPool(pId, userInfo[pId][_msgSender()]); } /** * @dev withdraw periode token from every pool(in this case is Yao) */ function withdrawPoolAll() public nonReentrant { for (uint256 index = 0; index < poolInfo.length; ++index) { UserInfo storage user = userInfo[index][_msgSender()]; if (user.amount > 0) _withdrawPool(index, user); } } /** * @dev implemtation of withdraw pending tokens */ function _withdrawPool(uint256 pId, UserInfo storage user) private { PoolInfo storage pool = poolInfo[pId]; // update pool for new accTokenPerShare _updatePool(pool); // calculate pending tokens uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt); // if has pending token, then send if (pending > 0) { safeTransferYAO(_msgSender(), pending); user.exChanged = user.exChanged.add(pending); emit Withdraw(_msgSender(), pId, pending); } // update user reward debut user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12); } // Safe Yao transfer function, just in case if rounding error causes pool to not have enough tokens. function safeTransferYAO(address to, uint256 amount) internal { if (amount > 0) { uint256 acgBal = _yao.balanceOf(address(this)); if (amount > acgBal) { _yao.transfer(to, acgBal); } else { _yao.transfer(to, amount); } } } /** * @dev get pool reward */ function getPoolReward(uint256 _poolLastRewardBlock, uint256 _poolAllocPoint) internal view returns (uint256) { return getPoolReward(_poolLastRewardBlock, _poolAllocPoint, block.number); } /** * @dev get pool reward */ function getPoolReward( uint256 _poolLastRewardBlock, uint256 _poolAllocPoint, uint256 _blockNumber ) internal view returns (uint256) { if (_blockNumber < miningBeginBlock) return 0; // get offset of current block from beginning uint256 currentOffset = _blockNumber.sub(miningBeginBlock); // get offset of last reward block from beginning uint256 lasRewardBlockOffset = _poolLastRewardBlock.sub(miningBeginBlock); uint256 poolRewards = 0; // from last periode to first periode for (uint256 idx = periodes.length - 1; ; --idx) { // if last reward is later that current periode, // so we sure that lasRewardBlockOffset to currentOffset is in the same periode, // accumulate rewards then stop iterate. // if not, that lasRewardBlockOffset and currentOffset is in the different periode, // accumulate rewards and move currentOffset to the beginning of current periode, contiune to iterate PeriodeReleases memory onePeriode = periodes[idx]; if (lasRewardBlockOffset >= onePeriode.blockOffset) { poolRewards = poolRewards.add(onePeriode.tokenPerBlock * currentOffset.sub(lasRewardBlockOffset)); break; } else if (currentOffset > onePeriode.blockOffset) { poolRewards = poolRewards.add(onePeriode.tokenPerBlock * (currentOffset.sub(onePeriode.blockOffset))); currentOffset = onePeriode.blockOffset; } } // apply allocation percentage to pool reward return poolRewards.mul(_poolAllocPoint).div(totalAllocPoint); } function getBlockInfo() public view returns (uint256, uint256) { return (block.timestamp, block.number); } function estimateRewards( uint256 pId, uint256 amount, uint256 blockOffset ) public view returns (uint256 rewards) { PoolInfo memory pool = poolInfo[pId]; uint256 yaoReward = getPoolReward(block.number, pool.allocPoint, block.number.add(blockOffset)); return yaoReward.mul(amount).div(pool.poolPledged.add(amount)); } function totalReleased() public view returns (uint256) { if (block.number < miningBeginBlock) return 0; // get offset of current block from beginning uint256 currentOffset = block.number.sub(miningBeginBlock); uint256 sum = 0; for (uint256 idx = periodes.length - 1; ; --idx) { PeriodeReleases memory onePeriode = periodes[idx]; if (currentOffset > onePeriode.blockOffset) { sum = sum.add(onePeriode.tokenPerBlock * (currentOffset.sub(onePeriode.blockOffset))); currentOffset = onePeriode.blockOffset; if (idx == 0) break; } } return sum; } modifier onEmergency() { require(isEmergency, "StakingBase: not in emergency"); _; } } /** * @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 ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } /** * @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 _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } /** * @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.UintToUintMap; * * // Declare a set state variable * EnumerableMap.UintToUintMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> uint256` (`UintToUintMap`) 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 Uint256Touint256Map) 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 } // UintToUintMap struct UintToUintMap { 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( UintToUintMap storage map, uint256 key, uint256 value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(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(UintToUintMap 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(UintToUintMap 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(UintToUintMap 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(UintToUintMap storage map, uint256 index) internal view returns (uint256, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), 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(UintToUintMap storage map, uint256 key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToUintMap storage map, uint256 key) internal view returns (uint256) { return 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( UintToUintMap storage map, uint256 key, string memory errorMessage ) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(key), errorMessage)); } } contract StakingERC1155Receiver is ERC1155Receiver { event OnERC1155Received(address operator, address from, uint256 id, uint256 value, bytes data); event OnERC1155BatchReceived(address operator, address from, uint256[] ids, uint256[] values, bytes data); /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) public virtual override returns (bytes4) { //return bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")); emit OnERC1155Received(operator, from, id, value, data); return this.onERC1155Received.selector; } /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) public virtual override returns (bytes4) { //return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")); emit OnERC1155BatchReceived(operator, from, ids, values, data); return this.onERC1155BatchReceived.selector; } } abstract contract StakingERC1155 is StakingBase, StakingERC1155Receiver { using SafeMath for uint256; using EnumerableMap for EnumerableMap.UintToUintMap; using EnumerableSet for EnumerableSet.UintSet; uint256 constant ERC1155StakingMax = 5; mapping(uint256 => mapping(address => EnumerableMap.UintToUintMap)) private _erc1155Pools; EnumerableSet.UintSet private _erc1155PoolIdSet; event DepositERC1155(address indexed user, uint256 indexed pid, uint256[] erc1155Id, uint256[] amount); event WithdrawERC1155(address indexed user, uint256 indexed pid, uint256[] erc1155Id, uint256[] amount); constructor() internal {} /** * @dev add a erc1155 pool */ function addERC1155Pool(uint256 _allocPoint, address _1155TokenAddr) public onlyAdmin { uint256 pId = _add(_allocPoint, _1155TokenAddr); _erc1155PoolIdSet.add(pId); } /** * @dev deposit erc1155 token to pool */ function depositERC1155( uint256 pId, uint256[] calldata erc1155Ids, uint256[] calldata amounts ) public validAsERC1155PId(pId) { require(erc1155Ids.length == amounts.length, "StakingERC1155: _ids and amounts length mismatch"); uint256 amountSum = 0; EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][_msgSender()]; for (uint256 index = 0; index < erc1155Ids.length; ++index) { (, uint256 count) = erc1155Entities.tryGet(erc1155Ids[index]); erc1155Entities.set(erc1155Ids[index], count.add(amounts[index])); amountSum = amountSum.add(amounts[index]); } require(_deposit(pId, amountSum) <= ERC1155StakingMax, "StakingERC1155: NFT staking count exceed its maximun"); IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id tokenProdiver.safeBatchTransferFrom(_msgSender(), address(this), erc1155Ids, amounts, ""); emit DepositERC1155(_msgSender(), pId, erc1155Ids, amounts); } /** * @dev withdraw erc1155 token from pool */ function withdrawERC1155( uint256 pId, uint256[] calldata erc1155Ids, uint256[] calldata amounts ) public validAsERC1155PId(pId) { require(erc1155Ids.length == amounts.length, "StakingERC1155: _ids and amounts length mismatch"); uint256 amountSum = 0; EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][_msgSender()]; for (uint256 index = 0; index < erc1155Ids.length; ++index) { uint256 id = erc1155Ids[index]; uint256 amount = amounts[index]; uint256 count = erc1155Entities.get(id); uint256 rest = count.sub(amount); if (rest > 0) erc1155Entities.set(id, rest); else erc1155Entities.remove(id); amountSum = amountSum.add(amount); } _withdraw(pId, amountSum); IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id tokenProdiver.safeBatchTransferFrom(address(this), _msgSender(), erc1155Ids, amounts, ""); emit WithdrawERC1155(_msgSender(), pId, erc1155Ids, amounts); } /** * @dev withdraw all staked erc1155 tokens in emergency, without tansfer pending tokens */ function emergencyWithdrawERC1155(uint256 pId) public onEmergency validAsERC1155PId(pId) { (uint256[] memory erc1155Ids, uint256[] memory amounts) = pledgedERC1155(pId, _msgSender()); _emergencyWithdraw(pId); IERC1155 tokenProdiver = IERC1155(poolInfo[pId].tokenAddress); // get token provider by id tokenProdiver.safeBatchTransferFrom(address(this), _msgSender(), erc1155Ids, amounts, ""); } /** * @dev get user pledgedERC1155 tokens for all pools */ function pledgedERC1155(uint256 pId, address user) public view validAsERC1155PId(pId) returns (uint256[] memory erc1155Ids, uint256[] memory amounts) { EnumerableMap.UintToUintMap storage erc1155Entities = _erc1155Pools[pId][user]; uint256 count = erc1155Entities.length(); erc1155Ids = new uint256[](count); amounts = new uint256[](count); for (uint256 index = 0; index < count; ++index) (erc1155Ids[index], amounts[index]) = erc1155Entities.at(index); } /** * @dev get all ERC1155 token pool ids */ function listERC1155PoolIds() public view returns (uint256[] memory poolIds) { poolIds = new uint256[](_erc1155PoolIdSet.length()); for (uint256 index = 0; index < poolIds.length; ++index) poolIds[index] = _erc1155PoolIdSet.at(index); } /** * @dev valid a pool id is belonged to erc 20 pool */ modifier validAsERC1155PId(uint256 pId) { require(_erc1155PoolIdSet.contains(pId), "StakingERC1155: pool id not belong to defi ERC1155"); _; } } /** * @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); } /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract StakingERC721Receiver is ERC165, IERC721Receiver { constructor() internal { _registerInterface(StakingERC721Receiver(address(0)).onERC721Received.selector); } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } abstract contract StakingERC721 is StakingBase, StakingERC721Receiver { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; uint256 constant ERC721StakingMax = 5; mapping(uint256 => mapping(address => EnumerableSet.UintSet)) private erc721Pools; EnumerableSet.UintSet private erc721PoolIdSet; event DepositERC721(address indexed user, uint256 indexed pid, uint256 indexed erc721Id); event WithdrawERC721(address indexed user, uint256 indexed pid, uint256 indexed erc721Id); constructor() internal {} // Add a new erc721 token 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 addERC721Pool(uint256 _allocPoint, address _721TokenAddr) public onlyAdmin { uint256 pId = _add(_allocPoint, _721TokenAddr); erc721PoolIdSet.add(pId); } // Deposit ERC721s to MasterChef for XIAONAN allocation. function depositERC721(uint256 pId, uint256 erc721Id) public validAsERC721PId(pId) { EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_msgSender()]; require(erc721Entities.add(erc721Id), "StakingERC721: erc721 token already deposited"); require(_deposit(pId, 1) <= ERC721StakingMax, "StakingERC721: NFT staking count exceed its maximun"); IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress); tokenProdiver.safeTransferFrom(_msgSender(), address(this), erc721Id); emit DepositERC721(_msgSender(), pId, erc721Id); } // Withdraw ERC721s from MasterChef. function withdrawERC721(uint256 pId, uint256 erc721Id) public validAsERC721PId(pId) { EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_msgSender()]; require(erc721Entities.remove(erc721Id), "StakingERC721: erc721 token not existe"); _withdraw(pId, 1); IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress); tokenProdiver.safeTransferFrom(address(this), _msgSender(), erc721Id); emit WithdrawERC721(_msgSender(), pId, erc721Id); } /** * @dev withdraw all staked erc1155 tokens in emergency, without tansfer pending tokens */ function emergencyWithdrawERC721(uint256 pId) public onEmergency validAsERC721PId(pId) { uint256[] memory erc721Ids = pledgedERC721(pId, _msgSender()); _emergencyWithdraw(pId); IERC721 tokenProdiver = IERC721(poolInfo[pId].tokenAddress); // get token provider by id for (uint256 index = 0; index < erc721Ids.length; ++index) tokenProdiver.safeTransferFrom(address(this), _msgSender(), erc721Ids[index]); } function pledgedERC721(uint256 pId, address _user) public view validAsERC721PId(pId) returns (uint256[] memory erc721Ids) { EnumerableSet.UintSet storage erc721Entities = erc721Pools[pId][_user]; uint256 count = erc721Entities.length(); erc721Ids = new uint256[](count); for (uint256 index = 0; index < count; ++index) erc721Ids[index] = erc721Entities.at(index); } function listERC721PoolIds() public view returns (uint256[] memory poolIds) { poolIds = new uint256[](erc721PoolIdSet.length()); for (uint256 index = 0; index < poolIds.length; ++index) poolIds[index] = erc721PoolIdSet.at(index); } modifier validAsERC721PId(uint256 pId) { require(erc721PoolIdSet.contains(pId), "StakingERC721: pool id not belong to defi ERC721"); _; } } contract StakingYao is Ownable, StakingBase, StakingERC1155, StakingERC721, TimeUtil { constructor(IERC20 yao_) public StakingBase(yao_) { prodInit(); } function prodInit() private { miningBeginBlock = 12527500; //2021/05/29 13:54:19 periodes.push(PeriodeReleases({blockOffset: toBlocks(0 days), tokenPerBlock: calculeTokenPerBlock(60000 ether, 14 days)})); periodes.push(PeriodeReleases({blockOffset: toBlocks(14 days), tokenPerBlock: calculeTokenPerBlock(25000 ether, 90 days)})); periodes.push(PeriodeReleases({blockOffset: toBlocks(104 days), tokenPerBlock: calculeTokenPerBlock(10000 ether, 90 days)})); periodes.push(PeriodeReleases({blockOffset: toBlocks(194 days), tokenPerBlock: calculeTokenPerBlock(3750 ether, 90 days)})); periodes.push(PeriodeReleases({blockOffset: toBlocks(284 days), tokenPerBlock: calculeTokenPerBlock(1250 ether, 90 days)})); periodes.push(PeriodeReleases({blockOffset: toBlocks(374 days), tokenPerBlock: 0})); updateMiningTotal(); } function updateMiningTotal() private { uint256 sum = 0; for (uint256 index = 1; index < periodes.length; ++index) { sum += (periodes[index].blockOffset - periodes[index - 1].blockOffset) * periodes[index - 1].tokenPerBlock; } miningTotal = sum; } function calculeTokenPerBlock(uint256 amount, uint256 time) private pure returns (uint256) { return amount / toBlocks(time); } }
withdraw without tokens, emergency only any inherited contract should call this function to make a emergencyWithdraw/
function _emergencyWithdraw(uint256 pId) internal nonReentrant onEmergency returns (uint256) { PoolInfo storage pool = poolInfo[pId]; UserInfo storage user = userInfo[pId][_msgSender()]; if (user.amount > 0) { user.amount = 0; user.rewardDebt = 0; pool.poolPledged = pool.poolPledged.sub(user.amount); } }
13,446,535
./full_match/9001/0x7A5c119ec5dDbF9631cf40f6e5DB28f31d4332a0/sources/src/Facets/CalldataVerificationFacet.sol
Validates the calldata data The calldata to validate bridge The bridge to validate or empty string to ignore sendingAssetId The sending asset id to validate or 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF to ignore receiver The receiver to validate or 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF to ignore amount The amount to validate or type(uint256).max to ignore destinationChainId The destination chain id to validate or type(uint256).max to ignore hasSourceSwaps Whether the calldata has source swaps hasDestinationCall Whether the calldata has a destination call return isValid Whether the calldata is validate Check bridge Check sendingAssetId Check receiver Check amount Check destinationChainId Check hasSourceSwaps Check hasDestinationCall
function validateCalldata( bytes calldata data, string calldata bridge, address sendingAssetId, address receiver, uint256 amount, uint256 destinationChainId, bool hasSourceSwaps, bool hasDestinationCall ) external pure returns (bool isValid) { ILiFi.BridgeData memory bridgeData; ( bridgeData.bridge, bridgeData.sendingAssetId, bridgeData.receiver, bridgeData.minAmount, bridgeData.destinationChainId, bridgeData.hasSourceSwaps, bridgeData.hasDestinationCall ) = extractMainParameters(data); return (keccak256(abi.encodePacked(bridge)) == keccak256(abi.encodePacked("")) || keccak256(abi.encodePacked(bridgeData.bridge)) == keccak256(abi.encodePacked(bridge))) && (sendingAssetId == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF || bridgeData.sendingAssetId == sendingAssetId) && (receiver == 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF || bridgeData.receiver == receiver) && (amount == type(uint256).max || bridgeData.minAmount == amount) && (destinationChainId == type(uint256).max || bridgeData.destinationChainId == destinationChainId) && bridgeData.hasSourceSwaps == hasSourceSwaps && bridgeData.hasDestinationCall == hasDestinationCall; }
11,534,526
/* Subscrypto Copyright (C) 2019 Subscrypto Team This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.2; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Medianizer { function read() public view returns (bytes32); } contract Weth { mapping(address => mapping(address => uint)) public allowance; mapping(address => uint) public balanceOf; function transferFrom(address src, address dst, uint wad) public returns (bool); } /// @author The Subscrypto Team /// @title Subscrypto recurring payments contract Subscrypto { using SafeMath for uint; Medianizer public daiPriceContract; Weth public wethContract; /** * Constructor * @param daiMedianizerContract address * @param wethContractAddress address */ constructor(address daiMedianizerContract, address wethContractAddress) public { daiPriceContract = Medianizer(daiMedianizerContract); wethContract = Weth(wethContractAddress); } event NewSubscription( address indexed subscriber, address indexed receiver, uint daiCents, uint32 interval ); event Unsubscribe( address indexed subscriber, address indexed receiver ); event ReceiverPaymentsCollected( address indexed receiver, uint weiAmount, uint startIndex, uint endIndex ); event PaymentCollected( address indexed subscriber, address indexed receiver, uint weiAmount, uint daiCents, uint48 effectiveTimestamp ); event UnfundedPayment( address indexed subscriber, address indexed receiver, uint weiAmount, uint daiCents ); event StaleSubscription( address indexed subscriber, address indexed receiver ); event SubscriptionDeactivated( address indexed subscriber, address indexed receiver ); event SubscriptionReactivated( address indexed subscriber, address indexed receiver ); // Conservative amount of gas used per loop in collectPayments() uint constant MIN_GAS_PER_COLLECT_PAYMENT = 45000; // Force subscribers to use multiple accounts when this limit is reached. uint constant MAX_SUBSCRIPTION_PER_SUBSCRIBER = 10000; // Minimum payment of 1 DAI uint constant MIN_SUBSCRIPTION_DAI_CENTS = 100; // If this many intervals pass without being collected, mark as inactive uint constant STALE_INTERVAL_THRESHOLD = 3; struct Subscription { bool isActive; // 1 byte uint48 nextPaymentTime; // 6 bytes uint32 interval; // 4 bytes address subscriber; // 20 bytes address receiver; // 20 bytes uint daiCents; // 32 bytes } // global counter for suscriptions uint64 nextIndex = 1; // source of truth for subscriptions mapping(uint64 => Subscription) public subscriptions; // subscriber => receiver => subsciptionIndex mapping(address => mapping(address => uint64)) public subscriberReceiver; // receiver => subs array mapping(address => uint64[]) public receiverSubs; // subscriber => subs array mapping(address => uint64[]) public subscriberSubs; /** * Create a new subscription. Must be called by the subscriber's account. * First payment of `daiCents` is paid on creation. * Actual payment is made in Wrapped Ether (wETH) using currenct DAI-ETH conversion rate. * @param receiver address * @param daiCents subscription amount in hundredths of DAI * @param interval seconds between payments */ function subscribe(address receiver, uint daiCents, uint32 interval) external { uint weiAmount = daiCentsToEthWei(daiCents, ethPriceInDaiWad()); uint64 existingIndex = subscriberReceiver[msg.sender][receiver]; require(subscriptions[existingIndex].daiCents == 0, "Subscription exists"); require(daiCents >= MIN_SUBSCRIPTION_DAI_CENTS, "Subsciption amount too low"); require(interval >= 86400, "Interval must be at least 1 day"); require(interval <= 31557600, "Interval must be at most 1 year"); require(subscriberSubs[msg.sender].length < MAX_SUBSCRIPTION_PER_SUBSCRIBER,"Subscription count limit reached"); // first payment require(wethContract.transferFrom(msg.sender, receiver, weiAmount), "wETH transferFrom() failed"); // add to subscription mappings subscriptions[nextIndex] = Subscription( true, uint48(now.add(interval)), interval, msg.sender, receiver, daiCents ); subscriberReceiver[msg.sender][receiver] = nextIndex; receiverSubs[receiver].push(nextIndex); subscriberSubs[msg.sender].push(nextIndex); emit NewSubscription(msg.sender, receiver, daiCents, interval); emit PaymentCollected(msg.sender, receiver, weiAmount, daiCents, uint48(now)); nextIndex++; } /** * Deactivate a subscription. Must be called by the subscriber's account. * Payments cannot be collected from deactivated subscriptons. * @param receiver address used to identify the unique subscriber-receiver pair. * @return success */ function deactivateSubscription(address receiver) external returns (bool) { uint64 index = subscriberReceiver[msg.sender][receiver]; require(index != 0, "Subscription does not exist"); Subscription storage sub = subscriptions[index]; require(sub.isActive, "Subscription is already disabled"); require(sub.daiCents > 0, "Subscription does not exist"); sub.isActive = false; emit SubscriptionDeactivated(msg.sender, receiver); return true; } /** * Reactivate a subscription. Must be called by the subscriber's account. * If less than one interval has passed since the last payment, no payment is collected now. * Otherwise it is treated as a new subscription starting now, and the first payment is collected. * No back-payments are collected. * @param receiver addres used to identify the unique subscriber-receiver pair. * @return success */ function reactivateSubscription(address receiver) external returns (bool) { uint64 index = subscriberReceiver[msg.sender][receiver]; require(index != 0, "Subscription does not exist"); Subscription storage sub = subscriptions[index]; require(!sub.isActive, "Subscription is already active"); sub.isActive = true; emit SubscriptionReactivated(msg.sender, receiver); if (calculateUnpaidIntervalsUntil(sub, now) > 0) { // only make a payment if at least one interval has lapsed since the last payment uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceInDaiWad()); require(wethContract.transferFrom(msg.sender, receiver, weiAmount), "Insufficient funds to reactivate subscription"); emit PaymentCollected(msg.sender, receiver, weiAmount, sub.daiCents, uint48(now)); } sub.nextPaymentTime = uint48(now.add(sub.interval)); return true; } /** * Delete a subscription. Must be called by the subscriber's account. * @param receiver address used to identify the unique subscriber-receiver pair. */ function unsubscribe(address receiver) external { uint64 index = subscriberReceiver[msg.sender][receiver]; require(index != 0, "Subscription does not exist"); delete subscriptions[index]; delete subscriberReceiver[msg.sender][receiver]; deleteElement(subscriberSubs[msg.sender], index); emit Unsubscribe(msg.sender, receiver); } /** * Delete a subscription. Must be called by the receiver's account. * @param subscriber address used to identify the unique subscriber-receiver pair. */ function unsubscribeByReceiver(address subscriber) external { uint64 index = subscriberReceiver[subscriber][msg.sender]; require(index != 0, "Subscription does not exist"); delete subscriptions[index]; delete subscriberReceiver[subscriber][msg.sender]; deleteElement(subscriberSubs[subscriber], index); emit Unsubscribe(subscriber, msg.sender); } /** * Collect all available *funded* payments for a receiver's account. * Helper function that calls collectPaymentsRange() with the full range. * Will process as many payments as possible with the gas provided and exit gracefully. * * @param receiver address */ function collectPayments(address receiver) external { collectPaymentsRange(receiver, 0, receiverSubs[receiver].length); } /** * A read-only version of collectPayments() * Calculates uncollected *funded* payments for a receiver. * @param receiver address * @return total unclaimed value in wei */ function getTotalUnclaimedPayments(address receiver) external view returns (uint) { uint totalPayment = 0; uint ethPriceWad = ethPriceInDaiWad(); for (uint i = 0; i < receiverSubs[receiver].length; i++) { Subscription storage sub = subscriptions[receiverSubs[receiver][i]]; if (sub.isActive && sub.daiCents != 0) { uint wholeUnpaidIntervals = calculateUnpaidIntervalsUntil(sub, now); if (wholeUnpaidIntervals > 0 && wholeUnpaidIntervals < STALE_INTERVAL_THRESHOLD) { uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceWad); uint authorizedBalance = allowedBalance(sub.subscriber); do { if (authorizedBalance >= weiAmount) { totalPayment = totalPayment.add(weiAmount); authorizedBalance = authorizedBalance.sub(weiAmount); } wholeUnpaidIntervals = wholeUnpaidIntervals.sub(1); } while (wholeUnpaidIntervals > 0); } } } return totalPayment; } /** * Calculates a subscriber's total outstanding payments in daiCents * @param subscriber address * @param time in seconds. If `time` < `now`, then we simply use `now` * @return total amount owed at `time` in daiCents */ function outstandingBalanceUntil(address subscriber, uint time) external view returns (uint) { uint until = time <= now ? now : time; uint64[] memory subs = subscriberSubs[subscriber]; uint totalDaiCents = 0; for (uint64 i = 0; i < subs.length; i++) { Subscription memory sub = subscriptions[subs[i]]; if (sub.isActive) { totalDaiCents = totalDaiCents.add(sub.daiCents.mul(calculateUnpaidIntervalsUntil(sub, until))); } } return totalDaiCents; } /** * Collect available *funded* payments for a receiver's account within a certain range of receiverSubs[receiver]. * Will process as many payments as possible with the gas provided and exit gracefully. * * @param receiver address * @param start starting index of receiverSubs[receiver] * @param end ending index of receiverSubs[receiver] * @return last processed index */ function collectPaymentsRange(address receiver, uint start, uint end) public returns (uint) { uint64[] storage subs = receiverSubs[receiver]; require(subs.length > 0, "receiver has no subscriptions"); require(start < end && end <= subs.length, "wrong arguments for range"); uint totalPayment = 0; uint ethPriceWad = ethPriceInDaiWad(); uint last = end; uint i = start; while (i < last) { if (gasleft() < MIN_GAS_PER_COLLECT_PAYMENT) { break; } Subscription storage sub = subscriptions[subs[i]]; // delete empty subs while (sub.daiCents == 0 && subs.length > 0) { uint lastIndex = subs.length.sub(1); subs[i] = subs[lastIndex]; delete(subs[lastIndex]); subs.length = lastIndex; if (last > lastIndex) { last = lastIndex; } if (lastIndex > 0) { sub = subscriptions[subs[i]]; } } if (sub.isActive && sub.daiCents != 0) { uint wholeUnpaidIntervals = calculateUnpaidIntervalsUntil(sub, now); if (wholeUnpaidIntervals > 0) { // this could be placed in the following else{} block, but the stack becomes too deep uint subscriberPayment = 0; if (wholeUnpaidIntervals >= STALE_INTERVAL_THRESHOLD) { sub.isActive = false; emit SubscriptionDeactivated(sub.subscriber, receiver); emit StaleSubscription(sub.subscriber, receiver); } else { uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceWad); uint authorizedBalance = allowedBalance(sub.subscriber); do { if (authorizedBalance >= weiAmount) { totalPayment = totalPayment.add(weiAmount); subscriberPayment = subscriberPayment.add(weiAmount); authorizedBalance = authorizedBalance.sub(weiAmount); emit PaymentCollected(sub.subscriber, receiver, weiAmount, sub.daiCents, sub.nextPaymentTime); sub.nextPaymentTime = calculateNextPaymentTime(sub); } else { emit UnfundedPayment(sub.subscriber, receiver, weiAmount, sub.daiCents); } wholeUnpaidIntervals = wholeUnpaidIntervals.sub(1); } while (wholeUnpaidIntervals > 0); } if (subscriberPayment > 0) { assert(wethContract.transferFrom(sub.subscriber, receiver, subscriberPayment)); } } } i++; } emit ReceiverPaymentsCollected(receiver, totalPayment, start, i); return i; } /** * Calculates how much wETH balance Subscrypto is authorized to use on bealf of `subscriber`. * Returns the minimum(subscriber's wETH balance, amount authorized to Subscrypto). * @param subscriber address * @return wad amount of wETH available for Subscrypto payments */ function allowedBalance(address subscriber) public view returns (uint) { uint balance = wethContract.balanceOf(subscriber); uint allowance = wethContract.allowance(subscriber, address(this)); return balance > allowance ? allowance : balance; } /** * Calls the DAI medianizer contract to get the current exchange rate for ETH-DAI * @return current ETH price in DAI (wad format) */ function ethPriceInDaiWad() public view returns (uint) { uint price = uint(daiPriceContract.read()); require(price > 1, "Invalid price for DAI."); return price; } /** * Helper function to search for and delete an array element without leaving a gap. * Array size is also decremented. * DO NOT USE if ordering is important. * @param array array to be modified * @param element value to be removed */ function deleteElement(uint64[] storage array, uint64 element) internal { uint lastIndex = array.length.sub(1); for (uint i = 0; i < array.length; i++) { if (array[i] == element) { array[i] = array[lastIndex]; delete(array[lastIndex]); array.length = lastIndex; break; } } } /** * Calculates how many whole unpaid intervals (will) have elapsed since the last payment at a specific `time`. * DOES NOT check if subscriber account is funded. * @param sub Subscription object * @param time timestamp in seconds * @return number of unpaid intervals */ function calculateUnpaidIntervalsUntil(Subscription memory sub, uint time) internal view returns (uint) { require(time >= now, "don't use a time before now"); if (time > sub.nextPaymentTime) { return ((time.sub(sub.nextPaymentTime)).div(sub.interval)).add(1); } return 0; } /** * Safely calculate the next payment timestamp for a Subscription * @param sub Subscription object * @return uint48 timestamp in seconds of the next payment */ function calculateNextPaymentTime(Subscription memory sub) internal pure returns (uint48) { uint48 nextPaymentTime = sub.nextPaymentTime + sub.interval; assert(nextPaymentTime > sub.nextPaymentTime); return nextPaymentTime; } /** * Converts DAI (cents) to ETH (wei) without losing precision * @param daiCents one hundreth of a DAI * @param ethPriceWad price from calling ethPriceInDaiWad() * @return ETH value denominated in wei */ function daiCentsToEthWei(uint daiCents, uint ethPriceWad) internal pure returns (uint) { return centsToWad(daiCents).mul(10**18).div(ethPriceWad); } /** * Converts amount in cents (hundredths of DAI) to amount in wad * @param cents daiCents (hundredths of DAI) * @return amount of dai in wad */ function centsToWad(uint cents) internal pure returns (uint) { return cents.mul(10**16); } }
Collect available funded payments for a receiver's account within a certain range of receiverSubs[receiver]. Will process as many payments as possible with the gas provided and exit gracefully. receiver address start starting index of receiverSubs[receiver] end ending index of receiverSubs[receiver] return last processed index/ delete empty subs this could be placed in the following else{} block, but the stack becomes too deep
function collectPaymentsRange(address receiver, uint start, uint end) public returns (uint) { uint64[] storage subs = receiverSubs[receiver]; require(subs.length > 0, "receiver has no subscriptions"); require(start < end && end <= subs.length, "wrong arguments for range"); uint totalPayment = 0; uint ethPriceWad = ethPriceInDaiWad(); uint last = end; uint i = start; while (i < last) { if (gasleft() < MIN_GAS_PER_COLLECT_PAYMENT) { break; } Subscription storage sub = subscriptions[subs[i]]; while (sub.daiCents == 0 && subs.length > 0) { uint lastIndex = subs.length.sub(1); subs[i] = subs[lastIndex]; delete(subs[lastIndex]); subs.length = lastIndex; if (last > lastIndex) { last = lastIndex; } if (lastIndex > 0) { sub = subscriptions[subs[i]]; } } if (sub.isActive && sub.daiCents != 0) { uint wholeUnpaidIntervals = calculateUnpaidIntervalsUntil(sub, now); if (wholeUnpaidIntervals > 0) { uint subscriberPayment = 0; if (wholeUnpaidIntervals >= STALE_INTERVAL_THRESHOLD) { sub.isActive = false; emit SubscriptionDeactivated(sub.subscriber, receiver); emit StaleSubscription(sub.subscriber, receiver); uint weiAmount = daiCentsToEthWei(sub.daiCents, ethPriceWad); uint authorizedBalance = allowedBalance(sub.subscriber); do { if (authorizedBalance >= weiAmount) { totalPayment = totalPayment.add(weiAmount); subscriberPayment = subscriberPayment.add(weiAmount); authorizedBalance = authorizedBalance.sub(weiAmount); emit PaymentCollected(sub.subscriber, receiver, weiAmount, sub.daiCents, sub.nextPaymentTime); sub.nextPaymentTime = calculateNextPaymentTime(sub); emit UnfundedPayment(sub.subscriber, receiver, weiAmount, sub.daiCents); } wholeUnpaidIntervals = wholeUnpaidIntervals.sub(1); } while (wholeUnpaidIntervals > 0); } if (subscriberPayment > 0) { assert(wethContract.transferFrom(sub.subscriber, receiver, subscriberPayment)); } } } i++; } emit ReceiverPaymentsCollected(receiver, totalPayment, start, i); return i; }
13,069,581
./partial_match/1/0x3034eA51375738c0B25beA8357a21Bec90d863bA/sources/YBASEPresale.sol
solium-disable-next-line
function claim() public { require(block.timestamp > ends, "presale has not yet ended"); require(claimable[msg.sender] > 0, "nothing to claim"); uint256 amount = claimable[msg.sender]; claimable[msg.sender] = 0; totalOwed = totalOwed.sub(amount); require(token.transfer(msg.sender, amount), "failed to claim"); }
2,862,770
pragma solidity ^0.4.24; // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/TxRegistry.sol /** * @title Transaction Registry for Customer * @dev Registry of customer's payments for MCW and payments for KWh. */ contract TxRegistry is Ownable { address public customer; // @dev Structure for TX data struct TxData { uint256 amountMCW; uint256 amountKWh; uint256 timestampPaymentMCW; bytes32 txPaymentKWh; uint256 timestampPaymentKWh; } // @dev Customer's Tx of payment for MCW registry mapping (bytes32 => TxData) private txRegistry; // @dev Customer's list of Tx bytes32[] private txIndex; /** * @dev Constructor * @param _customer the address of a customer for whom the TxRegistry contract is creating */ constructor(address _customer) public { customer = _customer; } /** * @dev Owner can add a new Tx of payment for MCW to the customer's TxRegistry * @param _txPaymentForMCW the Tx of payment for MCW which will be added * @param _amountMCW the amount of MCW tokens which will be recorded to the new Tx * @param _amountKWh the amount of KWh which will be recorded to the new Tx * @param _timestamp the timestamp of payment for MCW which will be recorded to the new Tx */ function addTxToRegistry( bytes32 _txPaymentForMCW, uint256 _amountMCW, uint256 _amountKWh, uint256 _timestamp ) public onlyOwner returns(bool) { require(_txPaymentForMCW != 0 && _amountMCW != 0 && _amountKWh != 0 && _timestamp != 0); require(txRegistry[_txPaymentForMCW].timestampPaymentMCW == 0); txRegistry[_txPaymentForMCW].amountMCW = _amountMCW; txRegistry[_txPaymentForMCW].amountKWh = _amountKWh; txRegistry[_txPaymentForMCW].timestampPaymentMCW = _timestamp; txIndex.push(_txPaymentForMCW); return true; } /** * @dev Owner can mark a customer's Tx of payment for MCW as spent * @param _txPaymentForMCW the Tx of payment for MCW which will be marked as spent * @param _txPaymentForKWh the additional Tx of payment for KWh which will be recorded to the original Tx as proof of spend * @param _timestamp the timestamp of payment for KWh which will be recorded to the Tx */ function setTxAsSpent(bytes32 _txPaymentForMCW, bytes32 _txPaymentForKWh, uint256 _timestamp) public onlyOwner returns(bool) { require(_txPaymentForMCW != 0 && _txPaymentForKWh != 0 && _timestamp != 0); require(txRegistry[_txPaymentForMCW].timestampPaymentMCW != 0); require(txRegistry[_txPaymentForMCW].timestampPaymentKWh == 0); txRegistry[_txPaymentForMCW].txPaymentKWh = _txPaymentForKWh; txRegistry[_txPaymentForMCW].timestampPaymentKWh = _timestamp; return true; } /** * @dev Get the customer's Tx of payment for MCW amount */ function getTxCount() public view returns(uint256) { return txIndex.length; } /** * @dev Get the customer's Tx of payment for MCW from customer's Tx list by index * @param _index the index of a customer's Tx of payment for MCW in the customer's Tx list */ function getTxAtIndex(uint256 _index) public view returns(bytes32) { return txIndex[_index]; } /** * @dev Get the customer's Tx of payment for MCW data - amount of MCW tokens which is recorded in the Tx * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getTxAmountMCW(bytes32 _txPaymentForMCW) public view returns(uint256) { return txRegistry[_txPaymentForMCW].amountMCW; } /** * @dev Get the customer's Tx of payment for MCW data - amount of KWh which is recorded in the Tx * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getTxAmountKWh(bytes32 _txPaymentForMCW) public view returns(uint256) { return txRegistry[_txPaymentForMCW].amountKWh; } /** * @dev Get the customer's Tx of payment for MCW data - timestamp of payment for MCW which is recorded in the Tx * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getTxTimestampPaymentMCW(bytes32 _txPaymentForMCW) public view returns(uint256) { return txRegistry[_txPaymentForMCW].timestampPaymentMCW; } /** * @dev Get the customer's Tx of payment for MCW data - Tx of payment for KWh which is recorded in the Tx * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getTxPaymentKWh(bytes32 _txPaymentForMCW) public view returns(bytes32) { return txRegistry[_txPaymentForMCW].txPaymentKWh; } /** * @dev Get the customer's Tx of payment for MCW data - timestamp of payment for KWh which is recorded in the Tx * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getTxTimestampPaymentKWh(bytes32 _txPaymentForMCW) public view returns(uint256) { return txRegistry[_txPaymentForMCW].timestampPaymentKWh; } /** * @dev Check the customer's Tx of payment for MCW * @param _txPaymentForMCW the Tx of payment for MCW which need to be checked */ function isValidTxPaymentForMCW(bytes32 _txPaymentForMCW) public view returns(bool) { bool isValid = false; if (txRegistry[_txPaymentForMCW].timestampPaymentMCW != 0) { isValid = true; } return isValid; } /** * @dev Check if the customer's Tx of payment for MCW is spent * @param _txPaymentForMCW the Tx of payment for MCW which need to be checked */ function isSpentTxPaymentForMCW(bytes32 _txPaymentForMCW) public view returns(bool) { bool isSpent = false; if (txRegistry[_txPaymentForMCW].timestampPaymentKWh != 0) { isSpent = true; } return isSpent; } /** * @dev Check the customer's Tx of payment for KWh * @param _txPaymentForKWh the Tx of payment for KWh which need to be checked */ function isValidTxPaymentForKWh(bytes32 _txPaymentForKWh) public view returns(bool) { bool isValid = false; for (uint256 i = 0; i < getTxCount(); i++) { if (txRegistry[getTxAtIndex(i)].txPaymentKWh == _txPaymentForKWh) { isValid = true; break; } } return isValid; } /** * @dev Get the customer's Tx of payment for MCW by Tx payment for KWh * @param _txPaymentForKWh the Tx of payment for KWh */ function getTxPaymentMCW(bytes32 _txPaymentForKWh) public view returns(bytes32) { bytes32 txMCW = 0; for (uint256 i = 0; i < getTxCount(); i++) { if (txRegistry[getTxAtIndex(i)].txPaymentKWh == _txPaymentForKWh) { txMCW = getTxAtIndex(i); break; } } return txMCW; } } // File: contracts/McwCustomerRegistry.sol /** * @title Customers Registry * @dev Registry of all customers */ contract McwCustomerRegistry is Ownable { // @dev Key: address of customer wallet, Value: address of customer TxRegistry contract mapping (address => address) private registry; // @dev Customers list address[] private customerIndex; // @dev Events for dashboard event NewCustomer(address indexed customer, address indexed txRegistry); event NewCustomerTx(address indexed customer, bytes32 txPaymentForMCW, uint256 amountMCW, uint256 amountKWh, uint256 timestamp); event SpendCustomerTx(address indexed customer, bytes32 txPaymentForMCW, bytes32 txPaymentForKWh, uint256 timestamp); // @dev Constructor constructor() public {} /** * @dev Owner can add a new customer to registry * @dev Creates a related TxRegistry contract for the new customer * @dev Related event will be generated * @param _customer the address of a new customer to add */ function addCustomerToRegistry(address _customer) public onlyOwner returns(bool) { require(_customer != address(0)); require(registry[_customer] == address(0)); address txRegistry = new TxRegistry(_customer); registry[_customer] = txRegistry; customerIndex.push(_customer); emit NewCustomer(_customer, txRegistry); return true; } /** * @dev Owner can add a new Tx of payment for MCW to the customer's TxRegistry * @dev Generates the Tx of payment for MCW (hash as proof of payment) and writes the Tx data to the customer's TxRegistry * @dev Related event will be generated * @param _customer the address of a customer to whom to add a new Tx * @param _amountMCW the amount of MCW tokens which will be recorded to the new Tx * @param _amountKWh the amount of KWh which will be recorded to the new Tx */ function addTxToCustomerRegistry(address _customer, uint256 _amountMCW, uint256 _amountKWh) public onlyOwner returns(bool) { require(isValidCustomer(_customer)); require(_amountMCW != 0 && _amountKWh != 0); uint256 timestamp = now; bytes32 txPaymentForMCW = keccak256( abi.encodePacked( _customer, _amountMCW, _amountKWh, timestamp) ); TxRegistry txRegistry = TxRegistry(registry[_customer]); require(txRegistry.getTxTimestampPaymentMCW(txPaymentForMCW) == 0); if (!txRegistry.addTxToRegistry( txPaymentForMCW, _amountMCW, _amountKWh, timestamp)) revert (); emit NewCustomerTx( _customer, txPaymentForMCW, _amountMCW, _amountKWh, timestamp); return true; } /** * @dev Owner can mark a customer's Tx of payment for MCW as spent * @dev Generates an additional Tx of paymant for KWh (hash as proof of spend), which connected to the original Tx. * @dev Related event will be generated * @param _customer the address of a customer to whom to spend a Tx * @param _txPaymentForMCW the Tx of payment for MCW which will be marked as spent */ function setCustomerTxAsSpent(address _customer, bytes32 _txPaymentForMCW) public onlyOwner returns(bool) { require(isValidCustomer(_customer)); TxRegistry txRegistry = TxRegistry(registry[_customer]); require(txRegistry.getTxTimestampPaymentMCW(_txPaymentForMCW) != 0); require(txRegistry.getTxTimestampPaymentKWh(_txPaymentForMCW) == 0); uint256 timestamp = now; bytes32 txPaymentForKWh = keccak256( abi.encodePacked( _txPaymentForMCW, timestamp) ); if (!txRegistry.setTxAsSpent(_txPaymentForMCW, txPaymentForKWh, timestamp)) revert (); emit SpendCustomerTx( _customer, _txPaymentForMCW, txPaymentForKWh, timestamp); return true; } /** * @dev Get the current amount of customers */ function getCustomerCount() public view returns(uint256) { return customerIndex.length; } /** * @dev Get the customer's address from customers list by index * @param _index the index of a customer in the customers list */ function getCustomerAtIndex(uint256 _index) public view returns(address) { return customerIndex[_index]; } /** * @dev Get the customer's TxRegistry contract * @param _customer the address of a customer for whom to get TxRegistry contract */ function getCustomerTxRegistry(address _customer) public view returns(address) { return registry[_customer]; } /** * @dev Check the customer's address * @param _customer the address of a customer which need to be checked */ function isValidCustomer(address _customer) public view returns(bool) { require(_customer != address(0)); bool isValid = false; address txRegistry = registry[_customer]; if (txRegistry != address(0)) { isValid = true; } return isValid; } // wrappers on TxRegistry contract /** * @dev Get the customer's Tx of payment for MCW amount * @param _customer the address of a customer for whom to get */ function getCustomerTxCount(address _customer) public view returns(uint256) { require(isValidCustomer(_customer)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 txCount = txRegistry.getTxCount(); return txCount; } /** * @dev Get the customer's Tx of payment for MCW from customer's Tx list by index * @param _customer the address of a customer for whom to get * @param _index the index of a customer's Tx of payment for MCW in the customer's Tx list */ function getCustomerTxAtIndex(address _customer, uint256 _index) public view returns(bytes32) { require(isValidCustomer(_customer)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bytes32 txIndex = txRegistry.getTxAtIndex(_index); return txIndex; } /** * @dev Get the customer's Tx of payment for MCW data - amount of MCW tokens which is recorded in the Tx * @param _customer the address of a customer for whom to get * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getCustomerTxAmountMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 amountMCW = txRegistry.getTxAmountMCW(_txPaymentForMCW); return amountMCW; } /** * @dev Get the customer's Tx of payment for MCW data - amount of KWh which is recorded in the Tx * @param _customer the address of a customer for whom to get * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getCustomerTxAmountKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 amountKWh = txRegistry.getTxAmountKWh(_txPaymentForMCW); return amountKWh; } /** * @dev Get the customer's Tx of payment for MCW data - timestamp of payment for MCW which is recorded in the Tx * @param _customer the address of a customer for whom to get * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getCustomerTxTimestampPaymentMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 timestampPaymentMCW = txRegistry.getTxTimestampPaymentMCW(_txPaymentForMCW); return timestampPaymentMCW; } /** * @dev Get the customer's Tx of payment for MCW data - Tx of payment for KWh which is recorded in the Tx * @param _customer the address of a customer for whom to get * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getCustomerTxPaymentKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(bytes32) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bytes32 txPaymentKWh = txRegistry.getTxPaymentKWh(_txPaymentForMCW); return txPaymentKWh; } /** * @dev Get the customer's Tx of payment for MCW data - timestamp of payment for KWh which is recorded in the Tx * @param _customer the address of a customer for whom to get * @param _txPaymentForMCW the Tx of payment for MCW for which to get data */ function getCustomerTxTimestampPaymentKWh(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 timestampPaymentKWh = txRegistry.getTxTimestampPaymentKWh(_txPaymentForMCW); return timestampPaymentKWh; } /** * @dev Check the customer's Tx of payment for MCW * @param _customer the address of a customer for whom to check * @param _txPaymentForMCW the Tx of payment for MCW which need to be checked */ function isValidCustomerTxPaymentForMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(bool) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bool isValid = txRegistry.isValidTxPaymentForMCW(_txPaymentForMCW); return isValid; } /** * @dev Check if the customer's Tx of payment for MCW is spent * @param _customer the address of a customer for whom to check * @param _txPaymentForMCW the Tx of payment for MCW which need to be checked */ function isSpentCustomerTxPaymentForMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(bool) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bool isSpent = txRegistry.isSpentTxPaymentForMCW(_txPaymentForMCW); return isSpent; } /** * @dev Check the customer's Tx of payment for KWh * @param _customer the address of a customer for whom to check * @param _txPaymentForKWh the Tx of payment for KWh which need to be checked */ function isValidCustomerTxPaymentForKWh(address _customer, bytes32 _txPaymentForKWh) public view returns(bool) { require(isValidCustomer(_customer)); require(_txPaymentForKWh != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bool isValid = txRegistry.isValidTxPaymentForKWh(_txPaymentForKWh); return isValid; } /** * @dev Get the customer's Tx of payment for MCW by Tx payment for KWh * @param _customer the address of a customer for whom to get * @param _txPaymentForKWh the Tx of payment for KWh */ function getCustomerTxPaymentMCW(address _customer, bytes32 _txPaymentForKWh) public view returns(bytes32) { require(isValidCustomer(_customer)); require(_txPaymentForKWh != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); bytes32 txMCW = txRegistry.getTxPaymentMCW(_txPaymentForKWh); return txMCW; } }
Get the customer's Tx of payment for MCW data - amount of MCW tokens which is recorded in the Tx _customer the address of a customer for whom to get _txPaymentForMCW the Tx of payment for MCW for which to get data/
function getCustomerTxAmountMCW(address _customer, bytes32 _txPaymentForMCW) public view returns(uint256) { require(isValidCustomer(_customer)); require(_txPaymentForMCW != bytes32(0)); TxRegistry txRegistry = TxRegistry(registry[_customer]); uint256 amountMCW = txRegistry.getTxAmountMCW(_txPaymentForMCW); return amountMCW; }
10,313,146
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; } }
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); return 0; } return 0; } return 0; } }
12,816,421
pragma solidity ^0.4.24; import "./Owned.sol"; import "./Stash.sol"; import "./StashFactory.sol"; import "./RedeemAgent.sol"; import "./PledgeAgent.sol"; contract Bank is Owned {// Regulator node (MAS) should be the owner function Bank() { owner = msg.sender; } StashFactory public sf; RedeemAgent public redeemAgent; PledgeAgent public pledgeAgent; function setExternalContracts(address _sf, address _pa, address _ra) onlyOwner { sf = StashFactory(_sf); pledgeAgent = PledgeAgent(_pa); redeemAgent = RedeemAgent(_ra); } /* salt tracking */ bytes16 public currentSalt; // used to retrieve shielded balance bytes16 public nettingSalt; // used to cache result salt after LSM calculation mapping(address => bytes32) public acc2stash; // @pseudo-public function registerStash(address _acc, string _stashName) onlyOwner { _registerStash(_acc, stringToBytes32(_stashName)); } function _registerStash(address _acc, bytes32 _stashName) onlyOwner { acc2stash[_acc] = _stashName; } function getStash(address _acc) view returns (string){ return bytes32ToString(_getStash(_acc)); } function _getStash(address _acc) view returns (bytes32){ return acc2stash[_acc]; } /* @pseudo-public during LSM / confirming pmt: banks and cb will call this to set their current salt @private for: [pledger] during pledge / redeem: MAS-regulator / cb will invoke this function */ function setCurrentSalt(bytes16 _salt) { bytes32 _stashName = acc2stash[msg.sender]; require(checkOwnedStash(_stashName), "not owned stash"); // non-owner will not update salt if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator } else { require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt } currentSalt = _salt; } /* @pseudo-public */ function setNettingSalt(bytes16 _salt) { bytes32 _stashName = acc2stash[msg.sender]; require(checkOwnedStash(_stashName), "not owned stash"); // non-owner will not update salt if (acc2stash[msg.sender] != centralBank) {// when banks are setting salt, cb should not update its salt require(msg.sender == owner || !isCentralBankNode()); // unless it invoked by MAS-regulator } else { require(isCentralBankNode()); // when cb are setting salt, banks should not update its salt } nettingSalt = _salt; } function updateCurrentSalt2NettingSalt() external { currentSalt = nettingSalt; } function updateCurrentSalt(bytes16 salt) external { currentSalt = salt; } // @pseudo-public, all the banks besides cb will not execute this action function setCentralBankCurrentSalt(bytes16 _salt) onlyCentralBank { if (isCentralBankNode()) { currentSalt = _salt; } } function getCurrentSalt() view returns (bytes16) { require(msg.sender == owner || checkOwnedStash(acc2stash[msg.sender])); return currentSalt; } /* set up central bank */ bytes32 public centralBank; function setCentralBank(bytes32 _stashName) onlyOwner { centralBank = _stashName; } modifier onlyCentralBank() {require(acc2stash[msg.sender] == centralBank); _;} /* Suspend bank / stash */ mapping(bytes32 => bool) public suspended; function suspendStash(bytes32 _stashName) onlyOwner { suspended[_stashName] = true; } function unSuspendStash(bytes32 _stashName) onlyOwner { suspended[_stashName] = false; } function isSuspended(bytes32 _stashName) external returns (bool){ return suspended[_stashName]; } //modifier notSuspended(bytes32 _stashName) { require(suspended[_stashName] == false); _; } event statusCode(int errorCode); // statusCode added to handle returns upon exceptions - Laks function emitStatusCode(int errorCode){ emit statusCode(errorCode); } // workaround to handle exception as require/throw do not return errors - need to refactor - Laks modifier notSuspended(bytes32 _stashName) { if (suspended[_stashName]) { emitStatusCode(100); return; } _; } /* @live: privateFor == MAS and owner node This method is set to onlyonwer as pledge include off-chain process */ function pledge(bytes32 _txRef, bytes32 _stashName, int _amount) // onlyCentralBank notSuspended(_stashName) { if (_stashName != centralBank || isCentralBankNode()) { sf.credit(_stashName, _amount); pledgeAgent.pledge(_txRef, _stashName, _amount); } } /* @live: privateFor = MAS and owner node */ function redeem(bytes32 _txRef, bytes32 _stashName, int _amount) //onlyCentralBank notSuspended(_stashName) { if (_stashName != centralBank || isCentralBankNode()) { sf.debit(_stashName, _amount); redeemAgent.redeem(_txRef, _stashName, _amount); } } function checkOwnedStash(bytes32 _stashName) view private returns (bool){ return sf.checkOwnedStash(_stashName, msg.sender); } function getOwnedStash() view returns (bytes32) { if (isCentralBankNode()) return centralBank; return sf.getOwnedStash(); } // Central bank controls all the stashes function isCentralBankNode() view returns (bool) { return sf.isCentralBankNode(); } function clear() external { } }
@pseudo-public / non-owner will not update salt unless it invoked by MAS-regulator when cb are setting salt, banks should not update its salt
function setNettingSalt(bytes16 _salt) { bytes32 _stashName = acc2stash[msg.sender]; require(checkOwnedStash(_stashName), "not owned stash"); require(msg.sender == owner || !isCentralBankNode()); require(isCentralBankNode()); } else { }
13,102,802
./partial_match/1/0x75Be69fc0859874E722D97a7f464D402e3dCff58/sources/contracts/standards/HONEYCOMBS721.sol
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./ Check that tokenId was not transferred by `_beforeTokenTransfer` hook `_balances[from]` cannot overflow for the same reason as described in `_burn`: `from`'s balance is the number of token held, which is at least one before the current transfer. `_balances[to]` could overflow in the conditions described in `_mint`. That would require all 2256 token ids to be minted, which in practice is impossible.
function _transfer(address from, address to, uint256 tokenId) internal virtual { if (HONEYCOMBS721.ownerOf(tokenId) != from) { revert ERC721__InvalidOwner(); } if (to == address(0)) { revert ERC721__TransferToZero(); } _beforeTokenTransfer(from, to, tokenId, 1); if (HONEYCOMBS721.ownerOf(tokenId) != from) { revert ERC721__InvalidOwner(); } unchecked { _balances[from] -= 1; _balances[to] += 1; } _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId, 1); }
3,888,214
/* solium-disable security/no-inline-assembly */ pragma solidity ^0.6.3; contract Doppelganger { struct MockCall { bool initialized; bool reverts; string revertReason; bytes returnValue; } mapping(bytes32 => MockCall) mockConfig; fallback() external payable { MockCall storage mockCall = __internal__getMockCall(); if (mockCall.reverts == true) { __internal__mockRevert(mockCall.revertReason); return; } __internal__mockReturn(mockCall.returnValue); } function __waffle__mockReverts(bytes memory data, string memory reason) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: true, revertReason: reason, returnValue: "" }); } function __waffle__mockReturns(bytes memory data, bytes memory value) public { mockConfig[keccak256(data)] = MockCall({ initialized: true, reverts: false, revertReason: "", returnValue: value }); } function __waffle__call(address target, bytes calldata data) external returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.call(data); require(succeeded, string(returnValue)); return returnValue; } function __waffle__staticcall(address target, bytes calldata data) external view returns (bytes memory) { (bool succeeded, bytes memory returnValue) = target.staticcall(data); require(succeeded, string(returnValue)); return returnValue; } function __internal__getMockCall() view private returns (MockCall storage mockCall) { mockCall = mockConfig[keccak256(msg.data)]; if (mockCall.initialized == true) { // Mock method with specified arguments return mockCall; } mockCall = mockConfig[keccak256(abi.encodePacked(msg.sig))]; if (mockCall.initialized == true) { // Mock method with any arguments return mockCall; } revert("Mock on the method is not initialized"); } function __internal__mockReturn(bytes memory ret) pure private { assembly { return (add(ret, 0x20), mload(ret)) } } function __internal__mockRevert(string memory reason) pure private { revert(reason); } }
Mock method with specified arguments Mock method with any arguments
function __internal__getMockCall() view private returns (MockCall storage mockCall) { mockCall = mockConfig[keccak256(msg.data)]; if (mockCall.initialized == true) { return mockCall; } mockCall = mockConfig[keccak256(abi.encodePacked(msg.sig))]; if (mockCall.initialized == true) { return mockCall; } revert("Mock on the method is not initialized"); }
6,380,055
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.3.2 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.3.2 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.3.2 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol // OpenZeppelin Contracts v4.3.2 (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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.3.2 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.3.2 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.3.2 (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); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts v4.3.2 (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: * * - `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 {} } // File: bubblez.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Bubblez is ERC20, Ownable { /* Written by: 0xInuarashi Discord: 0xInuarashi#1234 Twitter: https://twitter.com/0xinuarashi $BUBBLEZ ERC20 Token Yield Contract Features: - Minting of 100,000 $BUBBLEZ to Treasury [] - Transfer-Hook Token Yield with Bubble Budz Genesis Contract (interfaced) [] - Migration Reward Minting of 140 $BUBBLEZ to Migrators (interfaced) [] - Interaction by Controllers (interfaced) [] */ using SafeMath for uint; // // BUBBLEZ ERC20 Variables // Limits // uint public maxBubblez = 1926000 ether; uint public bubblezPerDay = 10 ether; uint public bubblezPerMigration = 140 ether; uint public bubblezForTreasury = 100000 ether; // Times uint public yieldStartTime = 1636243200; uint public yieldEndTime = 1794009600; uint internal secondsInDay = 86400; // Bubble Budz Genesis Interface address public bubbleBudzGenesisAddress; IERC721 public BubbleBudzGenesis; function setBubbleBudzGenesis(address address_) external onlyOwner { bubbleBudzGenesisAddress = address_; BubbleBudzGenesis = IERC721(address_); } // Controller Interface address public bubblezControllerAddress; function setBubblezController(address address_) external onlyOwner { bubblezControllerAddress = address_; } address public bubblezControllerAddress2; function setBubblezController2(address address_) external onlyOwner { bubblezControllerAddress2 = address_; } // Mappings for Yield mapping(address => uint) public pendingRewards; mapping(address => uint) public lastUpdatedTime; // Events event Migrated(address indexed to_, uint amount_); event Claimed(address indexed to_, uint amount_); // Constructor constructor() payable ERC20("Bubblez", "BUBBLEZ") { _mint(msg.sender, bubblezForTreasury); emit Claimed(msg.sender, bubblezForTreasury); } // Modifiers modifier onlySender { require(msg.sender == tx.origin, "No Smart Contracts!"); _; } modifier onlyBubbleBudzGenesis { require(msg.sender == bubbleBudzGenesisAddress, "You are not Bubble Budz Genesis!"); _; } modifier onlyBubblezControllers { require(msg.sender == bubbleBudzGenesisAddress || msg.sender == bubblezControllerAddress || msg.sender == bubblezControllerAddress2, "You are not a Bubble Budz Controller!"); _; } // Internal Functions function __getSmallerValue(uint a_, uint b_) internal pure returns (uint) { return a_ < b_ ? a_ : b_; } // function __calculateYieldReward(uint erc721Balance_, uint time_, uint lastUpdate_) internal view returns (uint) { // // (1 * (100000 * (165455 - 165400))) / 86400 // // return (erc721Balance_ * (bubblezPerDay * (time_ - lastUpdate_))) / secondsInDay; // return erc721Balance_.mul(bubblezPerDay.mul((time_.sub(lastUpdate_)))).div(secondsInDay); // } function __calculateYieldReward(address address_) internal view returns (uint) { uint _erc721Balance = BubbleBudzGenesis.balanceOf(address_); uint _time = __getSmallerValue(block.timestamp, yieldEndTime); uint _lastUpdate = lastUpdatedTime[address_]; if (_lastUpdate > yieldStartTime) { return _erc721Balance.mul(bubblezPerDay.mul((_time.sub(_lastUpdate)))).div(secondsInDay); } else { return 0; } } function __updateYieldReward(address address_) internal { uint _time = __getSmallerValue(block.timestamp, yieldEndTime); uint _lastUpdate = lastUpdatedTime[address_]; if (_lastUpdate > 0) { pendingRewards[address_] = pendingRewards[address_].add(__calculateYieldReward(address_)); } if (_lastUpdate != yieldEndTime) { lastUpdatedTime[address_] = _time; } } function __claimYieldReward(address address_) internal { uint _pendingRewards = pendingRewards[address_]; if (_pendingRewards > 0) { pendingRewards[address_] = 0; _mint(address_, _pendingRewards); emit Claimed(address_, _pendingRewards); } } ///////////////////// BUBBLEZ Functions //////////////////////// // Migration function mintMigrationReward(address to_) public onlyBubbleBudzGenesis { // Note: Only the Bubble Budz Genesis Contract can invoke this function. We don't want any random contract to be able to mint our migration reward! _mint(to_, bubblezPerMigration); emit Migrated(to_, bubblezPerMigration); } // Update Yield function updateReward(address address_) public { // Note: this can be called by anyone __updateYieldReward(address_); } function updateRewardForSelf() public { __updateYieldReward(msg.sender); } function updateRewardOnTransfer(address from_, address to_) public onlyBubbleBudzGenesis { // Note: this is called only on a transfer hook of Bubble Budz Genesis __updateYieldReward(from_); __updateYieldReward(to_); } // Claim Tokens function claimTokens(address claimer_) public { __updateYieldReward(claimer_); __claimYieldReward(claimer_); } function claimTokensForSelf() public { __updateYieldReward(msg.sender); __claimYieldReward(msg.sender); } // Burn Tokens function burn(address from_, uint amount_) public onlyBubblezControllers { _burn(from_, amount_); } // View Functions function getStorageClaimableTokens(address address_) public view returns (uint) { return pendingRewards[address_]; } function getPendingClaimableTokens(address address_) public view returns (uint) { return __calculateYieldReward(address_); } function getTotalClaimableTokens(address address_) public view returns (uint) { return pendingRewards[address_].add(__calculateYieldReward(address_)); } }
BUBBLEZ Functions Migration Note: Only the Bubble Budz Genesis Contract can invoke this function. We don't want any random contract to be able to mint our migration reward!
function mintMigrationReward(address to_) public onlyBubbleBudzGenesis { _mint(to_, bubblezPerMigration); emit Migrated(to_, bubblezPerMigration); }
11,779,147
pragma solidity ^0.4.12; import './zeppelin/math/SafeMath.sol'; import './zeppelin/token/StandardToken.sol'; contract BurnableToken is StandardToken { using SafeMath for uint256; event Burn(address indexed from, uint256 amount); event BurnRewardIncreased(address indexed from, uint256 value); /** * @dev Sending ether to contract increases burning reward */ function() payable { if(msg.value > 0){ BurnRewardIncreased(msg.sender, msg.value); } } /** * @dev Calculates how much ether one will receive in reward for burning tokens * @param _amount of tokens to be burned */ function burnReward(uint256 _amount) public constant returns(uint256){ return this.balance.mul(_amount).div(totalSupply); } /** * @dev Burns tokens and send reward * This is internal function because it DOES NOT check * if _from has allowance to burn tokens. * It is intended to be used in transfer() and transferFrom() which do this check. * @param _from The address which you want to burn tokens from * @param _amount of tokens to be burned */ function burn(address _from, uint256 _amount) internal returns(bool){ require(balances[_from] >= _amount); uint256 reward = burnReward(_amount); assert(this.balance - reward > 0); balances[_from] = balances[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); //assert(totalSupply >= 0); //Check is not needed because totalSupply.sub(value) will already throw if this condition is not met _from.transfer(reward); Burn(_from, _amount); return true; } /** * @dev Transfers or burns tokens * Burns tokens transferred to this contract itself or to zero address * @param _to The address to transfer to or token contract address to burn. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { if( (_to == address(this)) || (_to == 0) ){ return burn(msg.sender, _value); }else{ return super.transfer(_to, _value); } } /** * @dev Transfer tokens from one address to another * or burns them if _to is this contract or zero address * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { if( (_to == address(this)) || (_to == 0) ){ var _allowance = allowed[_from][msg.sender]; //require (_value <= _allowance); //Check is not needed because _allowance.sub(_value) will already throw if this condition is not met allowed[_from][msg.sender] = _allowance.sub(_value); return burn(_from, _value); }else{ return super.transferFrom(_from, _to, _value); } } }
Burns tokens and send reward This is internal function because it DOES NOT check if _from has allowance to burn tokens. It is intended to be used in transfer() and transferFrom() which do this check. _from The address which you want to burn tokens from _amount of tokens to be burned/assert(totalSupply >= 0); Check is not needed because totalSupply.sub(value) will already throw if this condition is not met
function burn(address _from, uint256 _amount) internal returns(bool){ require(balances[_from] >= _amount); uint256 reward = burnReward(_amount); assert(this.balance - reward > 0); balances[_from] = balances[_from].sub(_amount); totalSupply = totalSupply.sub(_amount); _from.transfer(reward); Burn(_from, _amount); return true; }
1,082,620
pragma solidity ^0.4.20; contract CutieCoreInterface { function isCutieCore() pure public returns (bool); function transferFrom(address _from, address _to, uint256 _cutieId) external; function transfer(address _to, uint256 _cutieId) external; function ownerOf(uint256 _cutieId) external view returns (address owner); function getCutie(uint40 _id) external view returns ( uint256 genes, uint40 birthTime, uint40 cooldownEndTime, uint40 momId, uint40 dadId, uint16 cooldownIndex, uint16 generation ); function getGenes(uint40 _id) public view returns ( uint256 genes ); function getCooldownEndTime(uint40 _id) public view returns ( uint40 cooldownEndTime ); function getCooldownIndex(uint40 _id) public view returns ( uint16 cooldownIndex ); function getGeneration(uint40 _id) public view returns ( uint16 generation ); function getOptional(uint40 _id) public view returns ( uint64 optional ); function changeGenes( uint40 _cutieId, uint256 _genes) public; function changeCooldownEndTime( uint40 _cutieId, uint40 _cooldownEndTime) public; function changeCooldownIndex( uint40 _cutieId, uint16 _cooldownIndex) public; function changeOptional( uint40 _cutieId, uint64 _optional) public; function changeGeneration( uint40 _cutieId, uint16 _generation) public; } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract MarketInterface { function withdrawEthFromBalance() external; function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public payable; function bid(uint40 _cutieId) public payable; } /// @title Auction Market for Blockchain Cuties. /// @author https://BlockChainArchitect.io contract Market is MarketInterface, Pausable { // Shows the auction on an Cutie Token struct Auction { // Price (in wei) at the beginning of auction uint128 startPrice; // Price (in wei) at the end of auction uint128 endPrice; // Current owner of Token address seller; // Auction duration in seconds uint40 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint40 startedAt; } // Reference to contract that tracks ownership CutieCoreInterface public coreContract; // Cut owner takes on each auction, in basis points - 1/100 of a per cent. // Values 0-10,000 map to 0%-100% uint16 public ownerFee; // Map from token ID to their corresponding auction. mapping (uint40 => Auction) cutieIdToAuction; event AuctionCreated(uint40 cutieId, uint128 startPrice, uint128 endPrice, uint40 duration, uint256 fee); event AuctionSuccessful(uint40 cutieId, uint128 totalPrice, address winner); event AuctionCancelled(uint40 cutieId); /// @dev disables sending fund to this contract function() external {} modifier canBeStoredIn128Bits(uint256 _value) { require(_value <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); _; } // @dev Adds to the list of open auctions and fires the // AuctionCreated event. // @param _cutieId The token ID is to be put on auction. // @param _auction To add an auction. // @param _fee Amount of money to feature auction function _addAuction(uint40 _cutieId, Auction _auction, uint256 _fee) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); cutieIdToAuction[_cutieId] = _auction; emit AuctionCreated( _cutieId, _auction.startPrice, _auction.endPrice, _auction.duration, _fee ); } // @dev Returns true if the token is claimed by the claimant. // @param _claimant - Address claiming to own the token. function _isOwner(address _claimant, uint256 _cutieId) internal view returns (bool) { return (coreContract.ownerOf(_cutieId) == _claimant); } // @dev Transfers the token owned by this contract to another address. // Returns true when the transfer succeeds. // @param _receiver - Address to transfer token to. // @param _cutieId - Token ID to transfer. function _transfer(address _receiver, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transfer(_receiver, _cutieId); } // @dev Escrows the token and assigns ownership to this contract. // Throws if the escrow fails. // @param _owner - Current owner address of token to escrow. // @param _cutieId - Token ID the approval of which is to be verified. function _escrow(address _owner, uint40 _cutieId) internal { // it will throw if transfer fails coreContract.transferFrom(_owner, this, _cutieId); } // @dev just cancel auction. function _cancelActiveAuction(uint40 _cutieId, address _seller) internal { _removeAuction(_cutieId); _transfer(_seller, _cutieId); emit AuctionCancelled(_cutieId); } // @dev Calculates the price and transfers winnings. // Does not transfer token ownership. function _bid(uint40 _cutieId, uint128 _bidAmount) internal returns (uint128) { // Get a reference to the auction struct Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); // Check that bid > current price uint128 price = _currentPrice(auction); require(_bidAmount >= price); // Provide a reference to the seller before the auction struct is deleted. address seller = auction.seller; _removeAuction(_cutieId); // Transfer proceeds to seller (if there are any!) if (price > 0) { uint128 fee = _computeFee(price); uint128 sellerValue = price - fee; seller.transfer(sellerValue); } emit AuctionSuccessful(_cutieId, price, msg.sender); return price; } // @dev Removes from the list of open auctions. // @param _cutieId - ID of token on auction. function _removeAuction(uint40 _cutieId) internal { delete cutieIdToAuction[_cutieId]; } // @dev Returns true if the token is on auction. // @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } // @dev calculate current price of auction. // When testing, make this function public and turn on // `Current price calculation` test suite. function _computeCurrentPrice( uint128 _startPrice, uint128 _endPrice, uint40 _duration, uint40 _secondsPassed ) internal pure returns (uint128) { if (_secondsPassed >= _duration) { return _endPrice; } else { int256 totalPriceChange = int256(_endPrice) - int256(_startPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); uint128 currentPrice = _startPrice + uint128(currentPriceChange); return currentPrice; } } // @dev return current price of token. function _currentPrice(Auction storage _auction) internal view returns (uint128) { uint40 secondsPassed = 0; uint40 timeNow = uint40(now); if (timeNow > _auction.startedAt) { secondsPassed = timeNow - _auction.startedAt; } return _computeCurrentPrice( _auction.startPrice, _auction.endPrice, _auction.duration, secondsPassed ); } // @dev Calculates owner's cut of a sale. // @param _price - Sale price of cutie. function _computeFee(uint128 _price) internal view returns (uint128) { return _price * ownerFee / 10000; } // @dev Remove all Ether from the contract with the owner's cuts. Also, remove any Ether sent directly to the contract address. // Transfers to the token contract, but can be called by // the owner or the token contract. function withdrawEthFromBalance() external { address coreAddress = address(coreContract); require( msg.sender == owner || msg.sender == coreAddress ); coreAddress.transfer(address(this).balance); } // @dev create and begin new auction. function createAuction(uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller) public whenNotPaused payable { require(_isOwner(msg.sender, _cutieId)); _escrow(msg.sender, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now) ); _addAuction(_cutieId, auction, msg.value); } // @dev Set the reference to cutie ownership contract. Verify the owner's fee. // @param fee should be between 0-10,000. function setup(address _coreContractAddress, uint16 _fee) public { require(coreContract == address(0)); require(_fee <= 10000); require(msg.sender == owner); ownerFee = _fee; CutieCoreInterface candidateContract = CutieCoreInterface(_coreContractAddress); require(candidateContract.isCutieCore()); coreContract = candidateContract; } // @dev Set the owner's fee. // @param fee should be between 0-10,000. function setFee(uint16 _fee) public { require(_fee <= 10000); require(msg.sender == owner); ownerFee = _fee; } // @dev bid on auction. Complete it and transfer ownership of cutie if enough ether was given. function bid(uint40 _cutieId) public payable whenNotPaused canBeStoredIn128Bits(msg.value) { // _bid throws if something failed. _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } // @dev Returns auction info for a token on auction. // @param _cutieId - ID of token on auction. function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); } // @dev Returns the current price of an auction. function getCurrentPrice(uint40 _cutieId) public view returns (uint128) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return _currentPrice(auction); } // @dev Cancels unfinished auction and returns token to owner. // Can be called when contract is paused. function cancelActiveAuction(uint40 _cutieId) public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelActiveAuction(_cutieId, seller); } // @dev Cancels auction when contract is on pause. Option is available only to owners in urgent situations. Tokens returned to seller. // Used on Core contract upgrade. function cancelActiveAuctionWhenPaused(uint40 _cutieId) whenPaused onlyOwner public { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); _cancelActiveAuction(_cutieId, auction.seller); } } /// @title Auction market for cuties sale /// @author https://BlockChainArchitect.io contract SaleMarket is Market { // @dev Sanity check reveals that the // auction in our setSaleAuctionAddress() call is right. bool public isSaleMarket = true; // @dev create and start a new auction // @param _cutieId - ID of cutie to auction, sender must be owner. // @param _startPrice - Price of item (in wei) at the beginning of auction. // @param _endPrice - Price of item (in wei) at the end of auction. // @param _duration - Length of auction (in seconds). // @param _seller - Seller function createAuction( uint40 _cutieId, uint128 _startPrice, uint128 _endPrice, uint40 _duration, address _seller ) public payable { require(msg.sender == address(coreContract)); _escrow(_seller, _cutieId); Auction memory auction = Auction( _startPrice, _endPrice, _seller, _duration, uint40(now) ); _addAuction(_cutieId, auction, msg.value); } // @dev LastSalePrice is updated if seller is the token contract. // Otherwise, default bid method is used. function bid(uint40 _cutieId) public payable canBeStoredIn128Bits(msg.value) { // _bid verifies token ID size _bid(_cutieId, uint128(msg.value)); _transfer(msg.sender, _cutieId); } }
Returns auction info for a token on auction. _cutieId - ID of token on auction.
function getAuctionInfo(uint40 _cutieId) public view returns ( address seller, uint128 startPrice, uint128 endPrice, uint40 duration, uint40 startedAt ) { Auction storage auction = cutieIdToAuction[_cutieId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.startedAt ); }
5,717,180
pragma solidity ^0.4.18; import "./SpaceBase.sol"; // @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens // @author Earthereum <[email protected]> (https://github.com/Earthereum) contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); } contract SpaceOwnership is SpaceBase, ERC721 { // Name and symbol of the non fungible token, as defined in ERC721. string public name = "Earthereum"; string public symbol = "ERTH"; bool public implementsERC721 = true; // Checks if a given address is the current owner of a particular planet. // _claimant the address we are validating against. // _tokenId planet id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return planetIndexToOwner[_tokenId] == _claimant; } // Checks if a given address currently has transferApproval for a particular planet. // _claimant the address we are confirming planet is approved for. // _tokenId planet id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return planetIndexToApproved[_tokenId] == _claimant; } // Marks an address as being approved for transferFrom(), overwriting any previous // approval. Setting _approved to address(0) clears all transfer approval. // NOTE: _approve() does NOT send the Approval event. This is intentional because // _approve() and transferFrom() are used together for putting planets on auction, and // there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { planetIndexToApproved[_tokenId] = _approved; } // Returns the number of planets owned by a specific address. // _owner The owner address to check. // Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } // Transfers a planet to another address. If transferring to a smart // contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or // Cryptoplanets specifically) or your planet may be lost forever. Seriously. // _to The address of the recipient, can be a user or contract. // _tokenId The ID of the planet to transfer. // Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any planets (except very briefly // after a gen0 planet is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of planets // through the allow + transferFrom flow. // require(_to != address(saleAuction)); // require(_to != address(siringAuction)); // You can only send your own planet. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } // Grant another address the right to transfer a specific planet via // transferFrom(). This is the preferred flow for transfering NFTs to contracts. // _to The address to be granted transfer approval. Pass address(0) to // clear all approvals. // _tokenId The ID of the planet that can be transferred if this call succeeds. // Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } // Transfer a planet owned by another address, for which the calling address // has previously been granted transfer approval by the owner. // _from The address that owns the planet to be transfered. // _to The address that should take ownership of the planet. Can be any address, // including the caller. // _tokenId The ID of the planet to be transferred. // Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any planets (except very briefly // after a gen0 planet is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } // Returns the total number of planets currently in existence. // Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return planets.length - 1; } // Returns the address currently assigned ownership of a given planet. // Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = planetIndexToOwner[_tokenId]; require(owner != address(0)); } // Returns a list of all planet IDs assigned to an address. // _owner The owner whose planets we are interested in. // This method MUST NEVER be called by smart contract code. First, it's fairly // expensive (it walks the entire planet array looking for Planets belonging to owner), // but it also returns a dynamic array, which is only supported for web3 calls, and // not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalPlanets = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all Planets have IDs starting at 1 and increasing // sequentially up to the totalplanet count. uint256 planetId; for (planetId = 1; planetId <= totalPlanets; planetId++) { if (planetIndexToOwner[planetId] == _owner) { result[resultIndex] = planetId; resultIndex++; } } return result; } } // Adapted from memcpy() by arachnid (Nick Johnson <[email protected]>) // This method is licenced under the Apache License. // Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _memcpy(uint _dest, uint _src, uint _len) private pure { // Copy word-length chunks while possible for(; _len >= 32; _len -= 32) { assembly { mstore(_dest, mload(_src)) } _dest += 32; _src += 32; } // Copy remaining bytes uint256 mask = 256 ** (32 - _len) - 1; assembly { let srcpart := and(mload(_src), not(mask)) let destpart := and(mload(_dest), mask) mstore(_dest, or(destpart, srcpart)) } } // Adapted from toString(slice) by arachnid (Nick Johnson <[email protected]>) // This method is licenced under the Apache License. // Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private pure returns (string) { var outputString = new string(_stringLength); uint256 outputPtr; uint256 bytesPtr; assembly { outputPtr := add(outputString, 32) bytesPtr := _rawBytes } _memcpy(outputPtr, bytesPtr, _stringLength); return outputString; } }
Marks an address as being approved for transferFrom(), overwriting any previous approval. Setting _approved to address(0) clears all transfer approval. NOTE: _approve() does NOT send the Approval event. This is intentional because _approve() and transferFrom() are used together for putting planets on auction, and there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal { planetIndexToApproved[_tokenId] = _approved; }
1,011,237
./full_match/1/0x61e0749C835f7Eca584DD83f93358C75712752E6/sources/browser/arb03.sol
Returns contract's ETH balance
function getETHBalance () external view returns (uint){ return address(this).balance; }
3,101,800
./partial_match/1/0xd56E1a69d97A4A0bD0942b7C6AE6eB44dBE371DE/sources/NFTProtocolDEX.sol
Set multisig ie. administrator account. Only the :sol:func:`msig` will be able to call this function successfully. _to address of the new multisig/admin account
function auth(address _to) external onlyMsig { require(_to != address(0x0), "Cannot set to zero address"); msig = _to; }
9,423,198
./partial_match/1/0xB6Fb960cD2E7e66aAB5adDC15066743f14C180c0/sources/killcord.sol
Outputs the `uint` for the last `block.timestamp` that registered to this contract on the blockchain.
function getLastCheckIn() public constant returns (uint) { return lastCheckIn; }
4,214,514
pragma solidity 0.4.24; // ---------------------------------------------------------------------------- // 'IST' 'istanbul' contract // ---------------------------------------------------------------------------- // Symbol : IST // Name : Istanbul // Total supply: 50.020.000.000000000000000000 // Decimals : 18 // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Math operations with safety checks // ---------------------------------------------------------------------------- library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a * b; require(a == 0 || c / a == b); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0); c = a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b <= a); c = a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); function burn(uint256 tokens) public returns (bool success); function freeze(uint256 tokens) public returns (bool success); function unfreeze(uint256 tokens) public returns (bool success); /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint tokens); /* This approve the allowance for the spender */ event Approval(address indexed tokenOwner, address indexed spender, uint tokens); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 tokens); /* This notifies clients about the amount frozen */ event Freeze(address indexed from, uint256 tokens); /* This notifies clients about the amount unfrozen */ event Unfreeze(address indexed from, uint256 tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); //constructor constructor () 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); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial supply // ---------------------------------------------------------------------------- contract istanbul is ERC20Interface, Owned { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; address public owner; /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping(address => mapping(address => uint256)) allowed; mapping (address => uint256) public freezeOf; /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { symbol = "IST"; name = "istanbul"; decimals = 18; _totalSupply = 50020000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // Owner's account must have sufficient balance to transfer // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require( tokens > 0 && to != 0x0 ); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit 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.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public onlyOwner returns (bool success) { allowed[msg.sender][spender] = tokens; emit 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 // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require( tokens > 0 && to != 0x0 && from != 0x0 ); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Burns the amount of tokens by the owner // ------------------------------------------------------------------------ function burn(uint256 tokens) public onlyOwner returns (bool success) { require (balances[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender _totalSupply = _totalSupply.sub(tokens); // Updates totalSupply emit Burn(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Freeze the amount of tokens by the owner // ------------------------------------------------------------------------ function freeze(uint256 tokens) public onlyOwner returns (bool success) { require (balances[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; balances[msg.sender] = balances[msg.sender].sub(tokens); // Subtract from the sender freezeOf[msg.sender] = freezeOf[msg.sender].add(tokens); // Updates totalSupply emit Freeze(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Unfreeze the amount of tokens by the owner // ------------------------------------------------------------------------ function unfreeze(uint256 tokens) public onlyOwner returns (bool success) { require (freezeOf[msg.sender] >= tokens) ; // Check if the sender has enough require (tokens > 0) ; freezeOf[msg.sender] = freezeOf[msg.sender].sub(tokens); // Subtract from the sender balances[msg.sender] = balances[msg.sender].add(tokens); emit Unfreeze(msg.sender, tokens); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } } // ---------------------------------------------------------------------------- // Psp (sha1) = c1323412799ee711e7e5a6a1ac655bbd18d75980 // ----------------------------------------------------------------------------
------------------------------------------------------------------------ Burns the amount of tokens by the owner ------------------------------------------------------------------------
function burn(uint256 tokens) public onlyOwner returns (bool success) { require (tokens > 0) ; emit Burn(msg.sender, tokens); return true; }
6,389,997
./full_match/11155111/0x15643fcF00285b3D2f31cb838Df02B0932c682c0/sources/ERC1643.sol
Used to remove an existing document from the contract by giving the name of the document. Can only be executed by the owner or manager of the contract. _name Name of the document. It should be unique always/ Protect against underflow If the document is not the last one in the array, swap it with the last one Reduce the length of the array by one
function removeDocument(bytes32 _name) external onlyOwnerOrManager { require( _documents[_name].lastModified != uint256(0), "Document does not exist" ); require(_docIndexes[_name] > 0, "Document index is not valid"); uint256 index = _docIndexes[_name] - 1; if (_docNames.length > 0 && index != _docNames.length - 1) { _docNames[index] = _docNames[_docNames.length - 1]; _docIndexes[_docNames[index]] = index + 1; } if (_docNames.length > 0) { _docNames.pop(); } emit DocumentRemoved( _name, _documents[_name].uri, _documents[_name].docHash ); }
3,818,786
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @artist: Steve Aoki /// @title: A0K1 Credits /// @author: manifold.xyz ///////////////////////////////////////////////////////////////////////////////////// // // // // // ,xWWWWWx,. // // 'OWWWWWWWNd. // // .xWWWK0KNWWNl // // .oNWWXc.,xWWWX: // // lNWWNo. .OWWW0, // // :XWWWx. ,0WWWO' // // ,0WWWO. :XWWWx. // // 'OWWW0, ... lNWWNd. // // .xWWWX: o0k; .dNWWXl // // .dNWWNl cXWW0' .kWWWX: // // lXWWNd. ;KWWWWk. '0WWW0, // // :XWWWk. '0WWWWWNd. ;KWWWO' // // ,0WWWO' .kWWWWWWWNo. cXWWWx. // // .OWWWK; .dNWWWWWWWWXc .oNWWNo. // // .xWWWXc oNWWWKOKNWWWK; .xWWWXl // // .oNWWNo cXWWWX:.,dNWWW0' 'OWWWX: // // lXWWWd. ;KWWWNl .kWWWWk. ;KWWW0, // // :XWWWk. '0WWWNd. ,0WWWWd. :XWWWO' // // ,0WWW0' ;dddxl. ,ddddo' lNWWWx. // // .xWWWNl .OWWWNc // // :XWWWO. ,llll:. .clllc. :KWWWO' // // lNWWWx. ;KWWWNo. .OWWWWk. ,0WWWK, // // .dNWWNo :XWWWXc .xWWWWO' .OWWWX: // // .xWWWXc lNWWWK;..oNWWWK; .xWWWNl // // 'OWWWK; .dNWWW0kOXWWWX: oNWWNd. // // ,0WWWO' .kWWWWWWWWWNl cXWWWx. // // :XWWWk. 'OWWWWWWWNd. ;KWWWO' // // lNWWNd. ;KWWWWWWk. '0WWWK; // // .dNWWNl :XWWWWO' .kWWWX: // // .xWWWK: lNWWK; .dNWWNl // // 'OWWW0, .dK0c lNWWNd. // // ,0WWWk. .,.. :XWWWx. // // :XWWWx. ,KWWWO' // // lNWWNo 'OWWWK, // // .dNWWXc .xWWWX: // // .xWWWK;..oNWWNl // // 'OWWW0x0XWWNd. // // ,KWWWWWWWWx. // // :XWWWWWWO' // // .l000O0l. // // // // // ///////////////////////////////////////////////////////////////////////////////////// import "@manifoldxyz/libraries-solidity/contracts/access/AdminControl.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "./ERC1155CollectionBase.sol"; /** * ERC1155 Collection Drop Contract */ contract A0K1Credits is ERC1155, ERC1155CollectionBase, AdminControl { constructor(address signingAddress_) ERC1155('') { _initialize( 50000, // maxSupply 25000, // purchaseMax 250000000000000000, // purchasePrice 0, // purchaseLimit 24, // transactionLimit 250000000000000000, // presalePurchasePrice 0, // presalePurchaseLimit signingAddress_ ); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, AdminControl) returns (bool) { return ERC1155.supportsInterface(interfaceId) || AdminControl.supportsInterface(interfaceId); } /** * @dev See {IERC1155Collection-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { return ERC1155.balanceOf(owner, TOKEN_ID); } /** * @dev See {IERC1155Collection-withdraw}. */ function withdraw(address payable recipient, uint256 amount) external override adminRequired { _withdraw(recipient, amount); } /** * @dev See {IERC1155Collection-setTransferLocked}. */ function setTransferLocked(bool locked) external override adminRequired { _setTransferLocked(locked); } /** * @dev See {IERC1155Collection-premint}. */ function premint(uint16 amount) external override adminRequired { _premint(amount, owner()); } /** * @dev See {IERC1155Collection-premint}. */ function premint(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired { _premint(amounts, addresses); } /** * @dev See {IERC1155Collection-mintReserve}. */ function mintReserve(uint16 amount) external override adminRequired { _mintReserve(amount, owner()); } /** * @dev See {IERC1155Collection-mintReserve}. */ function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external override adminRequired { _mintReserve(amounts, addresses); } /** * @dev See {IERC1155Collection-activate}. */ function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external override adminRequired { _activate(startTime_, duration, presaleInterval_, claimStartTime_, claimEndTime_); } /** * @dev See {IERC1155Collection-deactivate}. */ function deactivate() external override adminRequired { _deactivate(); } /** * @dev See {IERC1155Collection-updateRoyalties}. */ function updateRoyalties(address payable recipient, uint256 bps) external override adminRequired { _updateRoyalties(recipient, bps); } /** * @dev See {IERC1155Collection-setCollectionURI}. */ function setCollectionURI(string calldata uri) external override adminRequired { _setURI(uri); } /** * @dev See {IERC1155Collection-burn} */ function burn(address from, uint16 amount) public virtual override { require(from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved"); ERC1155._burn(from, TOKEN_ID, amount); } /** * @dev See {ERC1155CollectionBase-_mint}. */ function _mintERC1155(address to, uint16 amount) internal virtual override { ERC1155._mint(to, TOKEN_ID, amount, ""); } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer(address, address from, address, uint256[] memory, uint256[] memory, bytes memory) internal virtual override { _validateTokenTransferability(from); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/Strings.sol"; import "./IERC1155Collection.sol"; import "./CollectionBase.sol"; /** * ERC721 Collection Drop Contract (Base) */ abstract contract ERC1155CollectionBase is CollectionBase, IERC1155Collection { // Token ID to mint uint16 internal constant TOKEN_ID = 1; // Immutable variables that should only be set by the constructor or initializer uint16 public transactionLimit; uint16 public purchaseMax; uint16 public purchaseLimit; uint256 public purchasePrice; uint16 public presalePurchaseLimit; uint256 public presalePurchasePrice; uint16 public maxSupply; // Mutable mint state uint16 public purchaseCount; uint16 public reserveCount; mapping(address => uint16) private _mintCount; // Royalty address payable private _royaltyRecipient; uint256 private _royaltyBps; // Transfer lock bool public transferLocked; /** * Initializer */ function _initialize(uint16 maxSupply_, uint16 purchaseMax_, uint256 purchasePrice_, uint16 purchaseLimit_, uint16 transactionLimit_, uint256 presalePurchasePrice_, uint16 presalePurchaseLimit_, address signingAddress_) internal { require(_signingAddress == address(0), "Already initialized"); require(maxSupply_ >= purchaseMax_, "Invalid input"); maxSupply = maxSupply_; purchaseMax = purchaseMax_; purchasePrice = purchasePrice_; purchaseLimit = purchaseLimit_; transactionLimit = transactionLimit_; presalePurchaseLimit = presalePurchaseLimit_; presalePurchasePrice = presalePurchasePrice_; _signingAddress = signingAddress_; } /** * @dev See {IERC1155Collection-claim}. */ function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override { _validateClaimRestrictions(); _validateClaimRequest(message, signature, nonce, amount); _mint(msg.sender, amount, true); } /** * @dev See {IERC1155Collection-purchase}. */ function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override payable { _validatePurchaseRestrictions(); // Check purchase amounts require(amount <= purchaseRemaining() && (transactionLimit == 0 || amount <= transactionLimit), "Too many requested"); uint256 balance; if (!transferLocked && (presalePurchaseLimit > 0 || purchaseLimit > 0)) { balance = _mintCount[msg.sender]; } else { balance = balanceOf(msg.sender); } bool presale; if (block.timestamp - startTime < presaleInterval) { require((presalePurchaseLimit == 0 || amount <= (presalePurchaseLimit - balance)) && (purchaseLimit == 0 || amount <= (purchaseLimit - balance)), "Too many requested"); _validatePresalePrice(amount); presale = true; } else { require(purchaseLimit == 0 || amount <= (purchaseLimit - balance), "Too many requested"); _validatePrice(amount); } _validatePurchaseRequest(message, signature, nonce); _mint(msg.sender, amount, presale); } /** * @dev See {IERC1155Collection-state} */ function state() external override view returns (CollectionState memory) { if (msg.sender == address(0)) { // No message sender, no purchase balance return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, 0, active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } else { if (!transferLocked && (presalePurchaseLimit > 0 || purchaseLimit > 0)) { return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, _mintCount[msg.sender], active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } else { return CollectionState(transactionLimit, purchaseMax, purchaseRemaining(), purchasePrice, purchaseLimit, presalePurchasePrice, presalePurchaseLimit, uint16(balanceOf(msg.sender)), active, startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } } } /** * @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID * @param owner The address to get the token balance of */ function balanceOf(address owner) public virtual override view returns (uint256); /** * @dev See {IERC1155Collection-purchaseRemaining}. */ function purchaseRemaining() public virtual override view returns (uint16) { return purchaseMax - purchaseCount; } /** * @dev See {IERC1155Collection-getRoyalties}. */ function getRoyalties(uint256) external override view returns (address payable, uint256) { return (_royaltyRecipient, _royaltyBps); } /** * @dev See {IERC1155Collection-royaltyInfo}. */ function royaltyInfo(uint256, uint256 salePrice) external override view returns (address, uint256) { return (_royaltyRecipient, (salePrice * _royaltyBps) / 10000); } /** * Premint tokens to the owner. Purchase must not be active. */ function _premint(uint16 amount, address owner) internal virtual { require(!active, "Already active"); _mint(owner, amount, true); } /** * Premint tokens to the list of addresses. Purchase must not be active. */ function _premint(uint16[] calldata amounts, address[] calldata addresses) internal virtual { require(!active, "Already active"); for (uint256 i = 0; i < addresses.length; i++) { _mint(addresses[i], amounts[i], true); } } /** * Mint reserve tokens. Purchase must be completed. */ function _mintReserve(uint16 amount, address owner) internal virtual { require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete"); require(purchaseCount + reserveCount + amount <= maxSupply, "Too many requested"); reserveCount += amount; _mintERC1155(owner, amount); } /** * Mint reserve tokens. Purchase must be completed. */ function _mintReserve(uint16[] calldata amounts, address[] calldata addresses) internal virtual { require(endTime != 0 && endTime <= block.timestamp, "Cannot mint reserve until after sale complete"); uint16 totalAmount; for (uint256 i = 0; i < addresses.length; i++) { totalAmount += amounts[i]; } require(purchaseCount + reserveCount + totalAmount <= maxSupply, "Too many requested"); reserveCount += totalAmount; for (uint256 i = 0; i < addresses.length; i++) { _mintERC1155(addresses[i], amounts[i]); } } /** * Mint function internal to ERC1155CollectionBase to keep track of state */ function _mint(address to, uint16 amount, bool presale) internal { purchaseCount += amount; // Track total mints per address only if necessary if (!transferLocked && ((presalePurchaseLimit > 0 && presale) || purchaseLimit > 0)) { _mintCount[msg.sender] += amount; } _mintERC1155(to, amount); } /** * @dev A _mint function is required that calls the underlying ERC1155 mint. */ function _mintERC1155(address to, uint16 amount) internal virtual; /** * Validate price (override for custom pricing mechanics) */ function _validatePrice(uint16 amount) internal { require(msg.value == amount * purchasePrice, "Invalid purchase amount sent"); } /** * Validate price (override for custom pricing mechanics) */ function _validatePresalePrice(uint16 amount) internal virtual { require(msg.value == amount * presalePurchasePrice, "Invalid purchase amount sent"); } /** * If enabled, lock token transfers until after the sale has ended. * * This helps enforce purchase limits, so someone can't buy -> transfer -> buy again * while the token is minting. */ function _validateTokenTransferability(address from) internal view { require(!transferLocked || purchaseRemaining() == 0 || (active && block.timestamp >= endTime) || from == address(0), "Transfer locked until sale ends"); } /** * Set whether or not token transfers are locked till end of sale */ function _setTransferLocked(bool locked) internal { transferLocked = locked; } /** * @dev See {IERC1155Collection-updateRoyalties}. */ function _updateRoyalties(address payable recipient, uint256 bps) internal { _royaltyRecipient = recipient; _royaltyBps = bps; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IAdminControl.sol"; abstract contract AdminControl is Ownable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require(owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin"); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public override view returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ICollectionBase.sol"; /** * Collection Drop Contract (Base) */ abstract contract CollectionBase is ICollectionBase { using ECDSA for bytes32; using Strings for uint256; // Immutable variables that should only be set by the constructor or initializer address internal _signingAddress; // Message nonces mapping(string => bool) private _usedNonces; // Sale start/end control bool public active; uint256 public startTime; uint256 public endTime; uint256 public presaleInterval; // Claim period start/end control uint256 public claimStartTime; uint256 public claimEndTime; /** * Withdraw funds */ function _withdraw(address payable recipient, uint256 amount) internal { (bool success,) = recipient.call{value:amount}(""); require(success); } /** * Activate the sale */ function _activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) internal virtual { require(!active, "Already active"); require(startTime_ > block.timestamp, "Cannot activate in the past"); require(presaleInterval_ < duration, "Presale Interval cannot be longer than the sale"); require(claimStartTime_ <= claimEndTime_ && claimEndTime_ <= startTime_, "Invalid claim times"); startTime = startTime_; endTime = startTime + duration; presaleInterval = presaleInterval_; claimStartTime = claimStartTime_; claimEndTime = claimEndTime_; active = true; emit CollectionActivated(startTime, endTime, presaleInterval, claimStartTime, claimEndTime); } /** * Deactivate the sale */ function _deactivate() internal virtual { startTime = 0; endTime = 0; active = false; claimStartTime = 0; claimEndTime = 0; emit CollectionDeactivated(); } /** * Validate claim signature */ function _validateClaimRequest(bytes32 message, bytes calldata signature, string calldata nonce, uint16 amount) internal virtual { // Verify nonce usage/re-use require(!_usedNonces[nonce], "Cannot replay transaction"); // Verify valid message based on input variables bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length+bytes(uint256(amount).toString()).length).toString(), msg.sender, nonce, uint256(amount).toString())); require(message == expectedMessage, "Malformed message"); // Verify signature was performed by the expected signing address address signer = message.recover(signature); require(signer == _signingAddress, "Invalid signature"); _usedNonces[nonce] = true; } /** * Validate claim restrictions */ function _validateClaimRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= claimStartTime && block.timestamp <= claimEndTime, "Outside claim period."); } /** * Validate purchase signature */ function _validatePurchaseRequest(bytes32 message, bytes calldata signature, string calldata nonce) internal virtual { // Verify nonce usage/re-use require(!_usedNonces[nonce], "Cannot replay transaction"); // Verify valid message based on input variables bytes32 expectedMessage = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", (20+bytes(nonce).length).toString(), msg.sender, nonce)); require(message == expectedMessage, "Malformed message"); // Verify signature was performed by the expected signing address address signer = message.recover(signature); require(signer == _signingAddress, "Invalid signature"); _usedNonces[nonce] = true; } /** * Perform purchase restriciton checks. Override if more logic is needed */ function _validatePurchaseRestrictions() internal virtual { require(active, "Inactive"); require(block.timestamp >= startTime, "Purchasing not active"); } /** * @dev See {ICollectionBase-nonceUsed}. */ function nonceUsed(string memory nonce) external view override returns(bool) { return _usedNonces[nonce]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // @author: manifold.xyz import "./ICollectionBase.sol"; /** * @dev ERC1155 Collection Interface */ interface IERC1155Collection is ICollectionBase { struct CollectionState { uint16 transactionLimit; uint16 purchaseMax; uint16 purchaseRemaining; uint256 purchasePrice; uint16 purchaseLimit; uint256 presalePurchasePrice; uint16 presalePurchaseLimit; uint16 purchaseCount; bool active; uint256 startTime; uint256 endTime; uint256 presaleInterval; uint256 claimStartTime; uint256 claimEndTime; } /** * @dev Activates the contract. * @param startTime_ The UNIX timestamp in seconds the sale should start at. * @param duration The number of seconds the sale should remain active. * @param presaleInterval_ The period of time the contract should only be active for presale. */ function activate(uint256 startTime_, uint256 duration, uint256 presaleInterval_, uint256 claimStartTime_, uint256 claimEndTime_) external; /** * @dev Deactivate the contract */ function deactivate() external; /** * @dev Pre-mint tokens to the owner. Sale must not be active. * @param amount The number of tokens to mint. */ function premint(uint16 amount) external; /** * @dev Pre-mint tokens to the list of addresses. Sale must not be active. * @param amounts The amount of tokens to mint per address. * @param addresses The list of addresses to mint a token to. */ function premint(uint16[] calldata amounts, address[] calldata addresses) external; /** * @dev Claim - mint with validation. * @param amount The number of tokens to mint. * @param message Signed message to validate input args. * @param signature Signature of the signer to recover from signed message. * @param nonce Manifold-generated nonce. */ function claim(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external; /** * @dev Purchase - mint with validation. * @param amount The number of tokens to mint. * @param message Signed message to validate input args. * @param signature Signature of the signer to recover from signed message. * @param nonce Manifold-generated nonce. */ function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external payable; /** * @dev Mint reserve tokens to the owner. Sale must be complete. * @param amount The number of tokens to mint. */ function mintReserve(uint16 amount) external; /** * @dev Mint reserve tokens to the list of addresses. Sale must be complete. * @param amounts The amount of tokens to mint per address. * @param addresses The list of addresses to mint a token to. */ function mintReserve(uint16[] calldata amounts, address[] calldata addresses) external; /** * @dev Set the URI for the metadata for the collection. * @param uri The metadata URI. */ function setCollectionURI(string calldata uri) external; /** * @dev returns the collection state */ function state() external view returns (CollectionState memory); /** * @dev Total amount of tokens remaining for the given token id. */ function purchaseRemaining() external view returns (uint16); /** * @dev Withdraw funds (requires contract admin). * @param recipient The address to withdraw funds to * @param amount The amount to withdraw */ function withdraw(address payable recipient, uint256 amount) external; /** * @dev Set whether or not token transfers are locked until end of sale. * @param locked Whether or not transfers are locked */ function setTransferLocked(bool locked) external; /** * @dev Update royalties * @param recipient The address to set as the royalty recipient * @param bps The basis points to set as the royalty */ function updateRoyalties(address payable recipient, uint256 bps) external; /** * @dev Get the current royalty recipient and amount */ function getRoyalties(uint256) external view returns (address payable recipient, uint256 bps); /** * @dev EIP-2981 compatibility to determine royalty info on sale */ function royaltyInfo(uint256, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); /** * @dev Get balance of address. Similar to IERC1155-balanceOf, but doesn't require token ID * @param owner The address to get the token balance of */ function balanceOf(address owner) external view returns (uint256); /** * @dev Destroys `amount` tokens from `from` * @param from The address to remove tokens from * @param amount The amount of tokens to remove */ function burn(address from, uint16 amount) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz /** * @dev Collection Interface */ interface ICollectionBase { event CollectionActivated(uint256 startTime, uint256 endTime, uint256 presaleInterval, uint256 claimStartTime, uint256 claimEndTime); event CollectionDeactivated(); /** * @dev Check if nonce has been used */ function nonceUsed(string memory nonce) external view returns(bool); } // 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 (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); }
See {IERC1155Collection-updateRoyalties}./
function updateRoyalties(address payable recipient, uint256 bps) external override adminRequired { _updateRoyalties(recipient, bps); }
10,079,381
// SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "./Rollup.sol"; import "./facets/IRollupFacets.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IMessageProvider.sol"; import "./INode.sol"; import "../libraries/Cloneable.sol"; contract RollupEventBridge is IMessageProvider, Cloneable { uint8 internal constant INITIALIZATION_MSG_TYPE = 11; uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8; uint8 internal constant CREATE_NODE_EVENT = 0; uint8 internal constant CONFIRM_NODE_EVENT = 1; uint8 internal constant REJECT_NODE_EVENT = 2; uint8 internal constant STAKE_CREATED_EVENT = 3; IBridge bridge; address rollup; modifier onlyRollup() { require(msg.sender == rollup, "ONLY_ROLLUP"); _; } function initialize(address _bridge, address _rollup) external { require(rollup == address(0), "ALREADY_INIT"); bridge = IBridge(_bridge); rollup = _rollup; } function rollupInitialized( uint256 confirmPeriodBlocks, uint256 avmGasSpeedLimitPerBlock, address owner, bytes calldata extraConfig ) external onlyRollup { bytes memory initMsg = abi.encodePacked( keccak256("ChallengePeriodEthBlocks"), confirmPeriodBlocks, keccak256("SpeedLimitPerSecond"), avmGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas keccak256("ChainOwner"), uint256(uint160(bytes20(owner))), extraConfig ); uint256 num = bridge.deliverMessageToInbox( INITIALIZATION_MSG_TYPE, address(0), keccak256(initMsg) ); emit InboxMessageDelivered(num, initMsg); } function nodeCreated( uint256 nodeNum, uint256 prev, uint256 deadline, address asserter ) external onlyRollup { deliverToBridge( abi.encodePacked( CREATE_NODE_EVENT, nodeNum, prev, block.number, deadline, uint256(uint160(bytes20(asserter))) ) ); } function nodeConfirmed(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum)); } function nodeRejected(uint256 nodeNum) external onlyRollup { deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum)); } function stakeCreated(address staker, uint256 nodeNum) external onlyRollup { deliverToBridge( abi.encodePacked( STAKE_CREATED_EVENT, uint256(uint160(bytes20(staker))), nodeNum, block.number ) ); } function deliverToBridge(bytes memory message) private { emit InboxMessageDelivered( bridge.deliverMessageToInbox( ROLLUP_PROTOCOL_EVENT_TYPE, msg.sender, keccak256(message) ), message ); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/proxy/Proxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RollupEventBridge.sol"; import "./RollupCore.sol"; import "./RollupLib.sol"; import "./INode.sol"; import "./INodeFactory.sol"; import "../challenge/IChallenge.sol"; import "../challenge/IChallengeFactory.sol"; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/IOutbox.sol"; import "../bridge/Messages.sol"; import "../libraries/ProxyUtil.sol"; import "../libraries/Cloneable.sol"; import "./facets/IRollupFacets.sol"; abstract contract RollupBase is Cloneable, RollupCore, Pausable { // Rollup Config uint256 public confirmPeriodBlocks; uint256 public extraChallengeTimeBlocks; uint256 public avmGasSpeedLimitPerBlock; uint256 public baseStake; // Bridge is an IInbox and IOutbox IBridge public delayedBridge; ISequencerInbox public sequencerBridge; IOutbox public outbox; RollupEventBridge public rollupEventBridge; IChallengeFactory public challengeFactory; INodeFactory public nodeFactory; address public owner; address public stakeToken; uint256 public minimumAssertionPeriod; uint256 public STORAGE_GAP_1; uint256 public STORAGE_GAP_2; uint256 public challengeExecutionBisectionDegree; address[] internal facets; mapping(address => bool) isValidator; /// @notice DEPRECATED -- this method is deprecated but still mantained for backward compatibility /// @dev this actually returns the avmGasSpeedLimitPerBlock /// @return this actually returns the avmGasSpeedLimitPerBlock function arbGasSpeedLimitPerBlock() external view returns (uint256) { return avmGasSpeedLimitPerBlock; } } contract Rollup is Proxy, RollupBase { using Address for address; constructor(uint256 _confirmPeriodBlocks) public Cloneable() Pausable() { // constructor is used so logic contract can't be init'ed confirmPeriodBlocks = _confirmPeriodBlocks; require(isInit(), "CONSTRUCTOR_NOT_INIT"); } function isInit() internal view returns (bool) { return confirmPeriodBlocks != 0; } // _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ] // connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory] function initialize( bytes32 _machineHash, uint256[4] calldata _rollupParams, address _stakeToken, address _owner, bytes calldata _extraConfig, address[6] calldata connectedContracts, address[2] calldata _facets, uint256[2] calldata sequencerInboxParams ) public { require(!isInit(), "ALREADY_INIT"); // calls initialize method in user facet require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT"); require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT"); (bool success, ) = _facets[1].delegatecall( abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken) ); require(success, "FAIL_INIT_FACET"); delayedBridge = IBridge(connectedContracts[0]); sequencerBridge = ISequencerInbox(connectedContracts[1]); outbox = IOutbox(connectedContracts[2]); delayedBridge.setOutbox(connectedContracts[2], true); rollupEventBridge = RollupEventBridge(connectedContracts[3]); delayedBridge.setInbox(connectedContracts[3], true); rollupEventBridge.rollupInitialized( _rollupParams[0], _rollupParams[2], _owner, _extraConfig ); challengeFactory = IChallengeFactory(connectedContracts[4]); nodeFactory = INodeFactory(connectedContracts[5]); INode node = createInitialNode(_machineHash); initializeCore(node); confirmPeriodBlocks = _rollupParams[0]; extraChallengeTimeBlocks = _rollupParams[1]; avmGasSpeedLimitPerBlock = _rollupParams[2]; baseStake = _rollupParams[3]; owner = _owner; // A little over 15 minutes minimumAssertionPeriod = 75; challengeExecutionBisectionDegree = 400; sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]); // facets[0] == admin, facets[1] == user facets = _facets; emit RollupCreated(_machineHash); require(isInit(), "INITIALIZE_NOT_INIT"); } function postUpgradeInit() external { // it is assumed the rollup contract is behind a Proxy controlled by a proxy admin // this function can only be called by the proxy admin contract address proxyAdmin = ProxyUtil.getProxyAdmin(); require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN"); // this upgrade moves the delay blocks and seconds tracking to the sequencer inbox // because of that we need to update the admin facet logic to allow the owner to set // these values in the sequencer inbox STORAGE_GAP_1 = 0; STORAGE_GAP_2 = 0; } function createInitialNode(bytes32 _machineHash) private returns (INode) { bytes32 state = RollupLib.stateHash( RollupLib.ExecutionState( 0, // total gas used _machineHash, 0, // inbox count 0, // send count 0, // log count 0, // send acc 0, // log acc block.number, // block proposed 1 // Initialization message already in inbox ) ); return INode( nodeFactory.createNode( state, 0, // challenge hash (not challengeable) 0, // confirm data 0, // prev node block.number // deadline block (not challengeable) ) ); } /** * This contract uses a dispatch pattern from EIP-2535: Diamonds * together with Open Zeppelin's proxy */ function getFacets() external view returns (address, address) { return (getAdminFacet(), getUserFacet()); } function getAdminFacet() public view returns (address) { return facets[0]; } function getUserFacet() public view returns (address) { return facets[1]; } /** * @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 override returns (address) { require(msg.data.length >= 4, "NO_FUNC_SIG"); address rollupOwner = owner; // if there is an owner and it is the sender, delegate to admin facet address target = rollupOwner != address(0) && rollupOwner == msg.sender ? getAdminFacet() : getUserFacet(); require(target.isContract(), "TARGET_NOT_CONTRACT"); return target; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "../INode.sol"; import "../../bridge/interfaces/IOutbox.sol"; interface IRollupUser { function initialize(address _stakeToken) external; function completeChallenge(address winningStaker, address losingStaker) external; function returnOldDeposit(address stakerAddress) external; function requireUnresolved(uint256 nodeNum) external view; function requireUnresolvedExists() external view; function countStakedZombies(INode node) external view returns (uint256); } interface IRollupAdmin { event OwnerFunctionCalled(uint256 indexed id); /** * @notice Add a contract authorized to put messages into this rollup's inbox * @param _outbox Outbox contract to add */ function setOutbox(IOutbox _outbox) external; /** * @notice Disable an old outbox from interacting with the bridge * @param _outbox Outbox contract to remove */ function removeOldOutbox(address _outbox) external; /** * @notice Enable or disable an inbox contract * @param _inbox Inbox contract to add or remove * @param _enabled New status of inbox */ function setInbox(address _inbox, bool _enabled) external; /** * @notice Pause interaction with the rollup contract */ function pause() external; /** * @notice Resume interaction with the rollup contract */ function resume() external; /** * @notice Set the addresses of rollup logic facets called * @param newAdminFacet address of logic that owner of rollup calls * @param newUserFacet ddress of logic that user of rollup calls */ function setFacets(address newAdminFacet, address newUserFacet) external; /** * @notice Set the addresses of the validator whitelist * @dev It is expected that both arrays are same length, and validator at * position i corresponds to the value at position i * @param _validator addresses to set in the whitelist * @param _val value to set in the whitelist for corresponding address */ function setValidator(address[] memory _validator, bool[] memory _val) external; /** * @notice Set a new owner address for the rollup * @param newOwner address of new rollup owner */ function setOwner(address newOwner) external; /** * @notice Set minimum assertion period for the rollup * @param newPeriod new minimum period for assertions */ function setMinimumAssertionPeriod(uint256 newPeriod) external; /** * @notice Set number of blocks until a node is considered confirmed * @param newConfirmPeriod new number of blocks until a node is confirmed */ function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external; /** * @notice Set number of extra blocks after a challenge * @param newExtraTimeBlocks new number of blocks */ function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external; /** * @notice Set speed limit per block * @param newAvmGasSpeedLimitPerBlock maximum avmgas to be used per block */ function setAvmGasSpeedLimitPerBlock(uint256 newAvmGasSpeedLimitPerBlock) external; /** * @notice Set base stake required for an assertion * @param newBaseStake maximum avmgas to be used per block */ function setBaseStake(uint256 newBaseStake) external; /** * @notice Set the token used for stake, where address(0) == eth * @dev Before changing the base stake token, you might need to change the * implementation of the Rollup User facet! * @param newStakeToken address of token used for staking */ function setStakeToken(address newStakeToken) external; /** * @notice Set max delay for sequencer inbox * @param newSequencerInboxMaxDelayBlocks max number of blocks * @param newSequencerInboxMaxDelaySeconds max number of seconds */ function setSequencerInboxMaxDelay( uint256 newSequencerInboxMaxDelayBlocks, uint256 newSequencerInboxMaxDelaySeconds ) external; /** * @notice Set execution bisection degree * @param newChallengeExecutionBisectionDegree execution bisection degree */ function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree) external; /** * @notice Updates a whitelist address for its consumers * @dev setting the newWhitelist to address(0) disables it for consumers * @param whitelist old whitelist to be deprecated * @param newWhitelist new whitelist to be used * @param targets whitelist consumers to be triggered */ function updateWhitelistConsumers( address whitelist, address newWhitelist, address[] memory targets ) external; /** * @notice Updates a whitelist's entries * @dev user at position i will be assigned value i * @param whitelist whitelist to be updated * @param user users to be updated in the whitelist * @param val if user is or not allowed in the whitelist */ function setWhitelistEntries( address whitelist, address[] memory user, bool[] memory val ) external; /** * @notice Updates whether an address is a sequencer at the sequencer inbox * @param newSequencer address to be modified * @param isSequencer whether this address should be authorized as a sequencer */ function setIsSequencer(address newSequencer, bool isSequencer) external; /** * @notice Upgrades the implementation of a beacon controlled by the rollup * @param beacon address of beacon to be upgraded * @param newImplementation new address of implementation */ function upgradeBeacon(address beacon, address newImplementation) external; function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external; function forceRefundStaker(address[] memory stacker) external; function forceCreateNode( bytes32 expectedNodeHash, bytes32[3][2] calldata assertionBytes32Fields, uint256[4][2] calldata assertionIntFields, bytes calldata sequencerBatchProof, uint256 beforeProposedBlock, uint256 beforeInboxMaxCount, uint256 prevNode ) external; function forceConfirmNode( uint256 nodeNum, bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount ) external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface IBridge { event MessageDelivered( uint256 indexed messageIndex, bytes32 indexed beforeInboxAcc, address inbox, uint8 kind, address sender, bytes32 messageDataHash ); event BridgeCallTriggered( address indexed outbox, address indexed destAddr, uint256 amount, bytes data ); event InboxToggle(address indexed inbox, bool enabled); event OutboxToggle(address indexed outbox, bool enabled); function deliverMessageToInbox( uint8 kind, address sender, bytes32 messageDataHash ) external payable returns (uint256); function executeCall( address destAddr, uint256 amount, bytes calldata data ) external returns (bool success, bytes memory returnData); // These are only callable by the admin function setInbox(address inbox, bool enabled) external; function setOutbox(address inbox, bool enabled) external; // View functions function activeOutbox() external view returns (address); function allowedInboxes(address inbox) external view returns (bool); function allowedOutboxes(address outbox) external view returns (bool); function inboxAccs(uint256 index) external view returns (bytes32); function messageCount() external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface IMessageProvider { event InboxMessageDelivered(uint256 indexed messageNum, bytes data); event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface INode { function initialize( address _rollup, bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external; function destroy() external; function addStaker(address staker) external returns (uint256); function removeStaker(address staker) external; function childCreated(uint256) external; function newChildConfirmDeadline(uint256 deadline) external; function stateHash() external view returns (bytes32); function challengeHash() external view returns (bytes32); function confirmData() external view returns (bytes32); function prev() external view returns (uint256); function deadlineBlock() external view returns (uint256); function noChildConfirmedBeforeBlock() external view returns (uint256); function stakerCount() external view returns (uint256); function stakers(address staker) external view returns (bool); function firstChildBlock() external view returns (uint256); function latestChildNumber() external view returns (uint256); function requirePastDeadline() external view; function requirePastChildConfirmDeadline() external view; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2020, Offchain Labs, 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.6.11; import "./ICloneable.sol"; contract Cloneable is ICloneable { string private constant NOT_CLONE = "NOT_CLONE"; bool private isMasterCopy; constructor() public { isMasterCopy = true; } function isMaster() external view override returns (bool) { return isMasterCopy; } function safeSelfDestruct(address payable dest) internal { require(!isMasterCopy, NOT_CLONE); selfdestruct(dest); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal 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 pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "./INode.sol"; import "./IRollupCore.sol"; import "./RollupLib.sol"; import "./INodeFactory.sol"; import "./RollupEventBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract RollupCore is IRollupCore { using SafeMath for uint256; // Stakers become Zombies after losing a challenge struct Zombie { address stakerAddress; uint256 latestStakedNode; } struct Staker { uint256 index; uint256 latestStakedNode; uint256 amountStaked; // currentChallenge is 0 if staker is not in a challenge address currentChallenge; bool isStaked; } uint256 private _latestConfirmed; uint256 private _firstUnresolvedNode; uint256 private _latestNodeCreated; uint256 private _lastStakeBlock; mapping(uint256 => INode) private _nodes; mapping(uint256 => bytes32) private _nodeHashes; address payable[] private _stakerList; mapping(address => Staker) public override _stakerMap; Zombie[] private _zombies; mapping(address => uint256) private _withdrawableFunds; /** * @notice Get the address of the Node contract for the given node * @param nodeNum Index of the node * @return Address of the Node contract */ function getNode(uint256 nodeNum) public view override returns (INode) { return _nodes[nodeNum]; } /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) external view override returns (address) { return _stakerList[stakerNum]; } /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) public view override returns (bool) { return _stakerMap[staker].isStaked; } /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) public view override returns (uint256) { return _stakerMap[staker].latestStakedNode; } /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) public view override returns (address) { return _stakerMap[staker].currentChallenge; } /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) public view override returns (uint256) { return _stakerMap[staker].amountStaked; } /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) public view override returns (address) { return _zombies[zombieNum].stakerAddress; } /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) { return _zombies[zombieNum].latestStakedNode; } /// @return Current number of un-removed zombies function zombieCount() public view override returns (uint256) { return _zombies.length; } function isZombie(address staker) public view override returns (bool) { for (uint256 i = 0; i < _zombies.length; i++) { if (staker == _zombies[i].stakerAddress) { return true; } } return false; } /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view override returns (uint256) { return _withdrawableFunds[owner]; } /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() public view override returns (uint256) { return _firstUnresolvedNode; } /// @return Index of the latest confirmed node function latestConfirmed() public view override returns (uint256) { return _latestConfirmed; } /// @return Index of the latest rollup node created function latestNodeCreated() public view override returns (uint256) { return _latestNodeCreated; } /// @return Ethereum block that the most recent stake was created function lastStakeBlock() external view override returns (uint256) { return _lastStakeBlock; } /// @return Number of active stakers currently staked function stakerCount() public view override returns (uint256) { return _stakerList.length; } /** * @notice Initialize the core with an initial node * @param initialNode Initial node to start the chain with */ function initializeCore(INode initialNode) internal { _nodes[0] = initialNode; _firstUnresolvedNode = 1; } /** * @notice React to a new node being created by storing it an incrementing the latest node counter * @param node Node that was newly created * @param nodeHash The hash of said node */ function nodeCreated(INode node, bytes32 nodeHash) internal { _latestNodeCreated++; _nodes[_latestNodeCreated] = node; _nodeHashes[_latestNodeCreated] = nodeHash; } /// @return Node hash as of this node number function getNodeHash(uint256 index) public view override returns (bytes32) { return _nodeHashes[index]; } /// @notice Reject the next unresolved node function _rejectNextNode() internal { destroyNode(_firstUnresolvedNode); _firstUnresolvedNode++; } /// @notice Confirm the next unresolved node function confirmNextNode( bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount, IOutbox outbox, RollupEventBridge rollupEventBridge ) internal { confirmNode( _firstUnresolvedNode, beforeSendAcc, sendsData, sendLengths, afterSendCount, afterLogAcc, afterLogCount, outbox, rollupEventBridge ); } function confirmNode( uint256 nodeNum, bytes32 beforeSendAcc, bytes calldata sendsData, uint256[] calldata sendLengths, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount, IOutbox outbox, RollupEventBridge rollupEventBridge ) internal { bytes32 afterSendAcc = RollupLib.feedAccumulator(sendsData, sendLengths, beforeSendAcc); INode node = getNode(nodeNum); // Authenticate data against node's confirm data pre-image require( node.confirmData() == RollupLib.confirmHash( beforeSendAcc, afterSendAcc, afterLogAcc, afterSendCount, afterLogCount ), "CONFIRM_DATA" ); // trusted external call to outbox outbox.processOutgoingMessages(sendsData, sendLengths); destroyNode(_latestConfirmed); _latestConfirmed = nodeNum; _firstUnresolvedNode = nodeNum + 1; rollupEventBridge.nodeConfirmed(nodeNum); emit NodeConfirmed(nodeNum, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount); } /** * @notice Create a new stake at latest confirmed node * @param stakerAddress Address of the new staker * @param depositAmount Stake amount of the new staker */ function createNewStake(address payable stakerAddress, uint256 depositAmount) internal { uint256 stakerIndex = _stakerList.length; _stakerList.push(stakerAddress); _stakerMap[stakerAddress] = Staker( stakerIndex, _latestConfirmed, depositAmount, address(0), // new staker is not in challenge true ); _lastStakeBlock = block.number; emit UserStakeUpdated(stakerAddress, 0, depositAmount); } /** * @notice Check to see whether the two stakers are in the same challenge * @param stakerAddress1 Address of the first staker * @param stakerAddress2 Address of the second staker * @return Address of the challenge that the two stakers are in */ function inChallenge(address stakerAddress1, address stakerAddress2) internal view returns (address) { Staker storage staker1 = _stakerMap[stakerAddress1]; Staker storage staker2 = _stakerMap[stakerAddress2]; address challenge = staker1.currentChallenge; require(challenge != address(0), "NO_CHAL"); require(challenge == staker2.currentChallenge, "DIFF_IN_CHAL"); return challenge; } /** * @notice Make the given staker as not being in a challenge * @param stakerAddress Address of the staker to remove from a challenge */ function clearChallenge(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; staker.currentChallenge = address(0); } /** * @notice Mark both the given stakers as engaged in the challenge * @param staker1 Address of the first staker * @param staker2 Address of the second staker * @param challenge Address of the challenge both stakers are now in */ function challengeStarted( address staker1, address staker2, address challenge ) internal { _stakerMap[staker1].currentChallenge = challenge; _stakerMap[staker2].currentChallenge = challenge; } /** * @notice Add to the stake of the given staker by the given amount * @param stakerAddress Address of the staker to increase the stake of * @param amountAdded Amount of stake to add to the staker */ function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal { Staker storage staker = _stakerMap[stakerAddress]; uint256 initialStaked = staker.amountStaked; uint256 finalStaked = initialStaked.add(amountAdded); staker.amountStaked = finalStaked; emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked); } /** * @notice Reduce the stake of the given staker to the given target * @param stakerAddress Address of the staker to reduce the stake of * @param target Amount of stake to leave with the staker * @return Amount of value released from the stake */ function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) { Staker storage staker = _stakerMap[stakerAddress]; uint256 current = staker.amountStaked; require(target <= current, "TOO_LITTLE_STAKE"); uint256 amountWithdrawn = current.sub(target); staker.amountStaked = target; increaseWithdrawableFunds(stakerAddress, amountWithdrawn); emit UserStakeUpdated(stakerAddress, current, target); return amountWithdrawn; } /** * @notice Remove the given staker and turn them into a zombie * @param stakerAddress Address of the staker to remove */ function turnIntoZombie(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; _zombies.push(Zombie(stakerAddress, staker.latestStakedNode)); deleteStaker(stakerAddress); } /** * @notice Update the latest staked node of the zombie at the given index * @param zombieNum Index of the zombie to move * @param latest New latest node the zombie is staked on */ function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal { _zombies[zombieNum].latestStakedNode = latest; } /** * @notice Remove the zombie at the given index * @param zombieNum Index of the zombie to remove */ function removeZombie(uint256 zombieNum) internal { _zombies[zombieNum] = _zombies[_zombies.length - 1]; _zombies.pop(); } /** * @notice Remove the given staker and return their stake * @param stakerAddress Address of the staker withdrawing their stake */ function withdrawStaker(address stakerAddress) internal { Staker storage staker = _stakerMap[stakerAddress]; uint256 initialStaked = staker.amountStaked; increaseWithdrawableFunds(stakerAddress, initialStaked); deleteStaker(stakerAddress); emit UserStakeUpdated(stakerAddress, initialStaked, 0); } /** * @notice Advance the given staker to the given node * @param stakerAddress Address of the staker adding their stake * @param nodeNum Index of the node to stake on */ function stakeOnNode( address stakerAddress, uint256 nodeNum, uint256 confirmPeriodBlocks ) internal { Staker storage staker = _stakerMap[stakerAddress]; INode node = _nodes[nodeNum]; uint256 newStakerCount = node.addStaker(stakerAddress); staker.latestStakedNode = nodeNum; if (newStakerCount == 1) { INode parent = _nodes[node.prev()]; parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks)); } } /** * @notice Clear the withdrawable funds for the given address * @param owner Address of the account to remove funds from * @return Amount of funds removed from account */ function withdrawFunds(address owner) internal returns (uint256) { uint256 amount = _withdrawableFunds[owner]; _withdrawableFunds[owner] = 0; emit UserWithdrawableFundsUpdated(owner, amount, 0); return amount; } /** * @notice Increase the withdrawable funds for the given address * @param owner Address of the account to add withdrawable funds to */ function increaseWithdrawableFunds(address owner, uint256 amount) internal { uint256 initialWithdrawable = _withdrawableFunds[owner]; uint256 finalWithdrawable = initialWithdrawable.add(amount); _withdrawableFunds[owner] = finalWithdrawable; emit UserWithdrawableFundsUpdated(owner, initialWithdrawable, finalWithdrawable); } /** * @notice Remove the given staker * @param stakerAddress Address of the staker to remove */ function deleteStaker(address stakerAddress) private { Staker storage staker = _stakerMap[stakerAddress]; uint256 stakerIndex = staker.index; _stakerList[stakerIndex] = _stakerList[_stakerList.length - 1]; _stakerMap[_stakerList[stakerIndex]].index = stakerIndex; _stakerList.pop(); delete _stakerMap[stakerAddress]; } /** * @notice Destroy the given node and clear out its address * @param nodeNum Index of the node to remove */ function destroyNode(uint256 nodeNum) internal { _nodes[nodeNum].destroy(); _nodes[nodeNum] = INode(0); } function nodeDeadline( uint256 avmGasSpeedLimitPerBlock, uint256 gasUsed, uint256 confirmPeriodBlocks, INode prevNode ) internal view returns (uint256 deadlineBlock) { // Set deadline rounding up to the nearest block uint256 checkTime = gasUsed.add(avmGasSpeedLimitPerBlock.sub(1)).div(avmGasSpeedLimitPerBlock); deadlineBlock = max(block.number.add(confirmPeriodBlocks), prevNode.deadlineBlock()).add( checkTime ); uint256 olderSibling = prevNode.latestChildNumber(); if (olderSibling != 0) { deadlineBlock = max(deadlineBlock, getNode(olderSibling).deadlineBlock()); } return deadlineBlock; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } struct StakeOnNewNodeFrame { uint256 currentInboxSize; INode node; bytes32 executionHash; INode prevNode; bytes32 lastHash; bool hasSibling; uint256 deadlineBlock; uint256 gasUsed; uint256 sequencerBatchEnd; bytes32 sequencerBatchAcc; } struct CreateNodeDataFrame { uint256 prevNode; uint256 confirmPeriodBlocks; uint256 avmGasSpeedLimitPerBlock; ISequencerInbox sequencerInbox; RollupEventBridge rollupEventBridge; INodeFactory nodeFactory; } uint8 internal constant MAX_SEND_COUNT = 100; function createNewNode( RollupLib.Assertion memory assertion, bytes32[3][2] calldata assertionBytes32Fields, uint256[4][2] calldata assertionIntFields, bytes calldata sequencerBatchProof, CreateNodeDataFrame memory inputDataFrame, bytes32 expectedNodeHash ) internal returns (bytes32 newNodeHash) { StakeOnNewNodeFrame memory memoryFrame; { // validate data memoryFrame.gasUsed = RollupLib.assertionGasUsed(assertion); memoryFrame.prevNode = getNode(inputDataFrame.prevNode); memoryFrame.currentInboxSize = inputDataFrame.sequencerInbox.messageCount(); // Make sure the previous state is correct against the node being built on require( RollupLib.stateHash(assertion.beforeState) == memoryFrame.prevNode.stateHash(), "PREV_STATE_HASH" ); // Ensure that the assertion doesn't read past the end of the current inbox require( assertion.afterState.inboxCount <= memoryFrame.currentInboxSize, "INBOX_PAST_END" ); // Insure inbox tip after assertion is included in a sequencer-inbox batch and return inbox acc; this gives replay protection against the state of the inbox (memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc) = inputDataFrame .sequencerInbox .proveInboxContainsMessage(sequencerBatchProof, assertion.afterState.inboxCount); } { memoryFrame.executionHash = RollupLib.executionHash(assertion); memoryFrame.deadlineBlock = nodeDeadline( inputDataFrame.avmGasSpeedLimitPerBlock, memoryFrame.gasUsed, inputDataFrame.confirmPeriodBlocks, memoryFrame.prevNode ); memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber() > 0; // here we don't use ternacy operator to remain compatible with slither if (memoryFrame.hasSibling) { memoryFrame.lastHash = getNodeHash(memoryFrame.prevNode.latestChildNumber()); } else { memoryFrame.lastHash = getNodeHash(inputDataFrame.prevNode); } memoryFrame.node = INode( inputDataFrame.nodeFactory.createNode( RollupLib.stateHash(assertion.afterState), RollupLib.challengeRoot(assertion, memoryFrame.executionHash, block.number), RollupLib.confirmHash(assertion), inputDataFrame.prevNode, memoryFrame.deadlineBlock ) ); } { uint256 nodeNum = latestNodeCreated() + 1; memoryFrame.prevNode.childCreated(nodeNum); newNodeHash = RollupLib.nodeHash( memoryFrame.hasSibling, memoryFrame.lastHash, memoryFrame.executionHash, memoryFrame.sequencerBatchAcc ); require(newNodeHash == expectedNodeHash, "UNEXPECTED_NODE_HASH"); nodeCreated(memoryFrame.node, newNodeHash); inputDataFrame.rollupEventBridge.nodeCreated( nodeNum, inputDataFrame.prevNode, memoryFrame.deadlineBlock, msg.sender ); } emit NodeCreated( latestNodeCreated(), getNodeHash(inputDataFrame.prevNode), newNodeHash, memoryFrame.executionHash, memoryFrame.currentInboxSize, memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc, assertionBytes32Fields, assertionIntFields ); return newNodeHash; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "../challenge/ChallengeLib.sol"; import "./INode.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library RollupLib { using SafeMath for uint256; struct Config { bytes32 machineHash; uint256 confirmPeriodBlocks; uint256 extraChallengeTimeBlocks; uint256 avmGasSpeedLimitPerBlock; uint256 baseStake; address stakeToken; address owner; address sequencer; uint256 sequencerDelayBlocks; uint256 sequencerDelaySeconds; bytes extraConfig; } struct ExecutionState { uint256 gasUsed; bytes32 machineHash; uint256 inboxCount; uint256 sendCount; uint256 logCount; bytes32 sendAcc; bytes32 logAcc; uint256 proposedBlock; uint256 inboxMaxCount; } function stateHash(ExecutionState memory execState) internal pure returns (bytes32) { return keccak256( abi.encodePacked( execState.gasUsed, execState.machineHash, execState.inboxCount, execState.sendCount, execState.logCount, execState.sendAcc, execState.logAcc, execState.proposedBlock, execState.inboxMaxCount ) ); } struct Assertion { ExecutionState beforeState; ExecutionState afterState; } function decodeExecutionState( bytes32[3] memory bytes32Fields, uint256[4] memory intFields, uint256 proposedBlock, uint256 inboxMaxCount ) internal pure returns (ExecutionState memory) { return ExecutionState( intFields[0], bytes32Fields[0], intFields[1], intFields[2], intFields[3], bytes32Fields[1], bytes32Fields[2], proposedBlock, inboxMaxCount ); } function decodeAssertion( bytes32[3][2] memory bytes32Fields, uint256[4][2] memory intFields, uint256 beforeProposedBlock, uint256 beforeInboxMaxCount, uint256 inboxMaxCount ) internal view returns (Assertion memory) { return Assertion( decodeExecutionState( bytes32Fields[0], intFields[0], beforeProposedBlock, beforeInboxMaxCount ), decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount) ); } function executionStateChallengeHash(ExecutionState memory state) internal pure returns (bytes32) { return ChallengeLib.assertionHash( state.gasUsed, ChallengeLib.assertionRestHash( state.inboxCount, state.machineHash, state.sendAcc, state.sendCount, state.logAcc, state.logCount ) ); } function executionHash(Assertion memory assertion) internal pure returns (bytes32) { return ChallengeLib.bisectionChunkHash( assertion.beforeState.gasUsed, assertion.afterState.gasUsed - assertion.beforeState.gasUsed, RollupLib.executionStateChallengeHash(assertion.beforeState), RollupLib.executionStateChallengeHash(assertion.afterState) ); } function assertionGasUsed(RollupLib.Assertion memory assertion) internal pure returns (uint256) { return assertion.afterState.gasUsed.sub(assertion.beforeState.gasUsed); } function challengeRoot( Assertion memory assertion, bytes32 assertionExecHash, uint256 blockProposed ) internal pure returns (bytes32) { return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount); } function challengeRootHash( bytes32 execution, uint256 proposedTime, uint256 maxMessageCount ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount)); } function confirmHash(Assertion memory assertion) internal pure returns (bytes32) { return confirmHash( assertion.beforeState.sendAcc, assertion.afterState.sendAcc, assertion.afterState.logAcc, assertion.afterState.sendCount, assertion.afterState.logCount ); } function confirmHash( bytes32 beforeSendAcc, bytes32 afterSendAcc, bytes32 afterLogAcc, uint256 afterSendCount, uint256 afterLogCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( beforeSendAcc, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount ) ); } function feedAccumulator( bytes memory messageData, uint256[] memory messageLengths, bytes32 beforeAcc ) internal pure returns (bytes32) { uint256 offset = 0; uint256 messageCount = messageLengths.length; uint256 dataLength = messageData.length; bytes32 messageAcc = beforeAcc; for (uint256 i = 0; i < messageCount; i++) { uint256 messageLength = messageLengths[i]; require(offset + messageLength <= dataLength, "DATA_OVERRUN"); bytes32 messageHash; assembly { messageHash := keccak256(add(messageData, add(offset, 32)), messageLength) } messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash)); offset += messageLength; } require(offset == dataLength, "DATA_LENGTH"); return messageAcc; } function nodeHash( bool hasSibling, bytes32 lastHash, bytes32 assertionExecHash, bytes32 inboxAcc ) internal pure returns (bytes32) { uint8 hasSiblingInt = hasSibling ? 1 : 0; return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface INodeFactory { function createNode( bytes32 _stateHash, bytes32 _challengeHash, bytes32 _confirmData, uint256 _prev, uint256 _deadlineBlock ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; import "../arch/IOneStepProof.sol"; interface IChallenge { function initializeChallenge( IOneStepProof[] calldata _executors, address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external; function currentResponderTimeLeft() external view returns (uint256); function lastMoveBlock() external view returns (uint256); function timeout() external; function asserter() external view returns (address); function challenger() external view returns (address); function clearChallenge() external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, 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.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IChallengeFactory { function createChallenge( address _resultReceiver, bytes32 _executionHash, uint256 _maxMessageCount, address _asserter, address _challenger, uint256 _asserterTimeLeft, uint256 _challengerTimeLeft, ISequencerInbox _sequencerBridge, IBridge _delayedBridge ) external returns (address); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface IOutbox { event OutboxEntryCreated( uint256 indexed batchNum, uint256 outboxEntryIndex, bytes32 outputRoot, uint256 numInBatch ); event OutBoxTransactionExecuted( address indexed destAddr, address indexed l2Sender, uint256 indexed outboxEntryIndex, uint256 transactionIndex ); function l2ToL1Sender() external view returns (address); function l2ToL1Block() external view returns (uint256); function l2ToL1EthBlock() external view returns (uint256); function l2ToL1Timestamp() external view returns (uint256); function l2ToL1BatchNum() external view returns (uint256); function l2ToL1OutputId() external view returns (bytes32); function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths) external; function outboxEntryExists(uint256 batchNum) external view returns (bool); function executeTransaction( uint256 outboxIndex, bytes32[] calldata proof, uint256 index, address l2Sender, address destAddr, uint256 l2Block, uint256 l1Block, uint256 l2Timestamp, uint256 amount, bytes calldata calldataForL1) external; } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, 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.6.11; library Messages { function messageHash( uint8 kind, address sender, uint256 blockNumber, uint256 timestamp, uint256 inboxSeqNum, uint256 gasPriceL1, bytes32 messageDataHash ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( kind, sender, blockNumber, timestamp, inboxSeqNum, gasPriceL1, messageDataHash ) ); } function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) { return keccak256(abi.encodePacked(inbox, message)); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; library ProxyUtil { function getProxyAdmin() internal view returns (address admin) { // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol#L48 // Storage slot with the admin of the proxy contract. // This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; assembly { admin := sload(slot) } } } // 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: Apache-2.0 /* * Copyright 2019, Offchain Labs, 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.6.11; interface ICloneable { function isMaster() external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; import "./INode.sol"; interface IRollupCore { function _stakerMap(address stakerAddress) external view returns ( uint256, uint256, uint256, address, bool ); event RollupCreated(bytes32 machineHash); event NodeCreated( uint256 indexed nodeNum, bytes32 indexed parentNodeHash, bytes32 nodeHash, bytes32 executionHash, uint256 inboxMaxCount, uint256 afterInboxBatchEndCount, bytes32 afterInboxBatchAcc, bytes32[3][2] assertionBytes32Fields, uint256[4][2] assertionIntFields ); event NodeConfirmed( uint256 indexed nodeNum, bytes32 afterSendAcc, uint256 afterSendCount, bytes32 afterLogAcc, uint256 afterLogCount ); event NodeRejected(uint256 indexed nodeNum); event RollupChallengeStarted( address indexed challengeContract, address asserter, address challenger, uint256 challengedNode ); event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance); event UserWithdrawableFundsUpdated( address indexed user, uint256 initialBalance, uint256 finalBalance ); function getNode(uint256 nodeNum) external view returns (INode); /** * @notice Get the address of the staker at the given index * @param stakerNum Index of the staker * @return Address of the staker */ function getStakerAddress(uint256 stakerNum) external view returns (address); /** * @notice Check whether the given staker is staked * @param staker Staker address to check * @return True or False for whether the staker was staked */ function isStaked(address staker) external view returns (bool); /** * @notice Get the latest staked node of the given staker * @param staker Staker address to lookup * @return Latest node staked of the staker */ function latestStakedNode(address staker) external view returns (uint256); /** * @notice Get the current challenge of the given staker * @param staker Staker address to lookup * @return Current challenge of the staker */ function currentChallenge(address staker) external view returns (address); /** * @notice Get the amount staked of the given staker * @param staker Staker address to lookup * @return Amount staked of the staker */ function amountStaked(address staker) external view returns (uint256); /** * @notice Get the original staker address of the zombie at the given index * @param zombieNum Index of the zombie to lookup * @return Original staker address of the zombie */ function zombieAddress(uint256 zombieNum) external view returns (address); /** * @notice Get Latest node that the given zombie at the given index is staked on * @param zombieNum Index of the zombie to lookup * @return Latest node that the given zombie is staked on */ function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256); /// @return Current number of un-removed zombies function zombieCount() external view returns (uint256); function isZombie(address staker) external view returns (bool); /** * @notice Get the amount of funds withdrawable by the given address * @param owner Address to check the funds of * @return Amount of funds withdrawable by owner */ function withdrawableFunds(address owner) external view returns (uint256); /** * @return Index of the first unresolved node * @dev If all nodes have been resolved, this will be latestNodeCreated + 1 */ function firstUnresolvedNode() external view returns (uint256); /// @return Index of the latest confirmed node function latestConfirmed() external view returns (uint256); /// @return Index of the latest rollup node created function latestNodeCreated() external view returns (uint256); /// @return Ethereum block that the most recent stake was created function lastStakeBlock() external view returns (uint256); /// @return Number of active stakers currently staked function stakerCount() external view returns (uint256); /// @return Node hash as of this node number function getNodeHash(uint256 index) external view returns (bytes32); } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2021, Offchain Labs, 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.6.11; interface ISequencerInbox { event SequencerBatchDelivered( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, bytes transactions, uint256[] lengths, uint256[] sectionsMetadata, uint256 seqBatchIndex, address sequencer ); event SequencerBatchDeliveredFromOrigin( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, bytes32 afterAcc, uint256 seqBatchIndex ); event DelayedInboxForced( uint256 indexed firstMessageNum, bytes32 indexed beforeAcc, uint256 newMessageCount, uint256 totalDelayedMessagesRead, bytes32[2] afterAccAndDelayed, uint256 seqBatchIndex ); /// @notice DEPRECATED - look at IsSequencerUpdated for new updates // event SequencerAddressUpdated(address newAddress); event IsSequencerUpdated(address addr, bool isSequencer); event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds); /// @notice DEPRECATED - look at MaxDelayUpdated for new updates // event MaxDelayBlocksUpdated(uint256 newValue); /// @notice DEPRECATED - look at MaxDelayUpdated for new updates // event MaxDelaySecondsUpdated(uint256 newValue); function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external; function setIsSequencer(address addr, bool isSequencer) external; function messageCount() external view returns (uint256); function maxDelayBlocks() external view returns (uint256); function maxDelaySeconds() external view returns (uint256); function inboxAccs(uint256 index) external view returns (bytes32); function getInboxAccsLength() external view returns (uint256); function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount) external view returns (uint256, bytes32); /// @notice DEPRECATED - use isSequencer instead function sequencer() external view returns (address); function isSequencer(address seq) external view returns (bool); } // 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: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, 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.6.11; import "../libraries/MerkleLib.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library ChallengeLib { using SafeMath for uint256; function firstSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount + (totalCount % bisectionCount); } function otherSegmentSize(uint256 totalCount, uint256 bisectionCount) internal pure returns (uint256) { return totalCount / bisectionCount; } function bisectionChunkHash( uint256 _segmentStart, uint256 _segmentLength, bytes32 _startHash, bytes32 _endHash ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash)); } function assertionHash(uint256 _avmGasUsed, bytes32 _restHash) internal pure returns (bytes32) { // Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0) return keccak256(abi.encodePacked(_avmGasUsed, _restHash)); } function assertionRestHash( uint256 _totalMessagesRead, bytes32 _machineState, bytes32 _sendAcc, uint256 _sendCount, bytes32 _logAcc, uint256 _logCount ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( _totalMessagesRead, _machineState, _sendAcc, _sendCount, _logAcc, _logCount ) ); } function updatedBisectionRoot( bytes32[] memory _chainHashes, uint256 _challengedSegmentStart, uint256 _challengedSegmentLength ) internal pure returns (bytes32) { uint256 bisectionCount = _chainHashes.length - 1; bytes32[] memory hashes = new bytes32[](bisectionCount); uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount); uint256 segmentStart = _challengedSegmentStart; hashes[0] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[0], _chainHashes[1] ); segmentStart = segmentStart.add(chunkSize); chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount); for (uint256 i = 1; i < bisectionCount; i++) { hashes[i] = ChallengeLib.bisectionChunkHash( segmentStart, chunkSize, _chainHashes[i], _chainHashes[i + 1] ); segmentStart = segmentStart.add(chunkSize); } return MerkleLib.generateRoot(hashes); } function verifySegmentProof( bytes32 challengeState, bytes32 item, bytes32[] calldata _merkleNodes, uint256 _merkleRoute ) internal pure returns (bool) { return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item); } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2019-2021, Offchain Labs, 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.6.11; library MerkleLib { function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) { bytes32[] memory prevLayer = _hashes; while (prevLayer.length > 1) { bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2); for (uint256 i = 0; i < nextLayer.length; i++) { if (2 * i + 1 < prevLayer.length) { nextLayer[i] = keccak256( abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1]) ); } else { nextLayer[i] = prevLayer[2 * i]; } } prevLayer = nextLayer; } return prevLayer[0]; } function calculateRoot( bytes32[] memory nodes, uint256 route, bytes32 item ) internal pure returns (bytes32) { uint256 proofItems = nodes.length; require(proofItems <= 256); bytes32 h = item; for (uint256 i = 0; i < proofItems; i++) { if (route % 2 == 0) { h = keccak256(abi.encodePacked(nodes[i], h)); } else { h = keccak256(abi.encodePacked(h, nodes[i])); } route /= 2; } return h; } } // SPDX-License-Identifier: Apache-2.0 /* * Copyright 2020, Offchain Labs, 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.6.11; import "../bridge/interfaces/IBridge.sol"; import "../bridge/interfaces/ISequencerInbox.sol"; interface IOneStepProof { // Bridges is sequencer bridge then delayed bridge function executeStep( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns ( uint64 gas, uint256 afterMessagesRead, bytes32[4] memory fields ); function executeStepDebug( address[2] calldata bridges, uint256 initialMessagesRead, bytes32[2] calldata accs, bytes calldata proof, bytes calldata bproof ) external view returns (string memory startMachine, string memory afterMachine); }
This is a virtual function that should be overriden so it returns the address to which the fallback function and {_fallback} should delegate./ if there is an owner and it is the sender, delegate to admin facet
function _implementation() internal view virtual override returns (address) { require(msg.data.length >= 4, "NO_FUNC_SIG"); address rollupOwner = owner; address target = rollupOwner != address(0) && rollupOwner == msg.sender ? getAdminFacet() : getUserFacet(); require(target.isContract(), "TARGET_NOT_CONTRACT"); return target; }
577,781
./full_match/137/0x6e754D2a8918216655BC3c8c03BF30C933Ce1276/sources/BaloneyCritters.sol
Allows contract `owner` to withdraw the contract's full balance./
function ownerWithdraw() external payable onlyOwner { require( address(this).balance > 0, "BaloneyCritters: Contract balance is 0" ); payable(msg.sender).transfer(address(this).balance); }
4,753,005
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol
Reverts execution with an "OrderIsCancelled" error message. orderHash The hash of the order that has already been cancelled./
function _revertOrderIsCancelled(bytes32 orderHash) pure { assembly { mstore(0, OrderIsCancelled_error_selector) mstore(OrderIsCancelled_error_orderHash_ptr, orderHash) revert(Error_selector_offset, OrderIsCancelled_error_length) } }
4,301,461
pragma solidity ^0.8.7; import "../nftx/interface/INFTXVault.sol"; import "../nftx/interface/INFTXLPStaking.sol"; import "../nftx/interface/IUniswapV2Router01.sol"; import "../nftx/interface/IVaultTokenUpgradeable.sol"; import "../nftx/interface/IRewardDistributionToken.sol"; import {IWETH} from "../nftx/interface/INFTXStakingZap.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; // SPDX-License-Identifier: MIT contract xRooStaking is Ownable { using PRBMathUD60x18 for uint256; event Staked( address indexed _user, uint256 _stake, uint256 _liquidity, uint256 _weth ); event Unstaked(address indexed _user, uint256 _stake, uint256 _liquidity); // --------- NFTX CONTRACTS/VARIABLES ------------- INFTXVault public NFTXVault; INFTXLPStaking public NFTXLPStaking; IRewardDistributionToken public NFTXRewardDistributionToken; uint256 constant base = 10**18; // 18 decimal places uint256 NFTXRewardPerLiquidity; IWETH public WETH; // --------- SUSHI CONTRACTS ------------ IUniswapV2Router01 public sushiRouter; IERC20 public SLPToken; // --------- INTERNAL CONTRACTS/VARIABLES --------- IERC20 public RTRewardToken; IERC721 public RTStakedToken; uint256 public rewardPeriod; uint256 public periodicReward; uint256 public lockTime; // at the start, RT rewards will not be withdrawable bool public lockRTRewards = true; // --------- STRUCTS -------------------- struct UserData { uint256 stake; uint256 liquidity; uint256 lastTimestamp; int256 RTRewardModifier; int256 NFTXRewardModifier; uint256 NFTXRewardWithdrawn; } struct Dividend { uint256 RTRewardToken; uint256 NFTXRewardToken; } // --------- CONTRACT DATA -------------- mapping(address => UserData) public users; // ---------- EXTERNAL CONTRACT METHODS ---------- constructor( address _NFTXVault, address _NFTXLPStaking, address _NFTXRewardDistributionToken, address _sushiRouter, address _SLPToken, address _RTRewardToken, address _RTStakedToken, uint256 _rewardPeriod, uint256 _periodicReward, uint256 _lockTime ) { RTRewardToken = IERC20(_RTRewardToken); RTStakedToken = IERC721(_RTStakedToken); rewardPeriod = _rewardPeriod; periodicReward = _periodicReward; lockTime = _lockTime; updateExternalReferences( _NFTXVault, _NFTXLPStaking, _NFTXRewardDistributionToken, _sushiRouter, _SLPToken ); } /** * Updates all external references (NFTX/Sushiswap/WETH). * @dev only for the contract owner to use, particularly in the case of near-FUBAR. * @param _NFTXVault the vault token address * @param _NFTXLPStaking the NFTXLPStaking contract address * @param _NFTXRewardDistributionToken the NFTX Reward distribution token * @param _sushiRouter the address of the Sushiswap router * @param _SLPToken the address of the liquidity pool WETH/vault token */ function updateExternalReferences( address _NFTXVault, address _NFTXLPStaking, address _NFTXRewardDistributionToken, address _sushiRouter, address _SLPToken ) public onlyOwner { // ASSIGNMENTS NFTXVault = INFTXVault(_NFTXVault); NFTXLPStaking = INFTXLPStaking(_NFTXLPStaking); NFTXRewardDistributionToken = IRewardDistributionToken( _NFTXRewardDistributionToken ); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); sushiRouter = IUniswapV2Router01(_sushiRouter); SLPToken = IERC20(_SLPToken); // APPROVALS IERC20Upgradeable(address(WETH)).approve( _sushiRouter, type(uint256).max ); SLPToken.approve(_sushiRouter, type(uint256).max); NFTXRewardDistributionToken.approve( address(NFTXLPStaking), type(uint256).max ); NFTXVault.approve(address(sushiRouter), type(uint256).max); SLPToken.approve(address(NFTXLPStaking), type(uint256).max); } /** * Updates the address for the reward token. * @param _token the token in which rewards will be disbursed. */ function setRTRewardToken(address _token) external onlyOwner { RTRewardToken = IERC20(_token); } /** * Locks/unlocks RT reward withdraw * @param _locked the value of the lock (boolean) */ function setLock(bool _locked) external onlyOwner { lockRTRewards = _locked; } /** * Sets the lock time where assets cannot be removed after staking. * @param _lockTime the amount of seconds the lock lasts after staking */ function setLockTime(uint256 _lockTime) external onlyOwner { require(_lockTime > 0); lockTime = _lockTime; } /** * Adds liquidity to the pool using the stakable ERC721 token * and WETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _wethIn the amount of WETH that has been provided by the call * @param _ids the ids of the tokens to stake */ function addLiquidityERC721( uint256 _minWethIn, uint256 _wethIn, uint256[] calldata _ids ) external { uint256 initialWETH = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ); IERC20Upgradeable(address(WETH)).transferFrom( msg.sender, address(this), _wethIn ); _addLiquidityERC721(msg.sender, _minWethIn, _wethIn, _ids); uint256 WETHRefund = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ) - initialWETH; if (WETHRefund < _wethIn && WETHRefund > 0) WETH.transfer(msg.sender, WETHRefund); } /** * Adds liquidity to the pool using the stakable ERC721 token * and ETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _ids the ids of the tokens to stake * @dev the value passed in is converted to WETH and sent to the LP. */ function addLiquidityERC721ETH(uint256 _minWethIn, uint256[] calldata _ids) external payable { uint256 initialWETH = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ); WETH.deposit{value: msg.value}(); _addLiquidityERC721(msg.sender, _minWethIn, msg.value, _ids); uint256 wethRefund = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ) - initialWETH; // Return extras. if (wethRefund < msg.value && wethRefund > 0) { WETH.withdraw(wethRefund); (bool success, ) = payable(msg.sender).call{value: wethRefund}(""); require(success, "Refund failed"); } } /** * Adds liquidity to the pool using the stakable ERC20 token * and WETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _wethIn the amount of WETH that has been provided by the call * @param _amount the amount of the ERC20 token to stake */ function addLiquidityERC20( uint256 _minWethIn, uint256 _wethIn, uint256 _amount ) external { IERC20Upgradeable(address(WETH)).transferFrom( msg.sender, address(this), _wethIn ); (, uint256 amountWETH, ) = _addLiquidityERC20( msg.sender, _minWethIn, _wethIn, _amount ); // refund unused WETH if (amountWETH < _wethIn && _wethIn - amountWETH > 0) { WETH.transfer(msg.sender, _wethIn - amountWETH); } } /** * Adds liquidity to the pool using the stakable ERC20 token * and ETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _amount the amount of the ERC20 token to stake * @dev the value passed in is converted to WETH and sent to the LP. */ function addLiquidityERC20ETH(uint256 _minWethIn, uint256 _amount) external payable { WETH.deposit{value: msg.value}(); (, uint256 amountWETH, ) = _addLiquidityERC20( msg.sender, _minWethIn, msg.value, _amount ); // refund unused ETH if (amountWETH < msg.value && msg.value - amountWETH > 0) { WETH.withdraw(msg.value - amountWETH); (bool sent, ) = payable(msg.sender).call{ value: msg.value - amountWETH }(""); require(sent, "refund failed"); } } /** * Removes all liquidity from the LP and claims rewards. * @param _amountTokenMin the min amount of the ERC20 staking token to get back * @param _amountWETHMin the min amount of WETH to get back * * NOTE you cannot withdraw until the timelock has expired. */ function removeLiquidity(uint256 _amountTokenMin, uint256 _amountWETHMin) external { require( users[msg.sender].lastTimestamp + lockTime < block.timestamp, "Locked" ); _removeLiquidity(msg.sender, _amountTokenMin, _amountWETHMin); } /** * Claims all of the dividends currently owed to the caller. * Will not claim RT rewards if the lock is set. */ function claimRewards() external { _claimRewards(msg.sender); } /** * Gets the rewards owed to the user. */ function dividendOf(address _user) external view returns (Dividend memory) { return _dividendOf(_user); } /** * An emergency function that will allow users to pull out their liquidity in the NFTX * reward distribution token. DOES NOT DISTRIBUTE REWARDS. This is to be used in the * case where our connection with NFTX's contracts causes transaction failures. * * NOTE you cannot withdraw until the timelock has expired. */ function emergencyExit() external { require( users[msg.sender].lastTimestamp + lockTime < block.timestamp, "Locked" ); _emergencyExit(msg.sender); } /** * Shows the time until the user's funds are unlocked (unix seconds). * @param _user the user whose lock time we are checking */ function lockedUntil(address _user) external view returns (uint256) { require(users[_user].lastTimestamp != 0, "N/A"); return users[_user].lastTimestamp + lockTime; } // ---------- INTERNAL CONTRACT METHODS ---------- function _totalLiquidityStaked() internal view returns (uint256) { return NFTXRewardDistributionToken.balanceOf(address(this)); } /** * An emergency escape in the unlikely case of a contract error * causing unstaking methods to fail. */ function _emergencyExit(address _user) internal { uint256 liquidity = users[_user].liquidity; delete users[_user]; NFTXRewardDistributionToken.transfer(_user, liquidity); } function _claimContractNFTXRewards() internal { uint256 currentRewards = NFTXVault.balanceOf(address(this)); uint256 dividend = NFTXRewardDistributionToken.dividendOf( address(this) ); if (dividend == 0) return; NFTXLPStaking.claimRewards(NFTXVault.vaultId()); require( NFTXVault.balanceOf(address(this)) == currentRewards + dividend, "Unexpected balance" ); NFTXRewardPerLiquidity += dividend.div(_totalLiquidityStaked()); } function _addLiquidityERC721( address _user, uint256 _minWethIn, uint256 _wethIn, uint256[] calldata _ids ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { _claimContractNFTXRewards(); uint256 initialRewardToken = NFTXVault.balanceOf(address(this)); for (uint256 i = 0; i < _ids.length; i++) { RTStakedToken.transferFrom(_user, address(this), _ids[i]); } RTStakedToken.setApprovalForAll(address(NFTXVault), true); NFTXVault.mint(_ids, new uint256[](0)); uint256 newTokens = NFTXVault.balanceOf(address(this)) - initialRewardToken; return _stakeAndUpdate(_user, _minWethIn, _wethIn, newTokens); } /** * Adds liquidity in ERC20 (the vault token) */ function _addLiquidityERC20( address _user, uint256 _minWethIn, uint256 _wethIn, uint256 _amount ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { _claimContractNFTXRewards(); NFTXVault.transferFrom(_user, address(this), _amount); return _stakeAndUpdate(_user, _minWethIn, _wethIn, _amount); } /** * Stakes on the SLP and then on NFTx's platform * @dev All vault token and WETH should be owned by the * contract before calling. */ function _stakeAndUpdate( address _user, uint256 _minWethIn, uint256 _wethIn, uint256 _amount // amount of ERC20 vault token ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { // stake on SUSHI ( amountToken, amountWETH, // amt used liquidity ) = sushiRouter.addLiquidity( address(NFTXVault), address(WETH), _amount, _wethIn, _amount, _minWethIn, address(this), block.timestamp ); NFTXLPStaking.deposit(NFTXVault.vaultId(), liquidity); // DEPOSIT IN NFTX UserData memory userData = users[_user]; uint256 NFTXRewardModifier = liquidity.mul(NFTXRewardPerLiquidity); uint256 currentNumPeriods = userData.lastTimestamp == 0 ? 0 : (block.timestamp - userData.lastTimestamp) / rewardPeriod; userData.liquidity += liquidity; userData.RTRewardModifier += int256( currentNumPeriods * periodicReward.mul(userData.stake) ); userData.lastTimestamp = block.timestamp; userData.stake += _amount; userData.NFTXRewardModifier -= int256(NFTXRewardModifier); users[_user] = userData; // return unstaked vault token if (amountToken < _amount) { NFTXVault.transfer(_user, _amount - amountToken); } emit Staked(_user, _amount, liquidity, amountWETH); } function _dividendOf(address _user) internal view returns (Dividend memory) { uint256 updatedNFTXRewardPerLiquidity = NFTXRewardPerLiquidity + NFTXRewardDistributionToken.dividendOf(address(this)).div( _totalLiquidityStaked() ); int256 nftxReward = int256( (users[_user].liquidity.mul(updatedNFTXRewardPerLiquidity)) ) + users[_user].NFTXRewardModifier - int256(users[_user].NFTXRewardWithdrawn); uint256 numPeriods = users[_user].lastTimestamp == 0 ? 0 : (block.timestamp - users[_user].lastTimestamp) / rewardPeriod; int256 rtReward = int256( numPeriods * periodicReward.mul(users[_user].stake) ) + users[_user].RTRewardModifier; require(nftxReward >= 0 && rtReward >= 0, "Negative Reward"); Dividend memory dividend; dividend.NFTXRewardToken = uint256(nftxReward); dividend.RTRewardToken = uint256(rtReward); return dividend; } function _claimRewards(address _user) internal { _claimContractNFTXRewards(); Dividend memory rewards = _dividendOf(_user); if (rewards.NFTXRewardToken > 0) { users[_user].NFTXRewardWithdrawn += rewards.NFTXRewardToken; NFTXVault.transfer(_user, rewards.NFTXRewardToken); } if (rewards.RTRewardToken > 0 && !lockRTRewards) { users[_user].RTRewardModifier -= int256(rewards.RTRewardToken); RTRewardToken.transfer(_user, rewards.RTRewardToken); } } function _removeLiquidity( address _user, uint256 _amountTokenMin, uint256 _amountWETHMin ) internal { uint256 amount = users[_user].liquidity; uint256 stake = users[_user].stake; _claimRewards(_user); delete users[_user]; // remove from NFTXLPStaking NFTXLPStaking.withdraw(NFTXVault.vaultId(), amount); // gives us <amount> SLP sushiRouter.removeLiquidity( address(NFTXVault), address(WETH), amount, _amountTokenMin, _amountWETHMin, _user, // send to user block.timestamp ); // return to user emit Unstaked(_user, stake, amount); } receive() external payable { // DO NOTHING } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/INFTXEligibility.sol"; import "../token/IERC20Upgradeable.sol"; import "../interface/INFTXVaultFactory.sol"; interface INFTXVault is IERC20Upgradeable { function manager() external view returns (address); function assetAddress() external view returns (address); function vaultFactory() external view returns (INFTXVaultFactory); function eligibilityStorage() external view returns (INFTXEligibility); function is1155() external view returns (bool); function allowAllItems() external view returns (bool); function enableMint() external view returns (bool); function enableRandomRedeem() external view returns (bool); function enableTargetRedeem() external view returns (bool); function enableRandomSwap() external view returns (bool); function enableTargetSwap() external view returns (bool); function vaultId() external view returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external view returns (uint256); function randomRedeemFee() external view returns (uint256); function targetRedeemFee() external view returns (uint256); function randomSwapFee() external view returns (uint256); function targetSwapFee() external view returns (uint256); function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event EnableRandomSwapUpdated(bool enabled); event EnableTargetSwapUpdated(bool enabled); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem, bool _enableRandomSwap, bool _enableTargetSwap ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee, uint256 _randomSwapFee, uint256 _targetSwapFee ) external; function disableVaultFees() external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface IVaultTokenUpgradeable is IERC20Upgradeable { function mint(address to, uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface IRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __RewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./INFTXVault.sol"; import "./INFTXVaultFactory.sol"; import "./INFTXFeeDistributor.sol"; import "./INFTXLPStaking.sol"; import "./ITimelockRewardDistributionToken.sol"; import "./IUniswapV2Router01.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "../token/IERC1155Upgradeable.sol"; import "../token/IERC20Upgradeable.sol"; import "../token/ERC721HolderUpgradeable.sol"; import "../token/IERC1155ReceiverUpgradeable.sol"; import "../util/OwnableUpgradeable.sol"; // Authors: @0xKiwi_. abstract contract IWETH { function deposit() virtual external payable; function transfer(address to, uint value) virtual external returns (bool); function withdraw(uint) virtual external; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } abstract contract INFTXStakingZap is IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { IWETH public immutable WETH; INFTXLPStaking public immutable lpStaking; INFTXVaultFactory public immutable nftxFactory; IUniswapV2Router01 public immutable sushiRouter; uint256 public lockTime; constructor(address _nftxFactory, address _sushiRouter) { nftxFactory = INFTXVaultFactory(_nftxFactory); lpStaking = INFTXLPStaking(INFTXFeeDistributor(INFTXVaultFactory(_nftxFactory).feeDistributor()).lpStaking()); sushiRouter = IUniswapV2Router01(_sushiRouter); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); IERC20Upgradeable(address(IUniswapV2Router01(_sushiRouter).WETH())).approve(_sushiRouter, type(uint256).max); } function setLockTime(uint256 newLockTime) virtual external; function addLiquidity721ETH( uint256 vaultId, uint256[] memory ids, uint256 minWethIn ) virtual external payable returns (uint256); function addLiquidity721ETHTo( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, address to ) virtual external payable returns (uint256); function addLiquidity1155ETH( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minEthIn ) virtual external payable returns (uint256); function addLiquidity1155ETHTo( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minEthIn, address to ) virtual external payable returns (uint256); function addLiquidity721( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn ) virtual external returns (uint256); function addLiquidity721To( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn, address to ) virtual external returns (uint256); function addLiquidity1155( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn ) virtual external returns (uint256); function addLiquidity1155To( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn, address to ) virtual external returns (uint256); function lockedUntil(uint256 vaultId, address who) virtual external view returns (uint256); function lockedLPBalance(uint256 vaultId, address who) virtual external view returns (uint256); receive() virtual external payable; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // 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: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathUD60x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18 /// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60 /// 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 uint256. library PRBMathUD60x18 { /// @dev Half the SCALE number. uint256 internal constant HALF_SCALE = 5e17; /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number. uint256 internal constant LOG2_E = 1_442695040888963407; /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number. function avg(uint256 x, uint256 y) internal pure returns (uint256 result) { // The operations can never overflow. unchecked { // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice. result = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @notice Yields the least unsigned 60.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_UD60x18. /// /// @param x The unsigned 60.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number. function ceil(uint256 x) internal pure returns (uint256 result) { if (x > MAX_WHOLE_UD60x18) { revert PRBMathUD60x18__CeilOverflow(x); } assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "SCALE - remainder" but faster. let delta := sub(SCALE, remainder) // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number. /// /// @dev Uses mulDiv to enable overflow-safe multiplication and division. /// /// Requirements: /// - The denominator cannot be zero. /// /// @param x The numerator as an unsigned 60.18-decimal fixed-point number. /// @param y The denominator as an unsigned 60.18-decimal fixed-point number. /// @param result The quotient as an unsigned 60.18-decimal fixed-point number. function div(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDiv(x, SCALE, y); } /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (uint256 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. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp(uint256 x) internal pure returns (uint256 result) { // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathUD60x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { uint256 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_UD60x18. /// /// @param x The exponent as an unsigned 60.18-decimal 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) { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (x << 64) / SCALE; // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation. result = PRBMath.exp2(x192x64); } } /// @notice Yields the greatest unsigned 60.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. /// @param x The unsigned 60.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number. function floor(uint256 x) internal pure returns (uint256 result) { assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x. /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part. /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number. function frac(uint256 x) internal pure returns (uint256 result) { assembly { result := mod(x, SCALE) } } /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be less than or equal to MAX_UD60x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in unsigned 60.18-decimal fixed-point representation. function fromUint(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__FromUintOverflow(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_UD60x18, lest it overflows. /// /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function gm(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xy = x * y; if (xy / x != y) { revert PRBMathUD60x18__GmOverflow(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 = PRBMath.sqrt(xy); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as an unsigned 60.18-decimal fixed-point number. function inv(uint256 x) internal pure returns (uint256 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 2.718281828459045235, for that we would need more fine-grained precision. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number. function ln(uint256 x) internal pure returns (uint256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 196205294292027477728. 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 unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number. function log10(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly multiplication 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) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) } default { result := MAX_UD60x18 } } if (result == MAX_UD60x18) { // 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 or equal to SCALE, otherwise the result would be negative. /// /// Caveats: /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number. function log2(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(x / SCALE); // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255 and SCALE is 1e18. result = n * SCALE; // This is y = x * 2^(-n). uint256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (uint256 delta = 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; } } } } /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal /// fixed-point number. /// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function. /// @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 product as an unsigned 60.18-decimal fixed-point number. function mul(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDivFixedPoint(x, y); } /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number. function pi() internal pure returns (uint256 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". /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number. /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number. /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number. function pow(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { result = y == 0 ? SCALE : uint256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (unsigned 60.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: /// - The result must fit within MAX_UD60x18. /// /// Caveats: /// - All from "mul". /// - Assumes 0^0 is 1. /// /// @param x The base as an unsigned 60.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function powu(uint256 x, uint256 y) internal pure returns (uint256 result) { // Calculate the first iteration of the loop in advance. result = y & 1 > 0 ? x : SCALE; // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { x = PRBMath.mulDivFixedPoint(x, x); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { result = PRBMath.mulDivFixedPoint(result, x); } } } /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number. function scale() internal pure returns (uint256 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 must be less than MAX_UD60x18 / SCALE. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as an unsigned 60.18-decimal fixed-point . function sqrt(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = PRBMath.sqrt(x * SCALE); } } /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The unsigned 60.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toUint(uint256 x) internal pure returns (uint256 result) { unchecked { result = x / SCALE; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/IBeacon.sol"; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // SPDX-License-Identifier: MIT 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 childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external returns (address); function lpStaking() external returns (address); function treasury() external returns (address); function defaultTreasuryAlloc() external returns (uint256); function defaultLPAlloc() external returns (uint256); function allocTotal(uint256 vaultId) external returns (uint256); function specificTreasuryAlloc(uint256 vaultId) external returns (uint256); // Write functions. function __FeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeMultipleReceiverAlloc( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, uint256[] memory allocPoints ) external; function changeMultipleReceiverAddress( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, address[] memory addresses, bool[] memory isContracts ) external; function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setDefaultTreasuryAlloc(uint256 _allocPoint) external; function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external; function setLPStakingAddress(address _lpStaking) external; function setNFTXVaultFactory(address _factory) external; function setDefaultLPAlloc(uint256 _allocPoint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface ITimelockRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __TimelockRewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function timelockMint(address account, uint256 amount, uint256 timelockLength) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); function timelockUntil(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721ReceiverUpgradeable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is IERC721ReceiverUpgradeable { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../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 meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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: Unlicense pragma solidity >=0.8.4; /// @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 closest power of two that is higher than 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; } } }
event CustomEligibilityDeployed(address eligibilityAddr); This function allows for an easy setup of any eligibility module contract from the EligibilityManager. It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow a similar interface. The manager has control over options like fees and features
interface INFTXVault is IERC20Upgradeable { function manager() external view returns (address); function assetAddress() external view returns (address); function vaultFactory() external view returns (INFTXVaultFactory); function eligibilityStorage() external view returns (INFTXEligibility); function is1155() external view returns (bool); function allowAllItems() external view returns (bool); function enableMint() external view returns (bool); function enableRandomRedeem() external view returns (bool); function enableTargetRedeem() external view returns (bool); function enableRandomSwap() external view returns (bool); function enableTargetSwap() external view returns (bool); function vaultId() external view returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external view returns (uint256); function randomRedeemFee() external view returns (uint256); function targetRedeemFee() external view returns (uint256); function randomSwapFee() external view returns (uint256); function targetSwapFee() external view returns (uint256); function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event EnableRandomSwapUpdated(bool enabled); event EnableTargetSwapUpdated(bool enabled); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem, bool _enableRandomSwap, bool _enableTargetSwap ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee, uint256 _randomSwapFee, uint256 _targetSwapFee ) external; function disableVaultFees() external; function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); }
884,312
pragma solidity ^0.4.25; // solium-disable-line linebreak-style /** * @author Anatolii Kucheruk ([email protected]) * @author Platin Limited, platin.io ([email protected]) */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; /** * @dev Reclaim all ERC20Basic compatible tokens * @param _token ERC20Basic The address of the token contract */ function reclaimToken(ERC20Basic _token) external onlyOwner { uint256 balance = _token.balanceOf(this); _token.safeTransfer(owner, balance); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this Ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by setting a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC223 compatible tokens * @param _from address The address that is transferring the tokens * @param _value uint256 the amount of the specified token * @param _data Bytes The data passed from the caller. */ function tokenFallback( address _from, uint256 _value, bytes _data ) external pure { _from; _value; _data; revert(); } } /** * @title Contracts that should not own Contracts * @author Remco Bloemen <remco@2π.com> * @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner * of this contract to reclaim ownership of the contracts. */ contract HasNoContracts is Ownable { /** * @dev Reclaim ownership of Ownable contracts * @param _contractAddr The address of the Ownable to be reclaimed. */ function reclaimContract(address _contractAddr) external onlyOwner { Ownable contractInst = Ownable(_contractAddr); contractInst.transferOwnership(owner); } } /** * @title Base contract for contracts that should not own things. * @author Remco Bloemen <remco@2π.com> * @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or * Owned contracts. See respective base contracts for details. */ contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts { } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Authorizable * @dev Authorizable contract holds a list of control addresses that authorized to do smth. */ contract Authorizable is Ownable { // List of authorized (control) addresses mapping (address => bool) public authorized; // Authorize event logging event Authorize(address indexed who); // UnAuthorize event logging event UnAuthorize(address indexed who); // onlyAuthorized modifier, restrict to the owner and the list of authorized addresses modifier onlyAuthorized() { require(msg.sender == owner || authorized[msg.sender], "Not Authorized."); _; } /** * @dev Authorize given address * @param _who address Address to authorize */ function authorize(address _who) public onlyOwner { require(_who != address(0), "Address can't be zero."); require(!authorized[_who], "Already authorized"); authorized[_who] = true; emit Authorize(_who); } /** * @dev unAuthorize given address * @param _who address Address to unauthorize */ function unAuthorize(address _who) public onlyOwner { require(_who != address(0), "Address can't be zero."); require(authorized[_who], "Address is not authorized"); authorized[_who] = false; emit UnAuthorize(_who); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Holders Token * @dev Extension to the OpenZepellin's StandardToken contract to track token holders. * Only holders with the non-zero balance are listed. */ contract HoldersToken is StandardToken { using SafeMath for uint256; // holders list address[] public holders; // holder number in the list mapping (address => uint256) public holderNumber; /** * @dev Get the holders count * @return uint256 Holders count */ function holdersCount() public view returns (uint256) { return holders.length; } /** * @dev Transfer tokens from one address to another preserving token holders * @param _to address The address which you want to transfer to * @param _value uint256 The amount of tokens to be transferred * @return bool Returns true if the transfer was succeeded */ function transfer(address _to, uint256 _value) public returns (bool) { _preserveHolders(msg.sender, _to, _value); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another preserving token holders * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 The amount of tokens to be transferred * @return bool Returns true if the transfer was succeeded */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { _preserveHolders(_from, _to, _value); return super.transferFrom(_from, _to, _value); } /** * @dev Remove holder from the holders list * @param _holder address Address of the holder to remove */ function _removeHolder(address _holder) internal { uint256 _number = holderNumber[_holder]; if (_number == 0 || holders.length == 0 || _number > holders.length) return; uint256 _index = _number.sub(1); uint256 _lastIndex = holders.length.sub(1); address _lastHolder = holders[_lastIndex]; if (_index != _lastIndex) { holders[_index] = _lastHolder; holderNumber[_lastHolder] = _number; } holderNumber[_holder] = 0; holders.length = _lastIndex; } /** * @dev Add holder to the holders list * @param _holder address Address of the holder to add */ function _addHolder(address _holder) internal { if (holderNumber[_holder] == 0) { holders.push(_holder); holderNumber[_holder] = holders.length; } } /** * @dev Preserve holders during transfers * @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 _preserveHolders(address _from, address _to, uint256 _value) internal { _addHolder(_to); if (balanceOf(_from).sub(_value) == 0) _removeHolder(_from); } } /** * @title PlatinTGE * @dev Platin Token Generation Event contract. It holds token economic constants and makes initial token allocation. * Initial token allocation function should be called outside the blockchain at the TGE moment of time, * from here on out, Platin Token and other Platin contracts become functional. */ contract PlatinTGE { using SafeMath for uint256; // Token decimals uint8 public constant decimals = 18; // solium-disable-line uppercase // Total Tokens Supply uint256 public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint256(decimals)); // 1,000,000,000 PTNX // SUPPLY // TOTAL_SUPPLY = 1,000,000,000 PTNX, is distributed as follows: uint256 public constant SALES_SUPPLY = 300000000 * (10 ** uint256(decimals)); // 300,000,000 PTNX - 30% uint256 public constant MINING_POOL_SUPPLY = 200000000 * (10 ** uint256(decimals)); // 200,000,000 PTNX - 20% uint256 public constant FOUNDERS_AND_EMPLOYEES_SUPPLY = 200000000 * (10 ** uint256(decimals)); // 200,000,000 PTNX - 20% uint256 public constant AIRDROPS_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals)); // 100,000,000 PTNX - 10% uint256 public constant RESERVES_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals)); // 100,000,000 PTNX - 10% uint256 public constant ADVISORS_POOL_SUPPLY = 70000000 * (10 ** uint256(decimals)); // 70,000,000 PTNX - 7% uint256 public constant ECOSYSTEM_POOL_SUPPLY = 30000000 * (10 ** uint256(decimals)); // 30,000,000 PTNX - 3% // HOLDERS address public PRE_ICO_POOL; // solium-disable-line mixedcase address public LIQUID_POOL; // solium-disable-line mixedcase address public ICO; // solium-disable-line mixedcase address public MINING_POOL; // solium-disable-line mixedcase address public FOUNDERS_POOL; // solium-disable-line mixedcase address public EMPLOYEES_POOL; // solium-disable-line mixedcase address public AIRDROPS_POOL; // solium-disable-line mixedcase address public RESERVES_POOL; // solium-disable-line mixedcase address public ADVISORS_POOL; // solium-disable-line mixedcase address public ECOSYSTEM_POOL; // solium-disable-line mixedcase // HOLDER AMOUNT AS PART OF SUPPLY // SALES_SUPPLY = PRE_ICO_POOL_AMOUNT + LIQUID_POOL_AMOUNT + ICO_AMOUNT uint256 public constant PRE_ICO_POOL_AMOUNT = 20000000 * (10 ** uint256(decimals)); // 20,000,000 PTNX uint256 public constant LIQUID_POOL_AMOUNT = 100000000 * (10 ** uint256(decimals)); // 100,000,000 PTNX uint256 public constant ICO_AMOUNT = 180000000 * (10 ** uint256(decimals)); // 180,000,000 PTNX // FOUNDERS_AND_EMPLOYEES_SUPPLY = FOUNDERS_POOL_AMOUNT + EMPLOYEES_POOL_AMOUNT uint256 public constant FOUNDERS_POOL_AMOUNT = 190000000 * (10 ** uint256(decimals)); // 190,000,000 PTNX uint256 public constant EMPLOYEES_POOL_AMOUNT = 10000000 * (10 ** uint256(decimals)); // 10,000,000 PTNX // Unsold tokens reserve address address public UNSOLD_RESERVE; // solium-disable-line mixedcase // Tokens ico sale with lockup period uint256 public constant ICO_LOCKUP_PERIOD = 182 days; // Platin Token ICO rate, regular uint256 public constant TOKEN_RATE = 1000; // Platin Token ICO rate with lockup, 20% bonus uint256 public constant TOKEN_RATE_LOCKUP = 1200; // Platin ICO min purchase amount uint256 public constant MIN_PURCHASE_AMOUNT = 1 ether; // Platin Token contract PlatinToken public token; // TGE time uint256 public tgeTime; /** * @dev Constructor * @param _tgeTime uint256 TGE moment of time * @param _token address Address of the Platin Token contract * @param _preIcoPool address Address of the Platin PreICO Pool * @param _liquidPool address Address of the Platin Liquid Pool * @param _ico address Address of the Platin ICO contract * @param _miningPool address Address of the Platin Mining Pool * @param _foundersPool address Address of the Platin Founders Pool * @param _employeesPool address Address of the Platin Employees Pool * @param _airdropsPool address Address of the Platin Airdrops Pool * @param _reservesPool address Address of the Platin Reserves Pool * @param _advisorsPool address Address of the Platin Advisors Pool * @param _ecosystemPool address Address of the Platin Ecosystem Pool * @param _unsoldReserve address Address of the Platin Unsold Reserve */ constructor( uint256 _tgeTime, PlatinToken _token, address _preIcoPool, address _liquidPool, address _ico, address _miningPool, address _foundersPool, address _employeesPool, address _airdropsPool, address _reservesPool, address _advisorsPool, address _ecosystemPool, address _unsoldReserve ) public { require(_tgeTime >= block.timestamp, "TGE time should be >= current time."); // solium-disable-line security/no-block-members require(_token != address(0), "Token address can't be zero."); require(_preIcoPool != address(0), "PreICO Pool address can't be zero."); require(_liquidPool != address(0), "Liquid Pool address can't be zero."); require(_ico != address(0), "ICO address can't be zero."); require(_miningPool != address(0), "Mining Pool address can't be zero."); require(_foundersPool != address(0), "Founders Pool address can't be zero."); require(_employeesPool != address(0), "Employees Pool address can't be zero."); require(_airdropsPool != address(0), "Airdrops Pool address can't be zero."); require(_reservesPool != address(0), "Reserves Pool address can't be zero."); require(_advisorsPool != address(0), "Advisors Pool address can't be zero."); require(_ecosystemPool != address(0), "Ecosystem Pool address can't be zero."); require(_unsoldReserve != address(0), "Unsold reserve address can't be zero."); // Setup tge time tgeTime = _tgeTime; // Setup token address token = _token; // Setup holder addresses PRE_ICO_POOL = _preIcoPool; LIQUID_POOL = _liquidPool; ICO = _ico; MINING_POOL = _miningPool; FOUNDERS_POOL = _foundersPool; EMPLOYEES_POOL = _employeesPool; AIRDROPS_POOL = _airdropsPool; RESERVES_POOL = _reservesPool; ADVISORS_POOL = _advisorsPool; ECOSYSTEM_POOL = _ecosystemPool; // Setup unsold reserve address UNSOLD_RESERVE = _unsoldReserve; } /** * @dev Allocate function. Token Generation Event entry point. * It makes initial token allocation according to the initial token supply constants. */ function allocate() public { // Should be called just after tge time require(block.timestamp >= tgeTime, "Should be called just after tge time."); // solium-disable-line security/no-block-members // Should not be allocated already require(token.totalSupply() == 0, "Allocation is already done."); // SALES token.allocate(PRE_ICO_POOL, PRE_ICO_POOL_AMOUNT); token.allocate(LIQUID_POOL, LIQUID_POOL_AMOUNT); token.allocate(ICO, ICO_AMOUNT); // MINING POOL token.allocate(MINING_POOL, MINING_POOL_SUPPLY); // FOUNDERS AND EMPLOYEES token.allocate(FOUNDERS_POOL, FOUNDERS_POOL_AMOUNT); token.allocate(EMPLOYEES_POOL, EMPLOYEES_POOL_AMOUNT); // AIRDROPS POOL token.allocate(AIRDROPS_POOL, AIRDROPS_POOL_SUPPLY); // RESERVES POOL token.allocate(RESERVES_POOL, RESERVES_POOL_SUPPLY); // ADVISORS POOL token.allocate(ADVISORS_POOL, ADVISORS_POOL_SUPPLY); // ECOSYSTEM POOL token.allocate(ECOSYSTEM_POOL, ECOSYSTEM_POOL_SUPPLY); // Check Token Total Supply require(token.totalSupply() == TOTAL_SUPPLY, "Total supply check error."); } } /** * @title PlatinToken * @dev Platin PTNX Token contract. Tokens are allocated during TGE. * Token contract is a standard ERC20 token with additional capabilities: TGE allocation, holders tracking and lockup. * Initial allocation should be invoked by the TGE contract at the TGE moment of time. * Token contract holds list of token holders, the list includes holders with positive balance only. * Authorized holders can transfer token with lockup(s). Lockups can be refundable. * Lockups is a list of releases dates and releases amounts. * In case of refund previous holder can get back locked up tokens. Only still locked up amounts can be transferred back. */ contract PlatinToken is HoldersToken, NoOwner, Authorizable, Pausable { using SafeMath for uint256; string public constant name = "Platin Token"; // solium-disable-line uppercase string public constant symbol = "PTNX"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase // lockup sruct struct Lockup { uint256 release; // release timestamp uint256 amount; // amount of tokens to release } // list of lockups mapping (address => Lockup[]) public lockups; // list of lockups that can be refunded mapping (address => mapping (address => Lockup[])) public refundable; // idexes mapping from refundable to lockups lists mapping (address => mapping (address => mapping (uint256 => uint256))) public indexes; // Platin TGE contract PlatinTGE public tge; // allocation event logging event Allocate(address indexed to, uint256 amount); // lockup event logging event SetLockups(address indexed to, uint256 amount, uint256 fromIdx, uint256 toIdx); // refund event logging event Refund(address indexed from, address indexed to, uint256 amount); // spotTransfer modifier, check balance spot on transfer modifier spotTransfer(address _from, uint256 _value) { require(_value <= balanceSpot(_from), "Attempt to transfer more than balance spot."); _; } // onlyTGE modifier, restrict to the TGE contract only modifier onlyTGE() { require(msg.sender == address(tge), "Only TGE method."); _; } /** * @dev Set TGE contract * @param _tge address PlatinTGE contract address */ function setTGE(PlatinTGE _tge) external onlyOwner { require(tge == address(0), "TGE is already set."); require(_tge != address(0), "TGE address can't be zero."); tge = _tge; authorize(_tge); } /** * @dev Allocate tokens during TGE * @param _to address Address gets the tokens * @param _amount uint256 Amount to allocate */ function allocate(address _to, uint256 _amount) external onlyTGE { require(_to != address(0), "Allocate To address can't be zero"); require(_amount > 0, "Allocate amount should be > 0."); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); _addHolder(_to); require(totalSupply_ <= tge.TOTAL_SUPPLY(), "Can't allocate more than TOTAL SUPPLY."); emit Allocate(_to, _amount); emit Transfer(address(0), _to, _amount); } /** * @dev Transfer tokens from one address to another * @param _to address The address which you want to transfer to * @param _value uint256 The amount of tokens to be transferred * @return bool Returns true if the transfer was succeeded */ function transfer(address _to, uint256 _value) public whenNotPaused spotTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @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 * @return bool Returns true if the transfer was succeeded */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused spotTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Transfer tokens from one address to another with lockup * @param _to address The address which you want to transfer to * @param _value uint256 The amount of tokens to be transferred * @param _lockupReleases uint256[] List of lockup releases * @param _lockupAmounts uint256[] List of lockup amounts * @param _refundable bool Is locked up amount refundable * @return bool Returns true if the transfer was succeeded */ function transferWithLockup( address _to, uint256 _value, uint256[] _lockupReleases, uint256[] _lockupAmounts, bool _refundable ) public onlyAuthorized returns (bool) { transfer(_to, _value); _lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable); // solium-disable-line arg-overflow } /** * @dev Transfer tokens from one address to another with lockup * @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 * @param _lockupReleases uint256[] List of lockup releases * @param _lockupAmounts uint256[] List of lockup amounts * @param _refundable bool Is locked up amount refundable * @return bool Returns true if the transfer was succeeded */ function transferFromWithLockup( address _from, address _to, uint256 _value, uint256[] _lockupReleases, uint256[] _lockupAmounts, bool _refundable ) public onlyAuthorized returns (bool) { transferFrom(_from, _to, _value); _lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable); // solium-disable-line arg-overflow } /** * @dev Refund refundable locked up amount * @param _from address The address which you want to refund tokens from * @return uint256 Returns amount of refunded tokens */ function refundLockedUp( address _from ) public onlyAuthorized returns (uint256) { address _sender = msg.sender; uint256 _balanceRefundable = 0; uint256 _refundableLength = refundable[_from][_sender].length; if (_refundableLength > 0) { uint256 _lockupIdx; for (uint256 i = 0; i < _refundableLength; i++) { if (refundable[_from][_sender][i].release > block.timestamp) { // solium-disable-line security/no-block-members _balanceRefundable = _balanceRefundable.add(refundable[_from][_sender][i].amount); refundable[_from][_sender][i].release = 0; refundable[_from][_sender][i].amount = 0; _lockupIdx = indexes[_from][_sender][i]; lockups[_from][_lockupIdx].release = 0; lockups[_from][_lockupIdx].amount = 0; } } if (_balanceRefundable > 0) { _preserveHolders(_from, _sender, _balanceRefundable); balances[_from] = balances[_from].sub(_balanceRefundable); balances[_sender] = balances[_sender].add(_balanceRefundable); emit Refund(_from, _sender, _balanceRefundable); emit Transfer(_from, _sender, _balanceRefundable); } } return _balanceRefundable; } /** * @dev Get the lockups list count * @param _who address Address owns locked up list * @return uint256 Lockups list count */ function lockupsCount(address _who) public view returns (uint256) { return lockups[_who].length; } /** * @dev Find out if the address has lockups * @param _who address Address checked for lockups * @return bool Returns true if address has lockups */ function hasLockups(address _who) public view returns (bool) { return lockups[_who].length > 0; } /** * @dev Get balance locked up at the current moment of time * @param _who address Address owns locked up amounts * @return uint256 Balance locked up at the current moment of time */ function balanceLockedUp(address _who) public view returns (uint256) { uint256 _balanceLokedUp = 0; uint256 _lockupsLength = lockups[_who].length; for (uint256 i = 0; i < _lockupsLength; i++) { if (lockups[_who][i].release > block.timestamp) // solium-disable-line security/no-block-members _balanceLokedUp = _balanceLokedUp.add(lockups[_who][i].amount); } return _balanceLokedUp; } /** * @dev Get refundable locked up balance at the current moment of time * @param _who address Address owns locked up amounts * @param _sender address Address owned locked up amounts * @return uint256 Locked up refundable balance at the current moment of time */ function balanceRefundable(address _who, address _sender) public view returns (uint256) { uint256 _balanceRefundable = 0; uint256 _refundableLength = refundable[_who][_sender].length; if (_refundableLength > 0) { for (uint256 i = 0; i < _refundableLength; i++) { if (refundable[_who][_sender][i].release > block.timestamp) // solium-disable-line security/no-block-members _balanceRefundable = _balanceRefundable.add(refundable[_who][_sender][i].amount); } } return _balanceRefundable; } /** * @dev Get balance spot for the current moment of time * @param _who address Address owns balance spot * @return uint256 Balance spot for the current moment of time */ function balanceSpot(address _who) public view returns (uint256) { uint256 _balanceSpot = balanceOf(_who); _balanceSpot = _balanceSpot.sub(balanceLockedUp(_who)); return _balanceSpot; } /** * @dev Lockup amount till release time * @param _who address Address gets the locked up amount * @param _amount uint256 Amount to lockup * @param _lockupReleases uint256[] List of lockup releases * @param _lockupAmounts uint256[] List of lockup amounts * @param _refundable bool Is locked up amount refundable */ function _lockup( address _who, uint256 _amount, uint256[] _lockupReleases, uint256[] _lockupAmounts, bool _refundable) internal { require(_lockupReleases.length == _lockupAmounts.length, "Length of lockup releases and amounts lists should be equal."); require(_lockupReleases.length.add(lockups[_who].length) <= 1000, "Can't be more than 1000 lockups per address."); if (_lockupReleases.length > 0) { uint256 _balanceLokedUp = 0; address _sender = msg.sender; uint256 _fromIdx = lockups[_who].length; uint256 _toIdx = _fromIdx + _lockupReleases.length - 1; uint256 _lockupIdx; uint256 _refundIdx; for (uint256 i = 0; i < _lockupReleases.length; i++) { if (_lockupReleases[i] > block.timestamp) { // solium-disable-line security/no-block-members lockups[_who].push(Lockup(_lockupReleases[i], _lockupAmounts[i])); _balanceLokedUp = _balanceLokedUp.add(_lockupAmounts[i]); if (_refundable) { refundable[_who][_sender].push(Lockup(_lockupReleases[i], _lockupAmounts[i])); _lockupIdx = lockups[_who].length - 1; _refundIdx = refundable[_who][_sender].length - 1; indexes[_who][_sender][_refundIdx] = _lockupIdx; } } } require(_balanceLokedUp <= _amount, "Can't lockup more than transferred amount."); emit SetLockups(_who, _amount, _fromIdx, _toIdx); // solium-disable-line arg-overflow } } }
Add holder to the holders list _holder address Address of the holder to add/
function _addHolder(address _holder) internal { if (holderNumber[_holder] == 0) { holders.push(_holder); holderNumber[_holder] = holders.length; } }
6,360,405
pragma solidity 0.6.6; import "../KyberNetwork.sol"; /* * @title Malicious Kyber Network, takes (steals) some extra fees and reports actual dest amount minus Fees. */ contract MaliciousKyberNetwork is KyberNetwork { uint256 public myFeeWei = 10; constructor(address _admin, IKyberStorage _kyberStorage) public KyberNetwork(_admin, _kyberStorage) {} function setMyFeeWei(uint256 fee) public { myFeeWei = fee; } /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Trade API for kyberNetwork /// @param tradeData Main trade data object for trade info to be stored function trade(TradeData memory tradeData, bytes memory hint) internal virtual nonReentrant override returns (uint256 destAmount) { tradeData.networkFeeBps = getAndUpdateNetworkFee(); validateTradeInput(tradeData.input); uint256 rateWithNetworkFee; (destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint); require(rateWithNetworkFee > 0, "trade invalid, if hint involved, try parseHint API"); require(rateWithNetworkFee < MAX_RATE, "rate > MAX_RATE"); require(rateWithNetworkFee >= tradeData.input.minConversionRate, "rate < min rate"); uint256 actualSrcAmount; if (destAmount > tradeData.input.maxDestAmount) { // notice tradeData passed by reference and updated destAmount = tradeData.input.maxDestAmount; actualSrcAmount = calcTradeSrcAmountFromDest(tradeData); } else { actualSrcAmount = tradeData.input.srcAmount; } // token -> eth doReserveTrades( tradeData.input.src, ETH_TOKEN_ADDRESS, address(this), tradeData.tokenToEth, tradeData.tradeWei, tradeData.tokenToEth.decimals, ETH_DECIMALS ); // eth -> token doReserveTrades( ETH_TOKEN_ADDRESS, tradeData.input.dest, tradeData.input.destAddress, tradeData.ethToToken, destAmount, ETH_DECIMALS, tradeData.ethToToken.decimals ); handleChange( tradeData.input.src, tradeData.input.srcAmount, actualSrcAmount, tradeData.input.trader ); handleFees(tradeData); emit KyberTrade({ src: tradeData.input.src, dest: tradeData.input.dest, ethWeiValue: tradeData.tradeWei, networkFeeWei: tradeData.networkFeeWei, customPlatformFeeWei: tradeData.platformFeeWei, t2eIds: tradeData.tokenToEth.ids, e2tIds: tradeData.ethToToken.ids, t2eSrcAmounts: tradeData.tokenToEth.srcAmounts, e2tSrcAmounts: tradeData.ethToToken.srcAmounts, t2eRates: tradeData.tokenToEth.rates, e2tRates: tradeData.ethToToken.rates }); if (gasHelper != IGasHelper(0)) { (bool success, ) = address(gasHelper).call( abi.encodeWithSignature( "freeGas(address,address,address,uint256,bytes32[],bytes32[])", tradeData.input.platformWallet, tradeData.input.src, tradeData.input.dest, tradeData.tradeWei, tradeData.tokenToEth.ids, tradeData.ethToToken.ids ) ); // remove compilation warning success; } return (destAmount - myFeeWei); } /// @notice Use token address ETH_TOKEN_ADDRESS for ether /// @dev Do one trade with each reserve in reservesData, verifying network balance /// as expected to ensure reserves take correct src amount /// @param src Source token /// @param dest Destination token /// @param destAddress Address to send tokens to /// @param reservesData reservesData to trade /// @param expectedDestAmount Amount to be transferred to destAddress /// @param srcDecimals Decimals of source token /// @param destDecimals Decimals of destination token function doReserveTrades( IERC20 src, IERC20 dest, address payable destAddress, ReservesData memory reservesData, uint256 expectedDestAmount, uint256 srcDecimals, uint256 destDecimals ) internal virtual override { if (src == dest) { // eth -> eth, need not do anything except for token -> eth: transfer eth to destAddress if (destAddress != (address(this))) { (bool success, ) = destAddress.call{value: expectedDestAmount - myFeeWei}(""); require(success, "send dest qty failed"); } return; } tradeAndVerifyNetworkBalance( reservesData, src, dest, srcDecimals, destDecimals ); if (destAddress != address(this)) { // for eth -> token / token -> token, transfer tokens to destAddress dest.safeTransfer(destAddress, expectedDestAmount - myFeeWei); } } // overwrite function to reduce bytecode size function removeKyberProxy(address kyberProxy) external virtual override {} }
Use token address ETH_TOKEN_ADDRESS for ether Trade API for kyberNetwork tradeData Main trade data object for trade info to be stored notice tradeData passed by reference and updated remove compilation warning
function trade(TradeData memory tradeData, bytes memory hint) internal virtual nonReentrant override returns (uint256 destAmount) { tradeData.networkFeeBps = getAndUpdateNetworkFee(); validateTradeInput(tradeData.input); uint256 rateWithNetworkFee; (destAmount, rateWithNetworkFee) = calcRatesAndAmounts(tradeData, hint); require(rateWithNetworkFee > 0, "trade invalid, if hint involved, try parseHint API"); require(rateWithNetworkFee < MAX_RATE, "rate > MAX_RATE"); require(rateWithNetworkFee >= tradeData.input.minConversionRate, "rate < min rate"); uint256 actualSrcAmount; if (destAmount > tradeData.input.maxDestAmount) { destAmount = tradeData.input.maxDestAmount; actualSrcAmount = calcTradeSrcAmountFromDest(tradeData); actualSrcAmount = tradeData.input.srcAmount; } tradeData.input.src, ETH_TOKEN_ADDRESS, address(this), tradeData.tokenToEth, tradeData.tradeWei, tradeData.tokenToEth.decimals, ETH_DECIMALS ); ETH_TOKEN_ADDRESS, tradeData.input.dest, tradeData.input.destAddress, tradeData.ethToToken, destAmount, ETH_DECIMALS, tradeData.ethToToken.decimals ); handleChange( tradeData.input.src, tradeData.input.srcAmount, actualSrcAmount, tradeData.input.trader ); handleFees(tradeData); emit KyberTrade({ src: tradeData.input.src, dest: tradeData.input.dest, ethWeiValue: tradeData.tradeWei, networkFeeWei: tradeData.networkFeeWei, customPlatformFeeWei: tradeData.platformFeeWei, t2eIds: tradeData.tokenToEth.ids, e2tIds: tradeData.ethToToken.ids, t2eSrcAmounts: tradeData.tokenToEth.srcAmounts, e2tSrcAmounts: tradeData.ethToToken.srcAmounts, t2eRates: tradeData.tokenToEth.rates, e2tRates: tradeData.ethToToken.rates }); if (gasHelper != IGasHelper(0)) { (bool success, ) = address(gasHelper).call( abi.encodeWithSignature( "freeGas(address,address,address,uint256,bytes32[],bytes32[])", tradeData.input.platformWallet, tradeData.input.src, tradeData.input.dest, tradeData.tradeWei, tradeData.tokenToEth.ids, tradeData.ethToToken.ids ) ); success; } return (destAmount - myFeeWei); }
7,322,657
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "../utils/AccessControlled.sol"; import "../interfaces/ICommodity.sol"; /** * @title Commodity * * @notice Fungible units used for trading and forging Byzantian Crystals * @dev Use of variable name 'value' in this contract is to be consistent with ERC20 code -- * elsewhere in this project, 'value' is referred to as 'amount'. */ contract Commodity is ERC20, ERC20Detailed, AccessControlled { uint public miningReward; bytes32 public miningTarget; bytes32 public prevMiningHash; // Mapping of block number to bool indicating if commodity was mined // (so each commodity can be mined only once per block) mapping (uint => bool) private wasMinedInBlock; constructor(string _name, string _symbol, uint _miningReward, bytes32 _miningTarget) ERC20Detailed(_name, _symbol, 0) public { miningReward = _miningReward; miningTarget = _miningTarget; prevMiningHash = sha256(abi.encodePacked("0")); } /** * @notice Creates more of a token for an account * @dev Called by GIA when commodity is mined * @param _to Address of account to transfer to * @return boolean true on success */ function dispenseReward(address _to, bytes32 _hash) public onlyGIA returns (bool) { require(wasMinedInBlock[block.number] == false, "Commodity already mined this block"); require(_hash < miningTarget, "That hash is not valid"); _mint(_to, miningReward); prevMiningHash = _hash; miningReward = miningReward.sub(1); wasMinedInBlock[block.number] = true; return true; } /** * @notice Transfers token into escrow on the contract * @dev Called when sell order created for token * @param _from Address of account to transfer from * @param _value Quantity of token to transfer * @return boolean true on success */ function transferToEscrow(address _from, uint _value) public onlyGEA returns (bool) { _transfer(_from, geaAddress, _value); return true; } /** * @notice Burns a specified amount of the token * @dev Called when forging a crystal * @dev Can only be accessed by Temple Authority * @param _account Address of account to burn token from * @param _value Quantity of token to burn * @return boolean true on success */ function burn(address _account, uint _value) public onlyTA returns (bool) { _burn(_account, _value); return true; } }
Transfers token into escrow on the contract Called when sell order created for token _from Address of account to transfer from _value Quantity of token to transfer return boolean true on success/
function transferToEscrow(address _from, uint _value) public onlyGEA returns (bool) { _transfer(_from, geaAddress, _value); return true; }
2,485,499
// SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE"); modifier onlyValidatorManager() { require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required"); _; } modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyValidatorManager { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } pragma solidity ^0.6.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))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // 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: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 62893; uint public constant BROADCAST_DELTA = 131000; uint public constant COMPLAINT_BAD_DATA_DELTA = 49580; uint public constant PRE_RESPONSE_DELTA = 74500; uint public constant COMPLAINT_DELTA = 76221; uint public constant RESPONSE_DELTA = 183000; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyConstantsHolderManager { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyConstantsHolderManager { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe, IContractManager { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress( string calldata contractsName, address newContractsAddress ) external override onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view override returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE"); modifier onlyBountyReductionManager() { require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required"); _; } function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyBountyReductionManager { bountyReduction = true; } function disableBountyReduction() external onlyBountyReductionManager { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE"); // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; mapping (uint => bool) public incompliant; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrNodeManager(uint nodeIndex) { _checkNodeOrNodeManager(nodeIndex, msg.sender); _; } modifier onlyCompliance() { require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required"); _; } modifier nonZeroIP(bytes4 ip) { require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") nonZeroIP(params.ip) { // checks that Node has correct data require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } /** * @dev Marks the node as incompliant * */ function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (!incompliant[nodeIndex]) { incompliant[nodeIndex] = true; _makeNodeInvisible(nodeIndex); } } /** * @dev Marks the node as compliant * */ function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); } } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrNodeManager(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _tryToMakeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function changeIP( uint nodeIndex, bytes4 newIP, bytes4 newPublicIP ) external onlyAdmin checkNodeExists(nodeIndex) nonZeroIP(newIP) { if (newPublicIP != 0x0) { require(newIP == newPublicIP, "IP address is not the same"); nodes[nodeIndex].publicIP = newPublicIP; } nodesIPCheck[nodes[nodeIndex].ip] = false; nodesIPCheck[newIP] = true; nodes[nodeIndex].ip = newIP; } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _tryToMakeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _tryToMakeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) { _makeNodeVisible(nodeIndex); } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || hasRole(NODE_MANAGER_ROLE, msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _canBeVisible(uint nodeIndex) private view returns (bool) { return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active; } } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../ConstantsHolder.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE"); /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external { require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required"); require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE"); /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external { require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required"); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE"); modifier onlyLockerManager() { require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required"); _; } /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyLockerManager { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _setupRole(LOCKER_MANAGER_ROLE, msg.sender); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyLockerManager { _lockers.push(locker); emit LockerWasAdded(locker); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } }
Marks the node as compliant/
function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); } }
6,301,602
// SPDX-License-Identifier: MIT pragma solidity ^0.7.3; library Modular_Squaring { // It is faster to pass in the parameters then to store them in the contract // u is precomputed as in http://cacr.uwaterloo.ca/hac/about/chap14.pdf 14.42 // https://www.lirmm.fr/arith18/papers/hasenplaugh-FastModularReduction.pdf // result = x % modulus // u = (base^(2*k))/modulus (base is radix, k is bits) function square_mod( uint128[] memory a, uint128[] memory p, uint128[] memory u ) internal pure returns (uint128[] memory) { return reduce(square(a), p, u); } function reduce( uint128[] memory x, uint128[] memory p, uint128[] memory u ) internal pure returns (uint128[] memory result_array) { uint256 k = p.length; uint128[] memory q2 = multiply(x, (k - 1), x.length, u); result_array = new uint128[](k + 1); multiply(q2, k + 1, q2.length, p, result_array); subtract(x, k + 1, result_array, result_array); if (compare(result_array, p) > 0) { subtract(result_array, result_array.length, p, result_array); } } function multiply(uint128[] memory a, uint128[] memory b) internal pure returns (uint128[] memory result) { result = new uint128[](a.length + b.length); uint256 i; uint256 j; uint128 carry; uint256 a_i; uint256 temp; for (; i < a.length; ++i) { carry = 0; a_i = uint256(a[i]); for (j = 0; j < b.length; ++j) { temp = carry + a_i * b[j] + result[i + j]; result[i + j] = uint128(temp); carry = uint128(temp >> 128); } result[i + b.length] = carry; } } function multiply( uint128[] memory a, uint256 a_start, uint256 a_end, uint128[] memory b ) internal pure returns (uint128[] memory result) { result = new uint128[](a_end - a_start + b.length); uint256 i = a_start; uint256 j; uint128 carry; uint256 a_i; uint256 result_index; uint256 temp; for (; i < a_end; ++i) { carry = 0; a_i = uint256(a[i]); for (j = 0; j < b.length; ++j) { result_index = i + j - a_start; temp = carry + a_i * b[j] + result[result_index]; result[result_index] = uint128(temp); carry = uint128(temp >> 128); } result[i + b.length - a_start] = carry; } } function multiply( uint128[] memory a, uint256 a_start, uint256 a_end, uint128[] memory b, uint128[] memory result ) internal pure { uint256 i = a_start; uint256 j; uint128 carry; uint256 a_i; uint256 result_index; uint256 temp; uint256 final_index; for (; i < a_end; ++i) { carry = 0; a_i = uint256(a[i]); for (j = 0; j < b.length; ++j) { result_index = i + j - a_start; if (result_index < result.length) { temp = carry + a_i * b[j] + result[result_index]; result[result_index] = uint128(temp); carry = uint128(temp >> 128); } } final_index = i + b.length - a_start; if (final_index < result.length) { result[final_index] = carry; } } } function square(uint128[] memory a) internal pure returns (uint128[] memory) { return multiply(a, a); } function compare(uint128[] memory a, uint128[] memory b) internal pure returns (int8) { uint256 a_length = a.length; uint256 b_length = b.length; // TODO: can be reused as a_val or b_val uint256 max_length = a_length > b_length ? a_length : b_length; uint128 a_val; uint128 b_val; for (uint256 i = max_length - 1; i >= 0; --i) { a_val = i >= a_length ? 0 : a[i]; b_val = i >= b_length ? 0 : b[i]; if (a_val > b_val) return 1; if (b_val > a_val) return -1; } return 0; } // Where a > b function subtract(uint128[] memory a, uint128[] memory b) internal pure returns (uint128[] memory result) { result = new uint128[](a.length); uint8 carry; int256 b_val; int256 result_buf; for (uint256 i = 0; i < a.length; ++i) { b_val = i >= b.length ? 0 : b[i]; result_buf = a[i] - b_val - carry; result[i] = uint128(result_buf); carry = result_buf < 0 ? 1 : 0; } } // Where a > b function subtract( uint128[] memory a, uint256 a_length, uint128[] memory b ) internal pure returns (uint128[] memory result) { result = new uint128[](a_length); uint8 carry = 0; int256 b_val; int256 result_buf; for (uint256 i = 0; i < a_length; ++i) { b_val = i >= b.length ? 0 : b[i]; result_buf = a[i] - b_val - carry; result[i] = uint128(result_buf); carry = result_buf < 0 ? 1 : 0; } } // Where a > b function subtract( uint128[] memory a, uint256 a_length, uint128[] memory b, uint128[] memory result ) internal pure { uint8 carry = 0; int256 b_val; int256 result_buf; for (uint256 i = 0; i < a_length; ++i) { b_val = i >= b.length ? 0 : b[i]; result_buf = a[i] - b_val - carry; result[i] = uint128(result_buf); carry = result_buf < 0 ? 1 : 0; } } }
TODO: can be reused as a_val or b_val
function compare(uint128[] memory a, uint128[] memory b) internal pure returns (int8) { uint256 a_length = a.length; uint256 b_length = b.length; uint256 max_length = a_length > b_length ? a_length : b_length; uint128 a_val; uint128 b_val; for (uint256 i = max_length - 1; i >= 0; --i) { a_val = i >= a_length ? 0 : a[i]; b_val = i >= b_length ? 0 : b[i]; if (a_val > b_val) return 1; if (b_val > a_val) return -1; } return 0; }
15,819,227
/* Copyright 2019-2020 eMobilify GmbH 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.15; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract Registry is Ownable { // message prefix included in any signed data string private constant prefix = "\u0019Ethereum Signed Message:\n32"; /** * Events */ event OperatorUpdate(address indexed operator, string domain); event PartyUpdate( bytes2 countryCode, bytes3 partyId, address indexed partyAddress, Role[] roles, Module[] modulesSender, Module[] modulesReceiver, address indexed operatorAddress ); event DebugPacked(bytes packed); event DebugHash(bytes32 hash); /** * Admin methods */ // allow S&C to delete operator (e.g. if operator's private key is lost) function adminDeleteOperator(address operator) public onlyOwner { deleteNode(operator); } // allows owner of contract to overwrite an entry in the registry function adminDeleteParty(bytes2 countryCode, bytes3 partyId) public onlyOwner { address party = uniqueParties[countryCode][partyId]; deleteParty(party); } /** * OCN Node Operator Listings */ // address => domain name/url mapping(address => string) private nodeOf; // domain name/url => true/false mapping(string => bool) private uniqueDomains; // address => true/false mapping(address => bool) private uniqueOperators; // store operators to get list address[] private operators; /** * Create/Update the domain linked to a given operator (internal). */ function setNode(address operator, string memory domain) private { require(bytes(domain).length != 0, "Cannot set empty domain name. Use deleteNode method instead."); // check for domain uniqueness require(uniqueDomains[domain] == false, "Domain name already registered."); uniqueDomains[domain] = true; // store operator if new if (uniqueOperators[operator] == false) { operators.push(operator); } // store and log new node info uniqueOperators[operator] = true; nodeOf[operator] = domain; emit OperatorUpdate(operator, domain); } /** * Direct transaction by signer to create/update their linked domain. */ function setNode(string memory domain) public { setNode(msg.sender, domain); } /** * Raw transaction by signer to create/update another wallet's linked domain. * Requires the other wallet to have signed the same data provided. */ function setNodeRaw(address operator, string memory domain, uint8 v, bytes32 r, bytes32 s) public { bytes32 paramHash = keccak256(abi.encodePacked(operator, domain)); address signer = ecrecover(keccak256(abi.encodePacked(prefix, paramHash)), v, r, s); setNode(signer, domain); } /** * Removes a domain linked to a given node operator (internal). */ function deleteNode(address operator) private { string memory domain = nodeOf[operator]; require(bytes(domain).length > 0, "Cannot delete node that does not exist."); // delete node and log uniqueDomains[domain] = false; delete nodeOf[operator]; emit OperatorUpdate(operator, ""); } /** * Direct transaction allowing node operater to unlink their domain */ function deleteNode() public { deleteNode(msg.sender); } /** * Raw transaction by signer allowing them to delete another wallet's linked domain. * Requires the other wallet to have signed the same data provided. */ function deleteNodeRaw(address operator, uint8 v, bytes32 r, bytes32 s) public { bytes32 paramHash = keccak256(abi.encodePacked(operator)); address signer = ecrecover(keccak256(abi.encodePacked(prefix, paramHash)), v, r, s); deleteNode(signer); } /** * Get the domain name of a given operator. */ function getNode(address operator) public view returns (string memory) { return nodeOf[operator]; } /** * Get list of node operators. */ function getNodeOperators() public view returns (address[] memory) { return operators; } /** * OCPI Party Listings */ enum Role { CPO, EMSP, HUB, NAP, NSP, OTHER, SCSP } enum Module { cdrs, chargingprofiles, commands, locations, sessions, tariffs, tokens } struct PartyDetails { bytes2 countryCode; bytes3 partyId; Role[] roles; PartyModules modules; } struct PartyModules { Module[] sender; Module[] receiver; } // country_code => party_id => ocpi party address mapping(bytes2 => mapping(bytes3 => address)) private uniqueParties; // ocpi party => true/false mapping(address => bool) private uniquePartyAddresses; // ocpi party => party details mapping(address => PartyDetails) private partyOf; // ocpi party => node operator mapping(address => address) private operatorOf; // store parties to get list address[] private parties; /** * Create/update OCPI party details and node (internal). */ function setParty(address party, bytes2 countryCode, bytes3 partyId, Role[] memory roles, address operator) private { require(countryCode != bytes2(0), "Cannot set empty country_code. Use deleteParty method instead."); require(partyId != bytes3(0), "Cannot set empty party_id. Use deleteParty method instead."); require(roles.length > 0, "No roles provided."); require(operator != address(0), "Cannot set empty operator. Use deleteParty method instead."); // check for unique country_code and party_id combination address registeredParty = uniqueParties[countryCode][partyId]; require( registeredParty == address(0) || registeredParty == party, "Party with country_code/party_id already registered under different address." ); uniqueParties[countryCode][partyId] = party; require(bytes(nodeOf[operator]).length != 0, "Provided operator not registered."); if (uniquePartyAddresses[party] == false) { parties.push(party); } uniquePartyAddresses[party] = true; PartyModules memory modules; partyOf[party] = PartyDetails(countryCode, partyId, roles, modules); operatorOf[party] = operator; emit PartyUpdate(countryCode, partyId, party, roles, modules.sender, modules.receiver, operator); } /** * Direct transaction by signer to create/update OCPI party details. */ function setParty(bytes2 countryCode, bytes3 partyId, Role[] memory roles, address operator) public { setParty(msg.sender, countryCode, partyId, roles, operator); } /** * Raw transaction by signer to create/update another wallet's OCPI party details. * Requires the other wallet to have signed the same data provided. */ function setPartyRaw( address party, bytes2 countryCode, bytes3 partyId, Role[] memory roles, address operator, uint8 v, bytes32 r, bytes32 s ) public { bytes32 paramHash = keccak256(abi.encodePacked(party, countryCode, partyId, roles, operator)); address signer = ecrecover(keccak256(abi.encodePacked(prefix, paramHash)), v, r, s); require(signer == party, "Signer and provided party address different."); setParty(signer, countryCode, partyId, roles, operator); } /** * Set optional party module implementations (internal). */ function setPartyModules(address party, Module[] memory sender, Module[] memory receiver) private { address operator = operatorOf[party]; require(operator != address(0), "Party not registered. Use setParty method first."); partyOf[party].modules.sender = sender; partyOf[party].modules.receiver = receiver; PartyDetails memory details = partyOf[party]; emit PartyUpdate(details.countryCode, details.partyId, party, details.roles, sender, receiver, operator); } /** * Direct transaction by signer to set their module implementations */ function setPartyModules(Module[] memory sender, Module[] memory receiver) public { setPartyModules(msg.sender, sender, receiver); } /** * Raw transaction by signer to set another wallet's module implementations. * Requires the other wallet to have signed the same data provided. */ function setPartyModulesRaw(address party, Module[] memory sender, Module[] memory receiver, uint8 v, bytes32 r, bytes32 s) public { bytes32 paramHash = keccak256(abi.encodePacked(party, sender, receiver)); address signer = ecrecover(keccak256(abi.encodePacked(prefix, paramHash)), v, r, s); require(signer == party, "Signer and provided party address different."); setPartyModules(signer, sender, receiver); } /** * Delete OCPI party details and node (internal). */ function deleteParty(address party) private { require(operatorOf[party] != address(0), "Cannot delete party that does not exist. No operator found for given party."); delete operatorOf[party]; PartyDetails memory details = partyOf[party]; delete uniqueParties[details.countryCode][details.partyId]; delete partyOf[party]; Role[] memory emptyRoles; Module[] memory emptyModules; emit PartyUpdate(details.countryCode, details.partyId, party, emptyRoles, emptyModules, emptyModules, address(0)); } /** * Direct transaction by signer to delete OCPI party details. */ function deleteParty() public { deleteParty(msg.sender); } /** * Raw transaction by signer to delete another wallet's OCPI party details. * Requires the other wallet to have signed the same data provided. */ function deletePartyRaw(address party, uint8 v, bytes32 r, bytes32 s) public { bytes32 paramHash = keccak256(abi.encodePacked(party)); address signer = ecrecover(keccak256(abi.encodePacked(prefix, paramHash)), v, r, s); require(signer == party, "Signer and provided party address different."); deleteParty(signer); } /** * Gets operator iformation for a given OCPI party (address). */ function getOperatorByAddress(address party) public view returns (address operator, string memory domain) { operator = operatorOf[party]; domain = nodeOf[operator]; } /** * Gets operator information for a given OCPI party (country_code and party_id combination). */ function getOperatorByOcpi(bytes2 countryCode, bytes3 partyId) public view returns (address operator, string memory domain) { address party = uniqueParties[countryCode][partyId]; operator = operatorOf[party]; domain = nodeOf[operator]; } /** * Gets the party details, roles and node by the address of the party */ function getPartyDetailsByAddress(address partyAddress) public view returns ( bytes2 countryCode, bytes3 partyId, Module[] memory modulesSender, Module[] memory modulesReceiver, Role[] memory roles, address operatorAddress, string memory operatorDomain ) { PartyDetails memory details = partyOf[partyAddress]; countryCode = details.countryCode; partyId = details.partyId; roles = details.roles; modulesSender = details.modules.sender; modulesReceiver = details.modules.receiver; operatorAddress = operatorOf[partyAddress]; operatorDomain = nodeOf[operatorAddress]; } /** * Gets the party details, roles and node by the country_code/party_id of the party */ function getPartyDetailsByOcpi(bytes2 countryCode, bytes3 partyId) public view returns ( address partyAddress, Role[] memory roles, Module[] memory modulesSender, Module[] memory modulesReceiver, address operatorAddress, string memory operatorDomain ) { partyAddress = uniqueParties[countryCode][partyId]; PartyDetails memory details = partyOf[partyAddress]; roles = details.roles; modulesSender = details.modules.sender; modulesReceiver = details.modules.receiver; operatorAddress = operatorOf[partyAddress]; operatorDomain = nodeOf[operatorAddress]; } /** * Get the list of parties registered */ function getParties() public view returns (address[] memory) { return parties; } }
Direct transaction by signer to create/update their linked domain./
function setNode(string memory domain) public { setNode(msg.sender, domain); }
7,220,271
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts-upgradeable/presets/ERC721PresetMinterPauserAutoIdUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {NativeMetaTransaction} from "./NativeMetaTransaction.sol"; import {ContextMixin} from "./ContextMixin.sol"; //import { SoapPunkCollectiblesChild } from "./SoupPunk_child.sol"; contract SpaceTime is ERC721PresetMinterPauserAutoIdUpgradeable, NativeMetaTransaction, ContextMixin { using SafeMathUpgradeable for uint256; uint256 private _tokenCount; uint256 private _endTime; // uint256 private _multPrice; uint256 private _refundByCatch; // uint8 private _maxVotes; uint8 private _maxMintByAccount; // uint16 private _totalArtworkAmount; uint32 private _totalTokenAmount; // string private _contractURI; SoapPunkCollectiblesChild private _spContract; // Mapping from address to vote count mapping (address => uint8) private _accountVoteCount; // Mapping from address to amount of mints mapping (address => uint8) private _accountMintCount; // Mapping from token id to minter mapping (uint256 => address) private _artworkMinterAccount; // Mapping from token id to boolean -> true if arwork is minted mapping (uint256 => bool) private _artworkMinted; // Mapping from address to votes array mapping (address => uint256[10]) private _accountVoteArtwork; // Mapping from address to boolean -> true if refund was used mapping (address => bool) private _accountRefundUsed; IERC20 private _tokenERC20; function initialize(string memory name, string memory symbol, string memory baseURI, string memory domainSeparator) initializer public { __ERC721PresetMinterPauserAutoId_init(name, symbol, baseURI); _initializeEIP712(domainSeparator); _tokenCount = 0; uint256 _startTime = block.timestamp; setEndTime(_startTime.add(2592000)); setPrice(5000000000000000000); // 5 Matic setContractURI("ipfs://contract-metadata"); } /** * @dev the URL to a JSON file with contract metadata for OpenSea. */ function contractURI() public view returns (string memory) { return _contractURI; } /** * @dev Returns the address of the current owner, OpenSea uses this information. */ function owner() public view returns (address) { return getRoleMember(DEFAULT_ADMIN_ROLE, 0); } /** * @dev Returns information about the fees for a given token. */ function royaltyInfo(uint256 _tokenId, uint256 _value) external view override returns (address receiver, uint256 amount) { return (address(this), _value.div(100); } function setERC20(IERC20 token) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to set token"); _tokenERC20 = token; } function setBaseURI(string memory baseURI, uint256 id) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change uri"); _setBaseURI(baseURI); } function setContractURI(string memory __contractURI) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change contract uri"); _contractURI = __contractURI; ContractURISet(__contractURI); } function setPrice(uint256 multPrice) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to set price"); _multPrice = multPrice; emit PriceSet(multPrice); } function setEndTime(uint256 endTime) public { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to change end time"); _endTime = endTime; emit EndTimeSet(endTime); } function mint(address to) public override { require(false, "SpaceTime: mint is not allowed"); // Nobody can call mint() } function getPrice(address for_account) public view returns(uint256 price, bool use_refund) { // bool willUseRefund = false; // If user didn't used the refund if (!_accountRefundUsed[for_account]) { // Check if owns Soaps if (_spContract.balanceOf(for_account, 0)>0) { willUseRefund = true; } else { // Iterate over votes for (uint i=0; i<_accountVoteCount[for_account]; i++) { if (_artworkMinterAccount[_accountVoteArtwork[for_account][i]] == for_account) { continue; } // If the voted artwork was minted if (_artworkMinted[_accountVoteArtwork[for_account][i]]) { willUseRefund = true; break; } } } } // uint256 tmpPrice = _multPrice.mul(5000); if (_tokenCount < 400) { tmpPrice = _multPrice.mul(10); } else if (_tokenCount < 800) { tmpPrice = _multPrice.mul(25); } else if (_tokenCount < 950) { tmpPrice = _multPrice.mul(45); } else if (_tokenCount < 990) { tmpPrice = _multPrice.mul(85); } else if (_tokenCount < 1024) { tmpPrice = _multPrice.mul(150); } if (!willUseRefund) { // Price not cut in half tmpPrice = tmpPrice.mul(2); } // return (tmpPrice, willUseRefund); } /** * @dev Get price, setting the refund as used. */ function _getPrice() private returns(uint256 price) { (uint256 tmpPrice, bool willUseRefund) = getPrice(_msgSender()); // Mark refund as used if (willUseRefund) { _accountRefundUsed[_msgSender()] = true; } return tmpPrice; } /** * @dev Mints artwork on sale. */ function buy() external //payable price(_getPrice()) returns(uint256 index) { require(!paused(), "SpaceTime: token mint while paused"); _tokenCount = _tokenCount.add(1); _artworkMinterAccount[id] = _msgSender(); _artworkMinted[id] = true; _accountMintCount[_msgSender()] += 1; _mint(_msgSender(), _tokenCount-1); return _tokenCount-1; } /* * @dev Remove all Ether from the contract, and transfer it to account of owner */ function withdrawBalance() external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SpaceTime: must have admin role to withdraw"); uint256 balance = _tokenERC20.balanceOf(address(this)); _tokenERC20.transfer(_msgSender(), balance); emit Withdraw(balance); } // Modifiers /** * @dev modifier Associete fee with a function call. If the caller sent too much, then is refunded, but only after the function body. * This was dangerous before Solidity version 0.4.0, where it was possible to skip the part after `_;`. * @param _amount - ether needed to call the function */ modifier price(uint256 _amount) { require(_tokenERC20.balanceOf(_msgSender()) >= _amount, "SpaceTime: Not enough ERC20 tokens."); require(_tokenERC20.allowance(_msgSender(), address(this)) >= _amount, "SpaceTime: Not enough ERC20 token allowance."); _; _tokenERC20.transferFrom(_msgSender(), address(this), _amount); } // Events /** * @dev Emits when owner take ETH out of contract * @param balance - amount of ETh sent out from contract */ event Withdraw(uint256 balance); /** * @dev Emits when a new price is set * @param multPrice - a multiplier for the price */ event PriceSet(uint256 multPrice); /** * @dev Emits when an artwork is voted * @param id - an artwork id * @param account - an account address */ event Vote(uint256 id, address account); /** * @dev Emits when the SoapPunk contract address is set * @param spAddress - an address */ event SPAddressSet(address spAddress); /** * @dev Emits when the contract URI is set * @param contractURI - an URL to the metadata */ event ContractURISet(string contractURI); /** * @dev Emits when the end time is set * @param endTime - the event end time */ event EndTimeSet(uint256 endTime); // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } }
If user didn't used the refund Check if owns Soaps Iterate over votes If the voted artwork was minted Price not cut in half
function getPrice(address for_account) public view returns(uint256 price, bool use_refund) { bool willUseRefund = false; if (!_accountRefundUsed[for_account]) { if (_spContract.balanceOf(for_account, 0)>0) { willUseRefund = true; for (uint i=0; i<_accountVoteCount[for_account]; i++) { if (_artworkMinterAccount[_accountVoteArtwork[for_account][i]] == for_account) { continue; } if (_artworkMinted[_accountVoteArtwork[for_account][i]]) { willUseRefund = true; break; } } } } if (_tokenCount < 400) { tmpPrice = _multPrice.mul(10); tmpPrice = _multPrice.mul(25); tmpPrice = _multPrice.mul(45); tmpPrice = _multPrice.mul(85); tmpPrice = _multPrice.mul(150); } if (!willUseRefund) { tmpPrice = tmpPrice.mul(2); } }
2,564,395
// 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); } } /** * @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); } } } } /** * @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; } } } /** * @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 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); } /** * @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; } } /** * @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 Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } 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); } } /** * @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); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns ( bytes4 retval ) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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(); } } contract DogZone721 is ERC721, ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; // Locked - 0 // Open - 1 // Ended - 2 enum SalePhase { WaitingToStart, InProgress, Finished } // TODO: CREATE NEW WALLET, CHANGE THIS AND THE PRIVATE KEY!!!! address private immutable signer = 0x304cE1e59421aCBc6adA104ba1b5F07f2f4676Cb; string private _baseURIextended; uint256 public constant MAX_TOKENS_PER_MINT = 50; uint256 public constant MAX_TOKENS = 10000; uint256 public constant TEAM_RESERVED_COUNT = 100; uint256 private teamMintedCounter; uint256 public usedSignaturesCount; uint256 public tokenMintPrice = 0.003 ether; // 0.03 ETH initial bool public metadataIsFrozen; bool public giveawayAllowed; bool public giveawayFrozen; mapping(bytes => bool) public usedSignatures; SalePhase public phase; constructor() ERC721("DOG ZONE", "DOGZ") {} // /// Freezes the metadata // /// @dev sets the state of `metadataIsFrozen` to true // /// @notice permamently freezes the metadata so that no more changes are possible function freezeMetadata() external onlyOwner { // require(!metadataIsFrozen, "Metadata is already frozen"); metadataIsFrozen = true; } // /// Adjust the mint price // /// @dev modifies the state of the `mintPrice` variable // /// @notice sets the price for minting a token // /// @param newPrice_ The new price for minting function adjustMintPrice(uint256 newPrice_) external onlyOwner { tokenMintPrice = newPrice_; } // /// Advance Phase // /// @dev Advance the sale phase state // /// @notice Advances sale phase state incrementally function enterNextPhase(SalePhase phase_) external onlyOwner { require( uint8(phase_) == uint8(phase) + 1 && (uint8(phase_) >= 0 && uint8(phase_) <= 2), "can only advance phases" ); phase = phase_; } /// Disburse payments /// @dev transfers amounts that correspond to addresses passeed in as args /// @param payees_ recipient addresses /// @param amounts_ amount to payout to address with corresponding index in the `payees_` array function disbursePayments(address[] memory payees_, uint256[] memory amounts_) external onlyOwner { require(payees_.length == amounts_.length, "Payees and amounts length mismatch"); for (uint256 i; i < payees_.length; i++) { makePaymentTo(payees_[i], amounts_[i]); } } /// Make a payment /// @dev internal fn called by `disbursePayments` to send Ether to an address function makePaymentTo(address address_, uint256 amt_) private { (bool success, ) = address_.call{value: amt_}(""); require(success, "Transfer failed."); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function _transfer( address from, address to, uint256 id ) internal override(ERC721) { require(uint8(phase) > 1, "Transfers are not allowed yet."); super._transfer(from, to, id); } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function setBaseURI(string memory baseURI_) external onlyOwner { require(!metadataIsFrozen, "Metadata is permanently frozen"); _baseURIextended = baseURI_; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), ".json")) : ""; } function _saleIsActive() private view { require(uint8(phase) == 1, "Sale not active."); } modifier saleIsActive() { _saleIsActive(); _; } function _notOverMaxSupply(uint256 supplyToMint, uint256 maxSupplyOfTokens) private pure { require(supplyToMint <= maxSupplyOfTokens, "Reached Max Allowed to Buy."); // if it goes over 10000 } function _isNotOverMaxPerMint(uint256 supplyToMint) private pure { require(supplyToMint <= MAX_TOKENS_PER_MINT, "Reached Max to MINT per Purchase"); } function recoverSigner(bytes32 hash, bytes memory signature) public pure returns (address) { bytes32 messageDigest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); return ECDSA.recover(messageDigest, signature); } function teamMint(uint256 numberOfTokens, address receiver) public onlyOwner { _isNotOverMaxPerMint(numberOfTokens); _notOverMaxSupply(numberOfTokens + totalSupply(), MAX_TOKENS); require(teamMintedCounter < TEAM_RESERVED_COUNT, "All team tokens are minted"); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = teamMintedCounter + 1; if (mintIndex <= MAX_TOKENS) { _safeMint(receiver, mintIndex); teamMintedCounter++; } } } function mint(uint256 numberOfTokens) public payable saleIsActive { _isNotOverMaxPerMint(numberOfTokens); _notOverMaxSupply(numberOfTokens + totalSupply(), MAX_TOKENS - TEAM_RESERVED_COUNT); require(tokenMintPrice * numberOfTokens <= msg.value, "Ether is not enough."); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply() + TEAM_RESERVED_COUNT + 1; if (mintIndex <= MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } } } function enableGiveaway() public onlyOwner { require(!giveawayFrozen, "Giveaway can not be enabled, it is frozen!"); giveawayAllowed = true; } function disableGiveaway() public onlyOwner { giveawayAllowed = false; giveawayFrozen = true; } function freeMint(bytes32 hash, bytes memory signature) public payable saleIsActive { require(giveawayAllowed, "Giveaway not enabled"); _isNotOverMaxPerMint(1); _notOverMaxSupply(1 + totalSupply(), MAX_TOKENS); require(usedSignaturesCount < 25, "All Giveaway Spots are already used!"); require( recoverSigner(hash, signature) == signer && !usedSignatures[signature], "Free giveaway not allowed for your address!" ); uint256 mintIndex = totalSupply() + 1; if (mintIndex <= MAX_TOKENS) { _safeMint(msg.sender, mintIndex); } usedSignatures[signature] = true; usedSignaturesCount = usedSignaturesCount + 1; } }
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; }
336,030
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /** * __ __ _ * | \/ | ___ _ __ ___| |_ ___ _ __ * | |\/| |/ _ \| '_ \/ __| __/ _ \ '__| * | | | | (_) | | | \__ \ || __/ | * |_|__|_|\___/|_| |_|___/\__\___|_|_ _ * / ___| __ _| |_ ___ ___| |__ (_) |__ | | ___ ___ * \___ \ / _` | __/ _ \/ __| '_ \| | '_ \| |/ _ \/ __| * ___) | (_| | || (_) \__ \ | | | | |_) | | __/\__ \ * |____/ \__,_|\__\___/|___/_| |_|_|_.__/|_|\___||___/ * */ import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./ERC2981ContractWideRoyalties.sol"; import "./MerkleProof.sol"; /** * @notice Original Satoshibles contract interface */ interface ISatoshible { function ownerOf( uint256 _tokenId ) external view returns (address owner); } /** * @title Monster Satoshibles * @notice NFT of monsters that can be burned and combined into prime monsters! * @author Aaron Hanson */ contract MonsterSatoshible is ERC721, ERC2981ContractWideRoyalties, Ownable { /// The max token supply uint256 public constant MAX_SUPPLY = 6666; /// The presale portion of the max supply uint256 public constant MAX_PRESALE_SUPPLY = 3333; /// Mysterious constants 💀 uint256 constant DEATH = 0xDEAD; uint256 constant LIFE = 0x024350AC; uint256 constant ALPHA = LIFE % DEATH * 1000; uint256 constant OMEGA = LIFE % DEATH + ALPHA; /// Prime types uint256 constant FRANKENSTEIN = 0; uint256 constant WEREWOLF = 1; uint256 constant VAMPIRE = 2; uint256 constant ZOMBIE = 3; uint256 constant INVALID = 4; /// Number of prime parts uint256 constant NUM_PARTS = 4; /// Bitfield mask for prime part detection during prime minting uint256 constant HAS_ALL_PARTS = 2 ** NUM_PARTS - 1; /// Merkle root summarizing the presale whitelist bytes32 public constant WHITELIST_MERKLE_ROOT = 0xdb6eea27a6a35a02d1928e9582f75c1e0a518ad5992b5cfee9cc0d86fb387b8d; /// Additional team wallets (can withdraw) address public constant TEAM_WALLET_A = 0xF746362D8162Eeb3624c17654FFAa6EB8bD71820; address public constant TEAM_WALLET_B = 0x16659F9D2ab9565B0c07199687DE3634c0965391; address public constant TEAM_WALLET_C = 0x7a73f770873761054ab7757E909ae48f771379D4; address public constant TEAM_WALLET_D = 0xB7c7e3809591F720f3a75Fb3efa05E76E6B7B92A; /// The maximum ERC-2981 royalties percentage uint256 public constant MAX_ROYALTIES_PCT = 600; /// Original Satoshibles contract instance ISatoshible public immutable SATOSHIBLE_CONTRACT; /// The max presale token ID uint256 public immutable MAX_PRESALE_TOKEN_ID; /// The current token supply uint256 public totalSupply; /// The current state of the sale bool public saleIsActive; /// Indicates if the public sale was opened manually bool public publicSaleOpenedEarly; /// The default and discount token prices in wei uint256 public tokenPrice = 99900000000000000; // 0.0999 ether uint256 public discountPrice = 66600000000000000; // 0.0666 ether /// Tracks number of presale mints already used per address mapping(address => uint256) public whitelistMintsUsed; /// The current state of the laboratory bool public laboratoryHasElectricity; /// Merkle root summarizing all monster IDs and their prime parts bytes32 public primePartsMerkleRoot; /// The provenance URI string public provenanceURI = "Not Yet Set"; /// When true, the provenanceURI can no longer be changed bool public provenanceUriLocked; /// The base URI string public baseURI = "https://api.satoshibles.com/monsters/token/"; /// When true, the baseURI can no longer be changed bool public baseUriLocked; /// Use Counters for token IDs using Counters for Counters.Counter; /// Monster token ID counter Counters.Counter monsterIds; /// Prime token ID counter for each prime type mapping(uint256 => Counters.Counter) primeIds; /// Prime ID offsets for each prime type mapping(uint256 => uint256) primeIdOffset; /// Bitfields that track original Satoshibles already used for discounts mapping(uint256 => uint256) satDiscountBitfields; /// Bitfields that track original Satoshibles already used in lab mapping(uint256 => uint256) satLabBitfields; /** * @notice Emitted when the saleIsActive flag changes * @param isActive Indicates whether or not the sale is now active */ event SaleStateChanged( bool indexed isActive ); /** * @notice Emitted when the public sale is opened early */ event PublicSaleOpenedEarly(); /** * @notice Emitted when the laboratoryHasElectricity flag changes * @param hasElectricity Indicates whether or not the laboratory is open */ event LaboratoryStateChanged( bool indexed hasElectricity ); /** * @notice Emitted when a prime is created in the lab * @param creator The account that created the prime * @param primeId The ID of the prime created * @param satId The Satoshible used as the 'key' to the lab * @param monsterIdsBurned The IDs of the monsters burned */ event PrimeCreated( address indexed creator, uint256 indexed primeId, uint256 indexed satId, uint256[4] monsterIdsBurned ); /** * @notice Requires the specified Satoshible to be owned by msg.sender * @param _satId Original Satoshible token ID */ modifier onlySatHolder( uint256 _satId ) { require( SATOSHIBLE_CONTRACT.ownerOf(_satId) == _msgSender(), "Sat not owned" ); _; } /** * @notice Requires msg.sender to be the owner or a team wallet */ modifier onlyTeam() { require( _msgSender() == TEAM_WALLET_A || _msgSender() == TEAM_WALLET_B || _msgSender() == TEAM_WALLET_C || _msgSender() == TEAM_WALLET_D || _msgSender() == owner(), "Not owner or team address" ); _; } /** * @notice Boom... Let's go! * @param _initialBatchCount Number of tokens to mint to msg.sender * @param _immutableSatoshible Original Satoshible contract address * @param _royaltiesPercentage Initial royalties percentage for ERC-2981 */ constructor( uint256 _initialBatchCount, address _immutableSatoshible, uint256 _royaltiesPercentage ) ERC721("Monster Satoshibles", "MSBLS") { SATOSHIBLE_CONTRACT = ISatoshible( _immutableSatoshible ); require( _royaltiesPercentage <= MAX_ROYALTIES_PCT, "Royalties too high" ); _setRoyalties( _msgSender(), _royaltiesPercentage ); _initializePrimeIdOffsets(); _initializeSatDiscountAvailability(); _initializeSatLabAvailability(); _mintTokens(_initialBatchCount); require( belowMaximum(_initialBatchCount, MAX_PRESALE_SUPPLY, MAX_SUPPLY ) == true, "Would exceed max supply" ); unchecked { MAX_PRESALE_TOKEN_ID = _initialBatchCount + MAX_PRESALE_SUPPLY; } } /** * @notice Mints monster tokens during presale, optionally with discounts * @param _numberOfTokens Number of tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints * @param _whitelistedTokens Account's total number of whitelisted tokens * @param _proof Merkle proof to be verified */ function mintTokensPresale( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount, uint256 _whitelistedTokens, bytes32[] calldata _proof ) external payable { require( publicSaleOpenedEarly == false, "Presale has ended" ); require( belowMaximum(monsterIds.current(), _numberOfTokens, MAX_PRESALE_TOKEN_ID ) == true, "Would exceed presale size" ); require( belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens, _whitelistedTokens ) == true, "Would exceed whitelisted count" ); require( verifyWhitelisted(_msgSender(), _whitelistedTokens, _proof ) == true, "Invalid whitelist proof" ); whitelistMintsUsed[_msgSender()] += _numberOfTokens; _doMintTokens( _numberOfTokens, _satsForDiscount ); } /** * @notice Mints monsters during public sale, optionally with discounts * @param _numberOfTokens Number of monster tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints */ function mintTokensPublicSale( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount ) external payable { require( publicSaleOpened() == true, "Public sale has not started" ); require( belowMaximum(monsterIds.current(), _numberOfTokens, MAX_SUPPLY ) == true, "Not enough tokens left" ); _doMintTokens( _numberOfTokens, _satsForDiscount ); } /** * @notice Mints a prime token by burning two or more monster tokens * @param _primeType Prime type to mint * @param _satId Original Satoshible token ID to use as 'key' to the lab * @param _monsterIds Array of monster token IDs to potentially be burned * @param _monsterPrimeParts Array of bitfields of monsters' prime parts * @param _proofs Array of merkle proofs to be verified */ function mintPrimeToken( uint256 _primeType, uint256 _satId, uint256[] calldata _monsterIds, uint256[] calldata _monsterPrimeParts, bytes32[][] calldata _proofs ) external onlySatHolder(_satId) { require( laboratoryHasElectricity == true, "Prime laboratory not yet open" ); require( _primeType < INVALID, "Invalid prime type" ); require( belowMaximum( primeIdOffset[_primeType], primeIds[_primeType].current() + 1, primeIdOffset[_primeType + 1] ) == true, "No more primes left of this type" ); require( satIsAvailableForLab(_satId) == true, "Sat has already been used in lab" ); // bitfield tracking aggregate parts across monsters // (head = 1, eyes = 2, mouth = 4, body = 8) uint256 combinedParts; uint256[4] memory burnedIds; unchecked { uint256 burnedIndex; for (uint256 i = 0; i < _monsterIds.length; i++) { require( verifyMonsterPrimeParts( _monsterIds[i], _monsterPrimeParts[i], _proofs[i] ) == true, "Invalid monster traits proof" ); uint256 theseParts = _monsterPrimeParts[i] >> (_primeType * NUM_PARTS) & HAS_ALL_PARTS; if (combinedParts | theseParts != combinedParts) { _burn( _monsterIds[i] ); burnedIds[burnedIndex++] = _monsterIds[i]; combinedParts |= theseParts; if (combinedParts == HAS_ALL_PARTS) { break; } } } } require( combinedParts == HAS_ALL_PARTS, "Not enough parts for this prime" ); _retireSatFromLab(_satId); primeIds[_primeType].increment(); unchecked { uint256 primeId = primeIdOffset[_primeType] + primeIds[_primeType].current(); totalSupply++; _safeMint( _msgSender(), primeId ); emit PrimeCreated( _msgSender(), primeId, _satId, burnedIds ); } } /** * @notice Activates or deactivates the sale * @param _isActive Whether to activate or deactivate the sale */ function activateSale( bool _isActive ) external onlyOwner { saleIsActive = _isActive; emit SaleStateChanged( _isActive ); } /** * @notice Starts the public sale before MAX_PRESALE_TOKEN_ID is minted */ function openPublicSaleEarly() external onlyOwner { publicSaleOpenedEarly = true; emit PublicSaleOpenedEarly(); } /** * @notice Modifies the prices in case of major ETH price changes * @param _tokenPrice The new default token price * @param _discountPrice The new discount token price */ function updateTokenPrices( uint256 _tokenPrice, uint256 _discountPrice ) external onlyOwner { require( _tokenPrice >= _discountPrice, "discountPrice cannot be larger" ); require( saleIsActive == false, "Sale is active" ); tokenPrice = _tokenPrice; discountPrice = _discountPrice; } /** * @notice Sets primePartsMerkleRoot summarizing all monster prime parts * @param _merkleRoot The new merkle root */ function setPrimePartsMerkleRoot( bytes32 _merkleRoot ) external onlyOwner { primePartsMerkleRoot = _merkleRoot; } /** * @notice Turns the laboratory on or off * @param _hasElectricity Whether to turn the laboratory on or off */ function electrifyLaboratory( bool _hasElectricity ) external onlyOwner { laboratoryHasElectricity = _hasElectricity; emit LaboratoryStateChanged( _hasElectricity ); } /** * @notice Mints the final prime token */ function mintFinalPrime() external onlyOwner { require( _exists(OMEGA) == false, "Final prime already exists" ); unchecked { totalSupply++; } _safeMint( _msgSender(), OMEGA ); } /** * @notice Sets the provenance URI * @param _newProvenanceURI The new provenance URI */ function setProvenanceURI( string calldata _newProvenanceURI ) external onlyOwner { require( provenanceUriLocked == false, "Provenance URI has been locked" ); provenanceURI = _newProvenanceURI; } /** * @notice Prevents further changes to the provenance URI */ function lockProvenanceURI() external onlyOwner { provenanceUriLocked = true; } /** * @notice Sets a new base URI * @param _newBaseURI The new base URI */ function setBaseURI( string calldata _newBaseURI ) external onlyOwner { require( baseUriLocked == false, "Base URI has been locked" ); baseURI = _newBaseURI; } /** * @notice Prevents further changes to the base URI */ function lockBaseURI() external onlyOwner { baseUriLocked = true; } /** * @notice Withdraws sale proceeds * @param _amount Amount to withdraw in wei */ function withdraw( uint256 _amount ) external onlyTeam { payable(_msgSender()).transfer( _amount ); } /** * @notice Withdraws any other tokens * @dev WARNING: Double check token is legit before calling this * @param _token Contract address of token * @param _to Address to which to withdraw * @param _amount Amount to withdraw * @param _hasVerifiedToken Must be true (sanity check) */ function withdrawOther( address _token, address _to, uint256 _amount, bool _hasVerifiedToken ) external onlyOwner { require( _hasVerifiedToken == true, "Need to verify token" ); IERC20(_token).transfer( _to, _amount ); } /** * @notice Sets token royalties (ERC-2981) * @param _recipient Recipient of the royalties * @param _value Royalty percentage (using 2 decimals - 10000 = 100, 0 = 0) */ function setRoyalties( address _recipient, uint256 _value ) external onlyOwner { require( _value <= MAX_ROYALTIES_PCT, "Royalties too high" ); _setRoyalties( _recipient, _value ); } /** * @notice Checks which Satoshibles can still be used for a discounted mint * @dev Uses bitwise operators to find the bit representing each Satoshible * @param _satIds Array of original Satoshible token IDs * @return Token ID for each of the available _satIds, zero otherwise */ function satsAvailableForDiscountMint( uint256[] calldata _satIds ) external view returns (uint256[] memory) { uint256[] memory satsAvailable = new uint256[](_satIds.length); unchecked { for (uint256 i = 0; i < _satIds.length; i++) { if (satIsAvailableForDiscountMint(_satIds[i])) { satsAvailable[i] = _satIds[i]; } } } return satsAvailable; } /** * @notice Checks which Satoshibles can still be used to mint a prime * @dev Uses bitwise operators to find the bit representing each Satoshible * @param _satIds Array of original Satoshible token IDs * @return Token ID for each of the available _satIds, zero otherwise */ function satsAvailableForLab( uint256[] calldata _satIds ) external view returns (uint256[] memory) { uint256[] memory satsAvailable = new uint256[](_satIds.length); unchecked { for (uint256 i = 0; i < _satIds.length; i++) { if (satIsAvailableForLab(_satIds[i])) { satsAvailable[i] = _satIds[i]; } } } return satsAvailable; } /** * @notice Checks if a Satoshible can still be used for a discounted mint * @dev Uses bitwise operators to find the bit representing the Satoshible * @param _satId Original Satoshible token ID * @return isAvailable True if _satId can be used for a discounted mint */ function satIsAvailableForDiscountMint( uint256 _satId ) public view returns (bool isAvailable) { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; isAvailable = satDiscountBitfields[page] >> shift & 1 == 1; } } /** * @notice Checks if a Satoshible can still be used to mint a prime * @dev Uses bitwise operators to find the bit representing the Satoshible * @param _satId Original Satoshible token ID * @return isAvailable True if _satId can still be used to mint a prime */ function satIsAvailableForLab( uint256 _satId ) public view returns (bool isAvailable) { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; isAvailable = satLabBitfields[page] >> shift & 1 == 1; } } /** * @notice Verifies a merkle proof for a monster ID and its prime parts * @param _monsterId Monster token ID * @param _monsterPrimeParts Bitfield of the monster's prime parts * @param _proof Merkle proof be verified * @return isVerified True if the merkle proof is verified */ function verifyMonsterPrimeParts( uint256 _monsterId, uint256 _monsterPrimeParts, bytes32[] calldata _proof ) public view returns (bool isVerified) { bytes32 node = keccak256( abi.encodePacked( _monsterId, _monsterPrimeParts ) ); isVerified = MerkleProof.verify( _proof, primePartsMerkleRoot, node ); } /** * @notice Gets total count of existing prime tokens for a prime type * @param _primeType Prime type * @return supply Count of existing prime tokens for this prime type */ function primeSupply( uint256 _primeType ) public view returns (uint256 supply) { supply = primeIds[_primeType].current(); } /** * @notice Gets total count of existing prime tokens * @return supply Count of existing prime tokens */ function totalPrimeSupply() public view returns (uint256 supply) { unchecked { supply = primeSupply(FRANKENSTEIN) + primeSupply(WEREWOLF) + primeSupply(VAMPIRE) + primeSupply(ZOMBIE) + (_exists(OMEGA) ? 1 : 0); } } /** * @notice Gets total count of monsters burned * @return burned Count of monsters burned */ function monstersBurned() public view returns (uint256 burned) { unchecked { burned = monsterIds.current() + totalPrimeSupply() - totalSupply; } } /** * @notice Gets state of public sale * @return publicSaleIsOpen True if public sale phase has begun */ function publicSaleOpened() public view returns (bool publicSaleIsOpen) { publicSaleIsOpen = publicSaleOpenedEarly == true || monsterIds.current() >= MAX_PRESALE_TOKEN_ID; } /// @inheritdoc ERC165 function supportsInterface( bytes4 _interfaceId ) public view override (ERC721, ERC2981Base) returns (bool doesSupportInterface) { doesSupportInterface = super.supportsInterface(_interfaceId); } /** * @notice Verifies a merkle proof for an account's whitelisted tokens * @param _account Account to verify * @param _whitelistedTokens Number of whitelisted tokens for _account * @param _proof Merkle proof to be verified * @return isVerified True if the merkle proof is verified */ function verifyWhitelisted( address _account, uint256 _whitelistedTokens, bytes32[] calldata _proof ) public pure returns (bool isVerified) { bytes32 node = keccak256( abi.encodePacked( _account, _whitelistedTokens ) ); isVerified = MerkleProof.verify( _proof, WHITELIST_MERKLE_ROOT, node ); } /** * @dev Base monster burning function * @param _tokenId Monster token ID to burn */ function _burn( uint256 _tokenId ) internal override { require( _isApprovedOrOwner(_msgSender(), _tokenId) == true, "not owner nor approved" ); unchecked { totalSupply -= 1; } super._burn( _tokenId ); } /** * @dev Base URI for computing tokenURI * @return Base URI string */ function _baseURI() internal view override returns (string memory) { return baseURI; } /** * @dev Base monster minting function, calculates price with discounts * @param _numberOfTokens Number of monster tokens to mint * @param _satsForDiscount Array of Satoshible IDs for discounted mints */ function _doMintTokens( uint256 _numberOfTokens, uint256[] calldata _satsForDiscount ) private { require( saleIsActive == true, "Sale must be active" ); require( _numberOfTokens >= 1, "Need at least 1 token" ); require( _numberOfTokens <= 50, "Max 50 at a time" ); require( _satsForDiscount.length <= _numberOfTokens, "Too many sats for discount" ); unchecked { uint256 discountIndex; for (; discountIndex < _satsForDiscount.length; discountIndex++) { _useSatForDiscountMint(_satsForDiscount[discountIndex]); } uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex) + discountPrice * discountIndex; require( totalPrice == msg.value, "Ether amount not correct" ); } _mintTokens( _numberOfTokens ); } /** * @dev Base monster minting function. * @param _numberOfTokens Number of monster tokens to mint */ function _mintTokens( uint256 _numberOfTokens ) private { unchecked { totalSupply += _numberOfTokens; for (uint256 i = 0; i < _numberOfTokens; i++) { monsterIds.increment(); _safeMint( _msgSender(), monsterIds.current() ); } } } /** * @dev Marks a Satoshible ID as having been used for a discounted mint * @param _satId Satoshible ID that was used for a discounted mint */ function _useSatForDiscountMint( uint256 _satId ) private onlySatHolder(_satId) { require( satIsAvailableForDiscountMint(_satId) == true, "Sat for discount already used" ); unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; satDiscountBitfields[page] &= ~(1 << shift); } } /** * @dev Marks a Satoshible ID as having been used to mint a prime * @param _satId Satoshible ID that was used to mint a prime */ function _retireSatFromLab( uint256 _satId ) private { unchecked { uint256 page = _satId / 256; uint256 shift = _satId % 256; satLabBitfields[page] &= ~(1 << shift); } } /** * @dev Initializes prime token ID offsets */ function _initializePrimeIdOffsets() private { unchecked { primeIdOffset[FRANKENSTEIN] = ALPHA; primeIdOffset[WEREWOLF] = ALPHA + 166; primeIdOffset[VAMPIRE] = ALPHA + 332; primeIdOffset[ZOMBIE] = ALPHA + 498; primeIdOffset[INVALID] = ALPHA + 665; } } /** * @dev Initializes bitfields of Satoshibles available for discounted mints */ function _initializeSatDiscountAvailability() private { unchecked { for (uint256 i = 0; i < 20; i++) { satDiscountBitfields[i] = type(uint256).max; } } } /** * @dev Initializes bitfields of Satoshibles available to mint primes */ function _initializeSatLabAvailability() private { unchecked { for (uint256 i = 0; i < 20; i++) { satLabBitfields[i] = type(uint256).max; } } } /** * @dev Helper function used for token ID range checks when minting * @param _currentValue Current token ID counter value * @param _incrementValue Number of tokens to increment by * @param _maximumValue Maximum token ID value allowed * @return isBelowMaximum True if _maximumValue is not exceeded */ function belowMaximum( uint256 _currentValue, uint256 _incrementValue, uint256 _maximumValue ) private pure returns (bool isBelowMaximum) { unchecked { isBelowMaximum = _currentValue + _incrementValue <= _maximumValue; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; library MerkleProof { function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; /// @title IERC2981Royalties /// @dev Interface for the ERC2981 - Token Royalty standard interface IERC2981Royalties { /// @notice 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 _value - 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 value sale price function royaltyInfo(uint256 _tokenId, uint256 _value) external view returns (address _receiver, uint256 _royaltyAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./ERC2981Base.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 /// @dev This implementation has the same royalties for each and every tokens abstract contract ERC2981ContractWideRoyalties is ERC2981Base { RoyaltyInfo private _royalties; /// @dev Sets token royalties /// @param _recipient recipient of the royalties /// @param _value percentage (using 2 decimals - 10000 = 100, 0 = 0) function _setRoyalties( address _recipient, uint256 _value ) internal { require(_value <= 10000, "ERC2981Royalties: Too high"); _royalties = RoyaltyInfo(_recipient, uint24(_value)); } /// @inheritdoc IERC2981Royalties function royaltyInfo( uint256, uint256 _value ) external view override returns (address receiver, uint256 royaltyAmount) { RoyaltyInfo memory royalties = _royalties; receiver = royalties.recipient; royaltyAmount = (_value * royalties.amount) / 10000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./IERC2981Royalties.sol"; /// @dev This is a contract used to add ERC2981 support to ERC721 and 1155 abstract contract ERC2981Base is ERC165, IERC2981Royalties { struct RoyaltyInfo { address recipient; uint24 amount; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC2981Royalties).interfaceId || super.supportsInterface(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 "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.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); } }
Gets total count of monsters burned return burned Count of monsters burned/
function monstersBurned() public view returns (uint256 burned) { unchecked { burned = monsterIds.current() + totalPrimeSupply() - totalSupply; } }
7,321,241
//Address: 0xbfb00a32ca5addd84985b43b1e313b9fe44bfe6a //Contract name: PADVTCrowdsale //Balance: 0 Ether //Verification Date: 5/31/2018 //Transacion Count: 4 // CODE STARTS HERE /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract FiatContract { function ETH(uint _id) constant returns (uint256); function USD(uint _id) constant returns (uint256); function EUR(uint _id) constant returns (uint256); function GBP(uint _id) constant returns (uint256); function updatedAt(uint _id) constant returns (uint); } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Safe Guard Contract */ contract SafeGuard is Ownable { event Transaction(address indexed destination, uint value, bytes data); /** * @dev Allows owner to execute a transaction. */ function executeTransaction(address destination, uint value, bytes data) public onlyOwner { require(externalCall(destination, value, data.length, data)); emit Transaction(destination, value, data); } /** * @dev call has been separated into its own function in order to take advantage * of the Solidity's code generator to produce a loop that copies tx.data into memory. */ function externalCall(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly let x := mload(0x40) // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _openingTime, uint256 _closingTime) public { // solium-disable-next-line security/no-block-members require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title AllowanceCrowdsale * @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale. */ contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; address public tokenWallet; /** * @dev Constructor, takes token wallet address. * @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale */ constructor(address _tokenWallet) public { require(_tokenWallet != address(0)); tokenWallet = _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return token.allowance(tokenWallet, this); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transferFrom(tokenWallet, _beneficiary, _tokenAmount); } } /** * @title Antiderivative Pre Token crowdsale */ contract PADVTCrowdsale is AllowanceCrowdsale, TimedCrowdsale, SafeGuard { FiatContract fContract; /** * @param _rate Multiplied by 0.01$ to calculate final price * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold * @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(uint256 _rate, address _wallet, ERC20 _token, address _tokenWallet, uint256 _openingTime, uint256 _closingTime) Crowdsale(_rate, _wallet, _token) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) public { fContract = FiatContract(0x8055d0504666e2B6942BeB8D6014c964658Ca591); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { // returns $0.01 ETH wei * rate uint256 ethCent = fContract.USD(0) * rate; return _weiAmount.div(ethCent); } }
Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase/ optional override
function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { }
5,493,700
pragma solidity >=0.5.16; // SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; // import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol"; /************************************************** */ /* no1s1 Data Smart Contract */ /************************************************** */ // TODO: is ERC721 contract no1s1Data { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract becomes contract admin bool private operational = true; // Main operational state of smart contract. Blocks all state changes throughout the contract if false // no1s1 main state variables bool no1s1Accessability; // Whether no1s1 is accessible bool no1s1Occupation; // Whether no1s1 is occupied enum BatteryState { Full, // 0 Good, // 1 Low, // 2 Empty // 3 } BatteryState no1s1BatteryLevel; // Battery level of no1s1 // User and Usage duration counters uint256 counterUsers; uint256 counterDuration; // Escrow balance uint256 escrowBalance; // Data structure of no1s1 technical system log (hourly) struct TechLog{ uint256 batteryCurrency; uint256 batteryVoltage; uint256 batteryChargeState; uint256 pvVoltage; uint256 systemPower; uint256 time; } // Data structure of no1s1 usage log (daily) struct UsageLog{ uint256 totalBalance; uint256 totalEscrow; uint256 totalUsers; uint256 totalDuration; uint256 time; } // Data structure of no1s1 users struct No1s1User { uint256 boughtDuration; bool accessed; uint256 actualDuration; bool left; uint256 paidEscrow; } // Arrays TechLog[] public no1s1TechLogs; // Array to store history of system data logs with struct TechLog UsageLog[] public no1s1UsageLogs; // Array to store history of system data logs with struct UsageLog // Mappings (key value pairs) mapping(address => uint256) authorizedContracts; // Mapping to store authorized contracts that can call into the data contract mapping(bytes32 => No1s1User) no1s1Users; // Mapping to store authorized no1s1 users /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Emitted when new contract is de-/authorized event AuthorizedContract(address appContract); event DeAuthorizedContract(address appContract); // Emitted when new tech log added event TechLogUpdate(uint256 batteryCurrency,uint256 batteryVoltage, uint256 batteryStateOfCharge,uint256 pvVoltage, uint256 systemEnergy, uint256 logTime); // Emitted when new usage log added event UsageLogUpdate(uint256 no1s1Balance, uint256 escrowBalance, uint256 userCounter, uint256 durationCounter, uint256 logTime); // Emitted when new purchase was made event newQRcode(bytes32 qrCode); // Emitted when access suceeded event accessSuceeded(uint256 allowedTime); // Emitted when user active/inactive event userActive(bool userActive); // Emitted when user left event exitSuccessful(uint256 totalMeditationTime); // Emitted when escrow got refunded event refundSuccessful(uint256 price, uint256 amountReturned); /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Constructor * Deploying the no1s1Data contract and the NFT contract for the no1s1 access token * The deploying account becomes contractOwner */ // TODO: add ERC721("no1s1 token", "NO1S1") for ERC721 support constructor() { contractOwner = msg.sender; // Initiate state variables no1s1Accessability = true; no1s1Occupation = true; no1s1BatteryLevel = BatteryState.Full; counterUsers = 0; counterDuration = 0; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /** * @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"); _; } /** * @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 that the contract calling into the data contract is authorized */ modifier isCallerAuthorized() { require(authorizedContracts[msg.sender] == 1, "Caller is not authorized"); _; } /** * @dev Modifier that checks whether no1s1 is accessible */ modifier checkAccessability() { require(no1s1Accessability == true, "no1s1 is currently closed."); _; } /** * @dev Modifier that checks whether no1s1 is occupied */ modifier checkOccupancy() { require(no1s1Occupation == true, "no1s1 is currently already occupied."); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * @return A bool that is the current operating status */ function isOperational() external 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) public requireContractOwner { operational = mode; } /** * @dev authorize app contract to call into data contract * @return A bool that is the current authorization status */ function authorizeContract(address appContract) public requireIsOperational requireContractOwner returns(bool) { authorizedContracts[appContract] = 1; emit AuthorizedContract(appContract); return true; } /** * @dev deauthorize app contract to call into data contract * @return A bool that is the current authorization status */ function deAuthorizeContract(address appContract) public requireIsOperational requireContractOwner returns(bool) { delete authorizedContracts[appContract]; emit DeAuthorizedContract(appContract); return true; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS (ONLY CALLABLE FROM APP CONTRACT) */ /********************************************************************************************/ /** * @dev function to modify the main state variable no1s1Accessability. This function is only for admins (not callable from app contract) to reset this state. */ function setAccessabilityStatus(bool mode) external isCallerAuthorized requireIsOperational { no1s1Accessability = mode; } /** * @dev function to modify the main state variable no1s1Occupation. This function is only for admins (not callable from app contract) to reset this state in case exiting the space is not detected */ function setOccupationStatus(bool mode) external isCallerAuthorized requireIsOperational { no1s1Occupation = mode; } /** * @dev function for backend to broadcast technical state, store it in no1s1TechLogs, and modify the main state variable no1s1BatteryLevel (hourly?) */ function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time, uint256 FULL_VALUE, uint256 GOOD_VALUE, uint256 LOW_VALUE) external isCallerAuthorized requireIsOperational { // Add new tech data log no1s1TechLogs.push(TechLog( { batteryCurrency: _Bcurrent, batteryVoltage: _Bvoltage, batteryChargeState: _BSOC, pvVoltage: _Pvoltage, systemPower: _Senergy, time:_Time } )); // Update battery state // TODO: adjust logic that it is based on battery voltage and currency if(_BSOC >= FULL_VALUE){ no1s1BatteryLevel = BatteryState.Full; } else if (_BSOC >= GOOD_VALUE){ no1s1BatteryLevel = BatteryState.Good; } else if (_BSOC >= LOW_VALUE){ no1s1BatteryLevel = BatteryState.Low; } else { no1s1BatteryLevel = BatteryState.Empty; } // Emit event emit TechLogUpdate(_Bcurrent, _Bvoltage, _BSOC, _Pvoltage, _Senergy, _Time); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) */ function no1s1InfoLog(uint256 _Time) external isCallerAuthorized requireIsOperational { // Add new usage data log no1s1UsageLogs.push(UsageLog( { totalBalance: address(this).balance, totalEscrow: escrowBalance, totalUsers: counterUsers, totalDuration: counterDuration, time: _Time } )); // Emit event emit UsageLogUpdate(address(this).balance, escrowBalance, counterUsers, counterDuration, _Time); } /** * @dev buy function to access no1s1, returns QR code */ function buy(uint256 _selectedDuration, address txSender, string calldata _username, uint256 ESCROW_AMOUNT, uint256 MAX_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external payable isCallerAuthorized requireIsOperational checkAccessability checkOccupancy { // check whether no1s1 is accessible and not occupied (modifiers in function headers) // check whether the entered duration is below the maximum duration require(_selectedDuration <= MAX_DURATION, "You request is longer than the maximum allowed meditation duration."); // check if the sent amount is sufficient to cover the escrow require(msg.value >= ESCROW_AMOUNT, "Not enough Ether provided."); // check whether no1s1 battery level is sufficient for chosen meditation time if(_selectedDuration >= GOOD_DURATION){ require(no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } else if (_selectedDuration >= LOW_DURATION){ require(no1s1BatteryLevel == BatteryState.Good || no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } else if (_selectedDuration > 0){ require(no1s1BatteryLevel == BatteryState.Low || no1s1BatteryLevel == BatteryState.Good || no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } // create key to store this order bytes32 key = keccak256(abi.encodePacked(txSender, _username)); // username to generate key so QR code is != address // check whether user has already bought meditation time require(no1s1Users[key].boughtDuration == 0, "You already bought meditation time for no1s1."); // add new no1s1 user no1s1Users[key] = No1s1User({ boughtDuration: _selectedDuration, accessed: false, actualDuration: 0, left: false, paidEscrow: msg.value }); // Update total escrow balance escrowBalance = escrowBalance.add(msg.value); // mit event with QR code (key) emit newQRcode(key); } /** * @dev function triggered by backend to check whether QR code is valid and authorizes to unlock door * @param _key QR code detected by camera * returns allowed duration to enter (if 0, door could stay locked) */ //TODO: trigger timer in back-end? function checkAccess(bytes32 _key, uint256 GOOD_DURATION, uint256 LOW_DURATION) external isCallerAuthorized requireIsOperational checkAccessability checkOccupancy { uint256 allowedDuration = no1s1Users[_key].boughtDuration; if (allowedDuration != 0) { // check again whether no1s1 is accessible and not occupied (modifiers in function headers) // check again battery status if(allowedDuration >= GOOD_DURATION){ require(no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } else if (allowedDuration >= LOW_DURATION){ require(no1s1BatteryLevel == BatteryState.Good || no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } else if (allowedDuration > 0){ require(no1s1BatteryLevel == BatteryState.Low || no1s1BatteryLevel == BatteryState.Good || no1s1BatteryLevel == BatteryState.Full, "no1s1 battery level not sufficient for selected duration."); } // update occupancy status so noone else can buy access no1s1Occupation = false; // emit event to unlock door for allowed duration emit accessSuceeded(allowedDuration); } else { // revert transaction revert("No meditation time bought for this key."); } } /** * @dev function triggered by back-end shortly after access() function with sensor feedback (door openend, motion detected) * if user has not entered, set occupancy back to not occupied and lock door */ function checkActivity(bool _pressureDetected, bytes32 _key) external isCallerAuthorized requireIsOperational { // check wether access has been checked require(no1s1Occupation == false, "Access key has not been checked yet."); // check whether access has already been registered require(no1s1Users[_key].accessed == false, "The access has already been registered."); // check wether user entered the space. // TODO: more sensors? motion? if (_pressureDetected == true) { // User is active! Update user infromation to accessed uint256 escrow = no1s1Users[_key].paidEscrow; no1s1Users[_key] = No1s1User({ boughtDuration: 0, accessed: true, actualDuration: 0, left: false, paidEscrow: escrow }); // Emit event emit userActive(true); } else { // If not active, revert occupancy state to not occupied no1s1Occupation = true; // Emit event emit userActive(false); } } /** * @dev function triggered by backend after leaving no1s1. resets the occupancy state. */ // TODO: careful with input format of _actualDuration [minutes] function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external isCallerAuthorized requireIsOperational { // check whether user has accessed require(no1s1Users[_key].accessed == true, "The user has not meditated yet!"); // check whether user left. TODO: more sensors? require(_doorOpened == true, "The user has not left the space yet!"); // update occupancy state no1s1Occupation = true; // update counters counterUsers = counterUsers.add(1); counterDuration = counterDuration.add(_actualDuration); // update user state uint256 escrow = no1s1Users[_key].paidEscrow; no1s1Users[_key] = No1s1User({ boughtDuration: 0, accessed: true, actualDuration: _actualDuration, left: true, paidEscrow: escrow }); // emit event emit exitSuccessful(_actualDuration); } /** * @dev function triggered by user after leaving no1s1. Pays back escrow and sends out confirmation NFT. */ function refundEscrow(address _sender, string calldata _username, uint256 MEDITATION_PRICE) external isCallerAuthorized requireIsOperational { // recalculate key bytes32 key = keccak256(abi.encodePacked(_sender, _username)); // check whether user has actually redeemed access (entered the space) require(no1s1Users[key].accessed == true, "You cannot redeem your escrow, because you have not meditated yet!"); // check whether user left. require(no1s1Users[key].left == true, "You cannot redeem your escrow, because you have not left the space yet!"); // calculate price for the entered duration uint256 actualDuration = no1s1Users[key].actualDuration; uint256 price = actualDuration.mul(uint256(MEDITATION_PRICE)); // Update total escrow balance uint256 escrow = no1s1Users[key].paidEscrow; escrowBalance = escrowBalance.sub(escrow); // Calculate amount to return uint256 amountToReturn = uint256(escrow).sub(uint256(price)); // check if payable duration is smaller then escrow if (escrow <= price) { // reset user state no1s1Users[key] = No1s1User({ boughtDuration: 0, accessed: false, actualDuration: 0, left: false, paidEscrow: 0 }); amountToReturn = 0; } else { // reset user state no1s1Users[key] = No1s1User({ boughtDuration: 0, accessed: false, actualDuration: 0, left: false, paidEscrow: 0 }); // send remaining escrow balance back to buyer payable(_sender).transfer(amountToReturn); //TODO: mint NFT and send to user, use user counter as ID (unique) //_safeMint(_sender, counterUsers); } // emit event emit refundSuccessful(price, amountToReturn); } /********************************************************************************************/ /* SMART CONTRACT VIEW FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of no1s1 (main state variables) */ function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance) { return (accessability = no1s1Accessability, occupation = no1s1Occupation, batteryState = uint256(no1s1BatteryLevel), totalUsers = counterUsers, totalDuration = counterDuration, myBalance = address(this).balance); } /** * @dev Get address of no1s1 */ function whoAmI() external view returns(address no1s1Address) { return (address(this)); } /** * @dev Get balance of no1s1 (without escrow paid) */ function howRichAmI() external view returns(uint256 no1s1Balance) { return (address(this).balance.sub(escrowBalance)); } /** * @dev get latest entries of UsageLog (max 10) */ function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations) { uint numberOfRecords = 10; if (no1s1UsageLogs.length >= numberOfRecords){ uint256[] memory tenUsers = new uint256[](numberOfRecords); uint256[] memory tenBalances = new uint256[](numberOfRecords); uint256[] memory tenEscrows = new uint256[](numberOfRecords); uint256[] memory tenDuration = new uint256[](numberOfRecords); for (uint i = 0; i < numberOfRecords; i++){ tenUsers[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalUsers; tenBalances[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalBalance; tenEscrows[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalEscrow; tenDuration[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalDuration; } return (tenUsers, tenBalances, tenDuration); } else if (no1s1UsageLogs.length < numberOfRecords){ uint256[] memory xUsers = new uint256[](no1s1UsageLogs.length); uint256[] memory xBalances = new uint256[](no1s1UsageLogs.length); uint256[] memory xEscrows = new uint256[](no1s1UsageLogs.length); uint256[] memory xDuration = new uint256[](no1s1UsageLogs.length); for (uint i = 0; i < no1s1UsageLogs.length; i++){ xUsers[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalUsers; xBalances[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalBalance; xEscrows[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalEscrow; xDuration[i] = no1s1UsageLogs[no1s1UsageLogs.length-1-i].totalDuration; } return (xUsers, xBalances, xDuration); } } /** * @dev retrieve values needed to buy meditation time */ function checkBuyStatus(uint256 MEDITATION_PRICE, uint256 FULL_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate) { // uint256 stateOfCharge = no1s1TechLogs[no1s1TechLogs.length-1].batterystateofcharge; uint256 batteryLevel = uint256(no1s1BatteryLevel); uint256 time = no1s1TechLogs[no1s1TechLogs.length-1].time; uint256 duration; if (batteryLevel == 0){ duration = FULL_DURATION;} else if (batteryLevel == 1){ duration = GOOD_DURATION;} else if(batteryLevel == 2){ duration = LOW_DURATION;} else if(batteryLevel == 3){ duration = 0;} return (batteryLevel, duration, MEDITATION_PRICE, time); } /** * @dev retrieve the latest technical logs */ function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage) { uint256 lastPVIV = no1s1TechLogs[no1s1TechLogs.length-1].pvVoltage; uint256 lastSOE = no1s1TechLogs[no1s1TechLogs.length-1].systemPower; uint256 lastBSoC = no1s1TechLogs[no1s1TechLogs.length-1].batteryChargeState; uint256 lastBCurrency = no1s1TechLogs[no1s1TechLogs.length-1].batteryCurrency; uint256 lastBVoltage = no1s1TechLogs[no1s1TechLogs.length-1].batteryVoltage; return (lastPVIV, lastSOE, lastBSoC, lastBCurrency, lastBVoltage); } /** * @dev retrieve user information with key (QR code) */ function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return (no1s1Users[_key].boughtDuration, no1s1Users[_key].accessed, no1s1Users[_key].actualDuration, no1s1Users[_key].left, no1s1Users[_key].paidEscrow); } /** * @dev retrieve user information with username */ function checkUserName(address _sender, string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { bytes32 key = keccak256(abi.encodePacked(_sender, _username)); return (key, no1s1Users[key].boughtDuration, no1s1Users[key].accessed, no1s1Users[key].actualDuration, no1s1Users[key].left, no1s1Users[key].paidEscrow); } /********************************************************************************************/ /* SMART CONTRACT FALLBACK FUNCTION */ /********************************************************************************************/ /** * @dev Payable fallback function to enable the contract to receive direct payments. */ fallback () external payable isCallerAuthorized requireIsOperational {} }
retrieve values needed to buy meditation time/ uint256 stateOfCharge = no1s1TechLogs[no1s1TechLogs.length-1].batterystateofcharge;
function checkBuyStatus(uint256 MEDITATION_PRICE, uint256 FULL_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate) { uint256 batteryLevel = uint256(no1s1BatteryLevel); uint256 time = no1s1TechLogs[no1s1TechLogs.length-1].time; uint256 duration; if (batteryLevel == 0){ duration = FULL_DURATION;} else if (batteryLevel == 1){ duration = GOOD_DURATION;} else if(batteryLevel == 2){ duration = LOW_DURATION;} else if(batteryLevel == 3){ duration = 0;} return (batteryLevel, duration, MEDITATION_PRICE, time); }
6,414,951
./partial_match/1/0x9641da0512A21B737303DDD4300c3c946411b8a0/sources/MintedTokenCappedCrowdsaleExt.sol
Don't mess the dates
function CrowdsaleExt(string _name, address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, bool _isUpdatable, bool _isWhiteListed) { owner = msg.sender; name = _name; token = FractionalERC20Ext(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; if(startsAt >= endsAt) { throw; } isUpdatable = _isUpdatable; isWhiteListed = _isWhiteListed; }
3,933,243
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // /** * @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 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; } } // /** * @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); } } } } // /** * @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"); } } } // /** * @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 transfered 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); } // /* * @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; } } // /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // interface IHoneyPropDict { function getMiningMultiplier(uint256 tokenId) external view returns (uint256); // in percentage, 100 denotes 100% } // contract HoneycombV2 is Ownable, IERC721Receiver { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. uint earned; // Earned HONEY. bool propEnabled; uint256 propTokenId; } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that HONEYs distribution occurs. uint256 accHoneyPerShare; // Accumulated HONEYs per share, times 1e12. uint256 totalShares; } struct BatchInfo { uint256 startBlock; uint256 endBlock; uint256 honeyPerBlock; uint256 totalAllocPoint; address prop; address propDict; } // Info of each batch BatchInfo[] public batchInfo; // Info of each pool at specified batch. mapping (uint256 => PoolInfo[]) public poolInfo; // Info of each user at specified batch and pool mapping (uint256 => mapping (uint256 => mapping (address => UserInfo))) public userInfo; IERC20 public honeyToken; event Deposit(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 amount); event DepositProp(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 propTokenId); event WithdrawProp(address indexed user, uint256 indexed batch, uint256 indexed pid, uint256 propTokenId); constructor (address _honeyToken) public { honeyToken = IERC20(_honeyToken); } function addBatch(uint256 startBlock, uint256 endBlock, uint256 honeyPerBlock, address prop, address propDict) public onlyOwner { require(endBlock > startBlock, "endBlock should be larger than startBlock"); require(endBlock > block.number, "endBlock should be larger than the current block number"); require(startBlock > block.number, "startBlock should be larger than the current block number"); if (batchInfo.length > 0) { uint256 lastEndBlock = batchInfo[batchInfo.length - 1].endBlock; require(startBlock >= lastEndBlock, "startBlock should be >= the endBlock of the last batch"); } uint256 senderHoneyBalance = honeyToken.balanceOf(address(msg.sender)); uint256 requiredHoney = endBlock.sub(startBlock).mul(honeyPerBlock); require(senderHoneyBalance >= requiredHoney, "insufficient HONEY for the batch"); honeyToken.safeTransferFrom(address(msg.sender), address(this), requiredHoney); batchInfo.push(BatchInfo({ startBlock: startBlock, endBlock: endBlock, honeyPerBlock: honeyPerBlock, totalAllocPoint: 0, prop: prop, propDict: propDict })); } function addPool(uint256 batch, IERC20 lpToken, uint256 multiplier) public onlyOwner { require(batch < batchInfo.length, "batch must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (targetBatch.startBlock <= block.number && block.number < targetBatch.endBlock) { updateAllPools(batch); } uint256 lastRewardBlock = block.number > targetBatch.startBlock ? block.number : targetBatch.startBlock; batchInfo[batch].totalAllocPoint = targetBatch.totalAllocPoint.add(multiplier); poolInfo[batch].push(PoolInfo({ lpToken: lpToken, allocPoint: multiplier, lastRewardBlock: lastRewardBlock, accHoneyPerShare: 0, totalShares: 0 })); } // Return rewardable block count over the given _from to _to block. function getPendingBlocks(uint256 batch, uint256 from, uint256 to) public view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (to < targetBatch.startBlock) { return 0; } if (to > targetBatch.endBlock) { if (from > targetBatch.endBlock) { return 0; } else { return targetBatch.endBlock.sub(from); } } else { return to.sub(from); } } // View function to see pending HONEYs on frontend. function pendingHoney(uint256 batch, uint256 pid, address account) external view returns (uint256) { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; if (block.number < targetBatch.startBlock) { return 0; } PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][account]; uint256 accHoneyPerShare = pool.accHoneyPerShare; if (block.number > pool.lastRewardBlock && pool.totalShares != 0) { uint256 pendingBlocks = getPendingBlocks(batch, pool.lastRewardBlock, block.number); uint256 honeyReward = pendingBlocks.mul(targetBatch.honeyPerBlock).mul(pool.allocPoint).div(targetBatch.totalAllocPoint); accHoneyPerShare = accHoneyPerShare.add(honeyReward.mul(1e12).div(pool.totalShares)); } uint256 power = 100; if (user.propEnabled) { IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); power = propDict.getMiningMultiplier(user.propTokenId); } return user.amount.mul(power).div(100).mul(accHoneyPerShare).div(1e12).sub(user.rewardDebt); } function updateAllPools(uint256 batch) public { require(batch < batchInfo.length, "batch must exist"); uint256 length = poolInfo[batch].length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(batch, pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 batch, uint256 pid) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; PoolInfo storage pool = poolInfo[batch][pid]; if (block.number < targetBatch.startBlock || block.number <= pool.lastRewardBlock || pool.lastRewardBlock > targetBatch.endBlock) { return; } if (pool.totalShares == 0) { pool.lastRewardBlock = block.number; return; } uint256 pendingBlocks = getPendingBlocks(batch, pool.lastRewardBlock, block.number); uint256 honeyReward = pendingBlocks.mul(targetBatch.honeyPerBlock).mul(pool.allocPoint).div(targetBatch.totalAllocPoint); pool.accHoneyPerShare = pool.accHoneyPerShare.add(honeyReward.mul(1e12).div(pool.totalShares)); pool.lastRewardBlock = block.number; } // Deposit LP tokens for HONEY allocation. function deposit(uint256 batch, uint256 pid, uint256 amount) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; require(block.number < targetBatch.endBlock, "batch ended"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user uint256 power = 100; if (user.propEnabled) { IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); power = propDict.getMiningMultiplier(user.propTokenId); } if (user.amount > 0) { uint256 pending = user.amount; if (user.propEnabled) { pending = pending.mul(power).div(100); } pending = pending.mul(pool.accHoneyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeHoneyTransfer(batch, pid, msg.sender, pending); } } // 3. Transfer LP Token from user to honeycomb if (amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount); user.amount = user.amount.add(amount); } // 4. Update pool.totalShares & user.rewardDebt if (user.propEnabled) { pool.totalShares = pool.totalShares.add(amount.mul(power).div(100)); user.rewardDebt = user.amount.mul(power).div(100).mul(pool.accHoneyPerShare).div(1e12); } else { pool.totalShares = pool.totalShares.add(amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); } emit Deposit(msg.sender, batch, pid, amount); } // Withdraw LP tokens. function withdraw(uint256 batch, uint256 pid, uint256 amount) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); UserInfo storage user = userInfo[batch][pid][msg.sender]; require(user.amount >= amount, "insufficient balance"); // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user BatchInfo storage targetBatch = batchInfo[batch]; PoolInfo storage pool = poolInfo[batch][pid]; uint256 pending = user.amount; uint256 power = 100; if (user.propEnabled) { IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); power = propDict.getMiningMultiplier(user.propTokenId); pending = pending.mul(power).div(100); } pending = pending.mul(pool.accHoneyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeHoneyTransfer(batch, pid, msg.sender, pending); } // 3. Transfer LP Token from honeycomb to user pool.lpToken.safeTransfer(address(msg.sender), amount); user.amount = user.amount.sub(amount); // 4. Update pool.totalShares & user.rewardDebt if (user.propEnabled) { pool.totalShares = pool.totalShares.sub(amount.mul(power).div(100)); user.rewardDebt = user.amount.mul(power).div(100).mul(pool.accHoneyPerShare).div(1e12); } else { pool.totalShares = pool.totalShares.sub(amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); } emit Withdraw(msg.sender, batch, pid, amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 batch, uint256 pid) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, batch, pid, user.amount); user.amount = 0; user.rewardDebt = 0; } function depositProp(uint256 batch, uint256 pid, uint256 propTokenId) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); UserInfo storage user = userInfo[batch][pid][msg.sender]; require(!user.propEnabled, "another prop is already enabled"); BatchInfo storage targetBatch = batchInfo[batch]; IERC721 propToken = IERC721(targetBatch.prop); require(propToken.ownerOf(propTokenId) == address(msg.sender), "must be the prop's owner"); // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user PoolInfo storage pool = poolInfo[batch][pid]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHoneyPerShare).div(1e12); pending = pending.sub(user.rewardDebt); if (pending > 0) { safeHoneyTransfer(batch, pid, msg.sender, pending); } } // 3. Transfer Prop from user to honeycomb propToken.safeTransferFrom(address(msg.sender), address(this), propTokenId); user.propEnabled = true; user.propTokenId = propTokenId; // 4. Update pool.totalShares & user.rewardDebt IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); uint256 power = propDict.getMiningMultiplier(user.propTokenId); pool.totalShares = pool.totalShares.sub(user.amount); pool.totalShares = pool.totalShares.add(user.amount.mul(power).div(100)); user.rewardDebt = user.amount.mul(power).div(100).mul(pool.accHoneyPerShare).div(1e12); emit DepositProp(msg.sender, batch, pid, propTokenId); } function withdrawProp(uint256 batch, uint256 pid, uint256 propTokenId) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); UserInfo storage user = userInfo[batch][pid][msg.sender]; require(user.propEnabled, "no prop is yet enabled"); require(propTokenId == user.propTokenId, "must be the owner of the prop"); BatchInfo storage targetBatch = batchInfo[batch]; IERC721 propToken = IERC721(targetBatch.prop); require(propToken.ownerOf(propTokenId) == address(this), "the prop is not staked"); // 1. Update pool.accHoneyPerShare updatePool(batch, pid); // 2. Transfer pending HONEY to user PoolInfo storage pool = poolInfo[batch][pid]; IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); uint256 power = propDict.getMiningMultiplier(user.propTokenId); uint256 pending = user.amount.mul(power).div(100); pending = pending.mul(pool.accHoneyPerShare).div(1e12); pending = pending.sub(user.rewardDebt); if (pending > 0) { safeHoneyTransfer(batch, pid, msg.sender, pending); } // 3. Transfer Prop from honeycomb to user propToken.safeTransferFrom(address(this), address(msg.sender), propTokenId); user.propEnabled = false; user.propTokenId = 0; // 4. Update pool.totalShares & user.rewardDebt pool.totalShares = pool.totalShares.sub(user.amount.mul(power).div(100)); pool.totalShares = pool.totalShares.add(user.amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); emit WithdrawProp(msg.sender, batch, pid, propTokenId); } function migrate(uint256 toBatch, uint256 toPid, uint256 amount, uint256 fromBatch, uint256 fromPid) public { require(toBatch < batchInfo.length, "target batch must exist"); require(toPid < poolInfo[toBatch].length, "target pool must exist"); require(fromBatch < batchInfo.length, "source batch must exist"); require(fromPid < poolInfo[fromBatch].length, "source pool must exist"); BatchInfo storage targetBatch = batchInfo[toBatch]; require(block.number < targetBatch.endBlock, "batch ended"); UserInfo storage userFrom = userInfo[fromBatch][fromPid][msg.sender]; if (userFrom.amount > 0) { PoolInfo storage poolFrom = poolInfo[fromBatch][fromPid]; PoolInfo storage poolTo = poolInfo[toBatch][toPid]; require(address(poolFrom.lpToken) == address(poolTo.lpToken), "must be the same token"); withdraw(fromBatch, fromPid, amount); deposit(toBatch, toPid, amount); } } function migrateProp(uint256 toBatch, uint256 toPid, uint256 propTokenId, uint256 fromBatch, uint256 fromPid) public { require(toBatch < batchInfo.length, "target batch must exist"); require(toPid < poolInfo[toBatch].length, "target pool must exist"); require(fromBatch < batchInfo.length, "source batch must exist"); require(fromPid < poolInfo[fromBatch].length, "source pool must exist"); BatchInfo storage sourceBatch = batchInfo[fromBatch]; BatchInfo storage targetBatch = batchInfo[toBatch]; require(block.number < targetBatch.endBlock, "batch ended"); require(targetBatch.prop == sourceBatch.prop, "prop not compatible"); require(targetBatch.propDict == sourceBatch.propDict, "propDict not compatible"); UserInfo storage userFrom = userInfo[fromBatch][fromPid][msg.sender]; require(userFrom.propEnabled, "no prop is yet enabled"); require(propTokenId == userFrom.propTokenId, "propTokenId not yours"); UserInfo storage userTo = userInfo[toBatch][toPid][msg.sender]; require(!userTo.propEnabled, "another prop is already enabled"); withdrawProp(fromBatch, fromPid, propTokenId); depositProp(toBatch, toPid, propTokenId); } // Safe honey transfer function, just in case if rounding error causes pool to not have enough HONEYs. function safeHoneyTransfer(uint256 batch, uint256 pid, address to, uint256 amount) internal { uint256 honeyBal = honeyToken.balanceOf(address(this)); require(honeyBal > 0, "insufficient HONEY balance"); UserInfo storage user = userInfo[batch][pid][to]; if (amount > honeyBal) { honeyToken.transfer(to, honeyBal); user.earned = user.earned.add(honeyBal); } else { honeyToken.transfer(to, amount); user.earned = user.earned.add(amount); } } function onERC721Received(address, address, uint256, bytes calldata) external override returns(bytes4) { return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } }
Deposit LP tokens for HONEY allocation. 1. Update pool.accHoneyPerShare 2. Transfer pending HONEY to user 3. Transfer LP Token from user to honeycomb 4. Update pool.totalShares & user.rewardDebt
function deposit(uint256 batch, uint256 pid, uint256 amount) public { require(batch < batchInfo.length, "batch must exist"); require(pid < poolInfo[batch].length, "pool must exist"); BatchInfo storage targetBatch = batchInfo[batch]; require(block.number < targetBatch.endBlock, "batch ended"); PoolInfo storage pool = poolInfo[batch][pid]; UserInfo storage user = userInfo[batch][pid][msg.sender]; updatePool(batch, pid); uint256 power = 100; if (user.propEnabled) { IHoneyPropDict propDict = IHoneyPropDict(targetBatch.propDict); power = propDict.getMiningMultiplier(user.propTokenId); } if (user.amount > 0) { uint256 pending = user.amount; if (user.propEnabled) { pending = pending.mul(power).div(100); } pending = pending.mul(pool.accHoneyPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeHoneyTransfer(batch, pid, msg.sender, pending); } } if (amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), amount); user.amount = user.amount.add(amount); } if (user.propEnabled) { pool.totalShares = pool.totalShares.add(amount.mul(power).div(100)); user.rewardDebt = user.amount.mul(power).div(100).mul(pool.accHoneyPerShare).div(1e12); pool.totalShares = pool.totalShares.add(amount); user.rewardDebt = user.amount.mul(pool.accHoneyPerShare).div(1e12); } emit Deposit(msg.sender, batch, pid, amount); }
11,964,654
pragma solidity 0.8.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import '../contracts/libraries/StringUtils.sol'; // @dev contract for rock,paper game0 contract RockPaperScissors is Ownable,ERC20 { string constant rock = "rock" ; string constant paper = "paper"; string constant scissors = "scissors"; bool rockchosen = false; bool scissorschosen = false; bool paperchosen = false; string choicemade; bool setprevwinnings = false; uint public prev_gamestaked; string private _tokenname ="RPSTOKENS"; string private _tokensymbol= "RPS"; address public _owner; uint randNonce =0; uint modulus =0; uint _payfee=0; uint maxWaitTime = 100; struct Game { uint gameid; uint256 gamecount; } struct Players { address payable playeraddress; string playername; uint256 playerscore; uint256 playerbalance; } struct PlayingGame{ uint playinggameid; address payable playerininaddress; bool gameover; uint256 gamescore; uint256 playerscount; uint duration; } uint256 public totalsupplytokens = 1000000; mapping(address => uint256) balances; mapping(address => mapping(bytes32 => bool)) playeringamecheck; mapping(uint => mapping(address => uint)) prev_winning; mapping(uint => mapping(address => uint)) gamewithplayer; mapping(uint => uint) gamesplayed; mapping(address => address) playersplayed; mapping(address => bool)paidforgames; mapping(uint=>Game) public _games; mapping(address=>Players)public _playerstore; mapping(uint=>PlayingGame) public _playinggames; // @dev objects inheriting from previous structs Game newgame; Players newplayerregistered; PlayingGame playerinthegame; Game[] public gamesregistered; Players[] public playersregistered; PlayingGame[] public gameinplay; constructor(address __owner) ERC20(_tokenname, _tokensymbol ) { _owner =__owner; totalSupply(); } // @dev fees to be paid to be registered for game // @params player=sender, contractowner,ether amount to be sent function payfee(address payable sender, address payable owneraddress, uint256 amount) public payable returns(bool, bytes memory){ _owner =owneraddress; _payfee = amount; require ( amount >= 10, "Amount not enough to play!"); (bool success,bytes memory data ) = _owner.call{value: _payfee}(""); require(success, "Check the amount sent as well"); paidforgames[sender]= true; return (success,data); } // @dev registeration for game // @params players name and address function registerplayername(string memory _playername, address payable _playeraddress) public returns(string memory, address){ require(msg.sender == _owner , "Caller is not owner"); if (paidforgames[_playeraddress] == true){ uint256 playerbalance =0; playerbalance = balanceOf(_playeraddress); if(playersplayed[_playeraddress] != _playeraddress){ playersplayed[_playeraddress] =_playeraddress ; // @dev storing to memory newplayerregistered = Players(_playeraddress,_playername, 0,playerbalance ); _playerstore[_playeraddress].playeraddress = _playeraddress; _playerstore[_playeraddress].playername = _playername; _playerstore[_playeraddress].playerscore = 0; _playerstore[_playeraddress].playerbalance = playerbalance; // @dev storing to storage -optional playersregistered.push(newplayerregistered); return (_playername,_playeraddress ); } } } // @dev register game, game id as random generator integer function registergame(uint _gameid) external returns(uint){ uint256 i =0; i++; require(msg.sender == _owner , "Caller is not owner"); uint256 gamecount = 0; if(gamesplayed[_gameid] != _gameid){ gamesplayed[_gameid] = _gameid; newgame = Game(_gameid,gamecount ); // Store into memory _games[_gameid].gameid = _gameid; _games[_gameid].gamecount = i; gamesregistered.push(newgame); return (_gameid); } } // @dev set both player and game function setplayinggame(uint _gameid, address payable playersaddress) internal returns(uint, address) { uint _playerscount =0; _playerscount++; require(msg.sender == _owner , "Caller is not owner"); uint __gameid =0; __gameid = _gameid; randNonce++; modulus= 3; __gameid = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % modulus; require(msg.sender == _owner, "Caller is not owner"); // @dev access control for registration of game and player require( _playinggames[_gameid].playerscount < 2 == true, "Only two players can play"); require(gamewithplayer[_gameid][playersaddress] != __gameid, "Player already is set in game"); gamewithplayer[_gameid][playersaddress] = __gameid; uint _duration = block.number + maxWaitTime; playerinthegame = PlayingGame(_gameid, playersaddress, false, 0,0, _duration); _playinggames[_gameid].playinggameid = _gameid; _playinggames[_gameid].playerininaddress = playersaddress; _playinggames[_gameid].gameover = false; _playinggames[_gameid].gamescore = 0; _playinggames[_gameid].playerscount = _playerscount; _playinggames[_gameid].duration = _duration; gameinplay.push(playerinthegame); return(_gameid, playersaddress); } // @dev several checks before game function _checkplayerregistered(address payable _playeraddress) public returns (bool ) { require(playersplayed[_playeraddress] == _playeraddress ); return(true); } function _checkgameregistered(uint _gameid) public returns (bool) { require(gamesplayed[_gameid]== _gameid); return(true); } function _checkplayeringame(uint _gameid,address _playeraddress ) public returns (bool){ require( gamewithplayer[_gameid][_playeraddress] == _gameid ); return (true); } // @dev triggers for choice selections function selectRock( ) public virtual returns(bool) { if (rockchosen){ rockchosen = true; return (rockchosen); }else{ rockchosen = false; return (rockchosen); } } function selectPaper() public virtual returns(bool) { if (paperchosen){ paperchosen = true; return (paperchosen); }else{ paperchosen = false; return (paperchosen); } } function selectScissors( ) public virtual returns(bool){ if (scissorschosen){ scissorschosen = true; return (scissorschosen); }else{ scissorschosen = false; return (scissorschosen); } } // @dev function for staking previous winnings in game function stakeprevwinnings( ) public virtual returns(bool) { if(setprevwinnings) { setprevwinnings =true; }else{ setprevwinnings =false; } return (setprevwinnings); } // @dev function for choosing which game to stake function choosegametostake(uint game_id,address payable _playeraddress ) public virtual returns(uint256){ prev_gamestaked =game_id; if (stakeprevwinnings( ) ==true ){ uint256 winnings =0; winnings = prev_winning[prev_gamestaked][_playeraddress]; transfer(_owner, winnings); return( winnings); } } event eventplaygame(uint _eventgameid, address payable _eventtheplayeraddress, string _eventchoicemade); // @dev function for overall game play and storing values in respective arrays function playgame(uint _gameid, address payable _theplayeraddress, string memory _choicemade ) internal returns(string memory, address, string memory){ require(msg.sender == _owner , "Caller is not owner"); _checkplayerregistered(_theplayeraddress); _checkgameregistered( _gameid); _checkplayeringame( _gameid ,_theplayeraddress ); choosegametostake(prev_gamestaked, _theplayeraddress ); for (uint i=0; i<2; i++){ choicemade = _choicemade; if (selectRock() == true ){ scissorschosen = false; paperchosen = false; choicemade = "rock" ; } if (selectPaper()== true ){ rockchosen = false; scissorschosen = false; choicemade = "paper" ; } if (selectScissors()== true ){ rockchosen =false; paperchosen =false; choicemade = "scissors" ; } continue; string[] memory choices; choices[0] ="rock"; choices[1]="paper"; choices[2]="scissors"; uint shuffler = 0; shuffler= 3; uint _gameindex = 0; randNonce++; _gameindex = uint(keccak256(abi.encodePacked(block.timestamp, msg.sender, randNonce))) % shuffler; string memory choice = choices[_gameindex]; if (StringUtils.equal(choicemade, choice)== true ){ approve( _theplayeraddress, 10000); transfer(_theplayeraddress,10000); balanceOf(_theplayeraddress); newplayerregistered.playeraddress =_theplayeraddress; prev_winning[_gameid][_theplayeraddress] =10000; _playerstore[_theplayeraddress].playerscore +=5; } emit eventplaygame( _gameid, _theplayeraddress, _choicemade); } } // @dev various ERC20 token functions inherited from ERC contract, // functions set as virtual function totalSupply() public view virtual override returns (uint256) { return totalsupplytokens; } function balanceOf(address account) public view override returns (uint256) { return balances[account]; } function owner() public view virtual override returns (address) { return _owner; } }
function for choosing which game to stake
function choosegametostake(uint game_id,address payable _playeraddress ) public virtual returns(uint256){ prev_gamestaked =game_id; if (stakeprevwinnings( ) ==true ){ uint256 winnings =0; winnings = prev_winning[prev_gamestaked][_playeraddress]; transfer(_owner, winnings); return( winnings); } }
5,467,371
pragma solidity ^0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ 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; } } // File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be sent to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } // File: openzeppelin-solidity/contracts/ownership/rbac/Roles.sol /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } // File: openzeppelin-solidity/contracts/ownership/rbac/RBAC.sol /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * @dev Supports unlimited numbers of roles and addresses. * @dev See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { checkRole(msg.sender, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public { addRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressAdded(addr); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address addr) public view returns (bool) { return hasRole(addr, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { addAddressToWhitelist(addrs[i]); } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public { removeRole(addr, ROLE_WHITELISTED); emit WhitelistedAddressRemoved(addr); } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public { for (uint256 i = 0; i < addrs.length; i++) { removeAddressFromWhitelist(addrs[i]); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/pixie/PixieToken.sol contract PixieToken is StandardToken, Whitelist, HasNoEther { string public constant name = "Pixie Token"; string public constant symbol = "PXE"; uint8 public constant decimals = 18; uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals)); // 100 Billion PXE ^ decimal bool public transfersEnabled = false; address public bridge; event BridgeChange(address to); event TransfersEnabledChange(bool to); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public Whitelist() { totalSupply_ = initialSupply; balances[msg.sender] = initialSupply; emit Transfer(0x0, msg.sender, initialSupply); // transfer bridge set to msg sender bridge = msg.sender; // owner is automatically whitelisted addAddressToWhitelist(msg.sender); } function transfer(address _to, uint256 _value) public returns (bool) { require( transfersEnabled || whitelist(msg.sender) || _to == bridge, "Unable to transfers locked or address not whitelisted or not sending to the bridge" ); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require( transfersEnabled || whitelist(msg.sender) || _to == bridge, "Unable to transfers locked or address not whitelisted or not sending to the bridge" ); return super.transferFrom(_from, _to, _value); } /** * @dev Allows for setting the bridge address * @dev Must be called by owner * * @param _new the address to set */ function changeBridge(address _new) external onlyOwner { require(_new != address(0), "Invalid address"); bridge = _new; emit BridgeChange(bridge); } /** * @dev Allows for setting transfer on/off - used as hard stop * @dev Must be called by owner * * @param _transfersEnabled the value to set */ function setTransfersEnabled(bool _transfersEnabled) external onlyOwner { transfersEnabled = _transfersEnabled; emit TransfersEnabledChange(transfersEnabled); } } // File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } // File: openzeppelin-solidity/contracts/crowdsale/distribution/utils/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ constructor(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: contracts/pixie/PixieCrowdsale.sol contract PixieCrowdsale is Crowdsale, Pausable { event Finalized(); event MinimumContributionUpdated(uint256 _minimumContribution); event OwnerTransfer( address indexed owner, address indexed caller, address indexed beneficiary, uint256 amount ); mapping(address => bool) public whitelist; mapping(address => bool) public managementWhitelist; mapping(address => uint256) public contributions; bool public isFinalized = false; // Tuesday, July 3, 2018 10:00:00 AM GMT+01:00 uint256 public openingTime = 1530608400; // Wednesday, August 1, 2018 9:59:59 AM GMT+01:00 uint256 public privateSaleCloseTime = 1533113999; // Monday, October 1, 2018 9:59:59 AM GMT+01:00 uint256 public preSaleCloseTime = 1538384399; // Wednesday, October 31, 2018 9:59:59 AM GMT+00:00 uint256 public closingTime = 1540979999; // price per token (no discount) uint256 public rate = 396039; // 22.5% discount uint256 public privateSaleRate = 485148; // 12.5% discount uint256 public preSaleRate = 445544; uint256 public softCap = 2650 ether; uint256 public hardCap = 101000 ether; uint256 public minimumContribution = 1 ether; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Throws if called by any account other than the owner or the someone in the management list. */ modifier onlyManagement() { require(msg.sender == owner || managementWhitelist[msg.sender], "Must be owner or in management whitelist"); _; } /** * @dev Constructs the Crowdsale contract with pre-defined parameter plus params * * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(address _wallet, PixieToken _token) public Crowdsale(rate, _wallet, _token) { vault = new RefundVault(wallet); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function softCapReached() public view returns (bool) { return weiRaised >= softCap; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (softCapReached()) { vault.close(); } else { vault.enableRefunds(); } } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault if not finalised, otherwise to wallet */ function _forwardFunds() internal { // once finalized all contributions got to the wallet if (isFinalized) { wallet.transfer(msg.value); } // otherwise send to vault to allow refunds, if required else { vault.deposit.value(msg.value)(msg.sender); } } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized, "Crowdsale already finalised"); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyManagement { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyManagement { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyManagement { whitelist[_beneficiary] = false; } /** * @dev Adds single address to the management whitelist. * @param _manager Address to be added to the management whitelist */ function addToManagementWhitelist(address _manager) external onlyManagement { managementWhitelist[_manager] = true; } /** * @dev Removes single address from the management whitelist. * @param _manager Address to be removed to the management whitelist */ function removeFromManagementWhitelist(address _manager) external onlyManagement { managementWhitelist[_manager] = false; } /** * @dev Allows for updating the opening time in the event of a delay * @dev Must be called by management, use sparingly as no restrictions are set * * @param _openingTime the epoch time to set */ function updateOpeningTime(uint256 _openingTime) external onlyManagement { require(_openingTime > 0, "A opening time must be specified"); openingTime = _openingTime; } /** * @dev Allows for updating the private sale close time in the event of a delay * @dev Must be called by management, use sparingly as no restrictions are set * * @param _privateSaleCloseTime the epoch time to set */ function updatePrivateSaleCloseTime(uint256 _privateSaleCloseTime) external onlyManagement { require(_privateSaleCloseTime > openingTime, "A private sale time must after the opening time"); privateSaleCloseTime = _privateSaleCloseTime; } /** * @dev Allows for updating the pre sale close time in the event of a delay * @dev Must be called by management, use sparingly as no restrictions are set * * @param _preSaleCloseTime the epoch time to set */ function updatePreSaleCloseTime(uint256 _preSaleCloseTime) external onlyManagement { require(_preSaleCloseTime > privateSaleCloseTime, "A pre sale time must be after the private sale close time"); preSaleCloseTime = _preSaleCloseTime; } /** * @dev Allows for updating the pre sale close time in the event of a delay * @dev Must be called by management, use sparingly as no restrictions are set * * @param _closingTime the epoch time to set */ function updateClosingTime(uint256 _closingTime) external onlyManagement { require(_closingTime > preSaleCloseTime, "A closing time must be after the pre-sale close time"); closingTime = _closingTime; } /** * @dev Allows for updating the minimum contribution required to participate * @dev Must be called by management * * @param _minimumContribution the minimum contribution to set */ function updateMinimumContribution(uint256 _minimumContribution) external onlyManagement { require(_minimumContribution > 0, "Minimum contribution must be great than zero"); minimumContribution = _minimumContribution; emit MinimumContributionUpdated(_minimumContribution); } /** * @dev Utility method for returning a set of epoch dates about the ICO */ function getDateRanges() external view returns ( uint256 _openingTime, uint256 _privateSaleCloseTime, uint256 _preSaleCloseTime, uint256 _closingTime ) { return ( openingTime, privateSaleCloseTime, preSaleCloseTime, closingTime ); } /** * @dev Extend parent behavior to update user contributions so far * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { super._updatePurchasingState(_beneficiary, _weiAmount); contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount); } /** * @dev Checks whether the hard cap has been reached. * @return Whether the cap was reached */ function hardCapReached() public view returns (bool) { return weiRaised >= hardCap; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Overridden method used to allow different rates for private/pre sale * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (now < privateSaleCloseTime) { return _weiAmount.mul(privateSaleRate); } if (now < preSaleCloseTime) { return _weiAmount.mul(preSaleRate); } return _weiAmount.mul(rate); } /** * @dev Checks whether the period in which the crowdsale is open has elapsed. * @return true if crowdsale period is open, otherwise false */ function isCrowdsaleOpen() public view returns (bool) { return now >= openingTime && now <= closingTime; } /** * @dev Extend parent behavior requiring contract to not be paused. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(isCrowdsaleOpen(), "Crowdsale not open"); require(weiRaised.add(_weiAmount) <= hardCap, "Exceeds maximum cap"); require(_weiAmount >= minimumContribution, "Beneficiary minimum amount not reached"); require(whitelist[_beneficiary], "Beneficiary not whitelisted"); require(whitelist[msg.sender], "Sender not whitelisted"); require(!paused, "Contract paused"); } /** * @dev Allow owner to transfer tokens. Will be used to transfer unsold tokens. * @param _beneficiary Token beneficiary * @param _tokenAmount Amount of tokens to deliver */ function transfer(address _beneficiary, uint256 _tokenAmount) external onlyOwner { _deliverTokens(_beneficiary, _tokenAmount); emit OwnerTransfer(msg.sender, address(this), _beneficiary, _tokenAmount); } }
Allows for updating the pre sale close time in the event of a delay Must be called by management, use sparingly as no restrictions are set _closingTime the epoch time to set/
function updateClosingTime(uint256 _closingTime) external onlyManagement { require(_closingTime > preSaleCloseTime, "A closing time must be after the pre-sale close time"); closingTime = _closingTime; }
5,466,565
./full_match/84531/0x42568094C97AaDb1fbBA949Ee212c44870Da05b0/sources/contracts/dsync.sol/dsync.sol
payable(DSYNC_VAULT).transfer((Listing.bounty DELETION_FEES)/10_000); IERC20(denomination).transfer(DSYNC_VAULT, (Listing.bounty DELETION_FEES)/10_000);
function deleteTask(bytes32 _taskHash) external payable whenNotPaused nonReentrant { contributionLog storage submission = Contributions[_taskHash]; require( submission.contributorCount == 0, "Cant delete subscribed task" ); taskLog storage Listing = Listings[_taskHash]; require(Listing.creator == msg.sender, "You are not creator"); require(Listing.state != JobState.PAUSE, "Job in Dispute"); address denomination = Listing.denominatedIN; uint256 refund = Listing.bounty - ((Listing.bounty * DELETION_FEES) / 10_000); Listing.state = JobState.PAUSE; if (denomination == address(0)) { payable(msg.sender).transfer(refund); IERC20(denomination).transfer(msg.sender, refund); } emit ListingDeleted(_taskHash, msg.sender); }
11,530,623
./full_match/43113/0x394B2ed7e3D7b1B4889E40B2eb3157cf2FdD9F4C/sources/AnubPresale_flat.sol
All requirementsAdjust guaranteed sold Is not buying only the guaranteed sold Still have token available?
function buyAnubToken(uint256 amountIn) external isFromContract { require(presale_enable, "Presale disabled"); require(isWhiteListed(msg.sender), "Not whitelised"); require(MIM.balanceOf(msg.sender) >= amountIn * DEFAULT_ANB_PRICE, "Balance insufficient"); require(soldListed[msg.sender].guaranteedSold <= amountIn || presale_sold + amountIn <= PRESALE_MAX_TOKEN, "No more token available (limit reached)"); require(amountIn >= MIN_PER_ACCOUNT, "Amount is not sufficient"); require(amountIn + soldListed[msg.sender].totalSold <= MAX_PER_ACCOUNT, "Amount buyable reached"); if(soldListed[msg.sender].guaranteedSold > 0) { if(soldListed[msg.sender].guaranteedSold - amountIn < 0) { if (amountIn - soldListed[msg.sender].guaranteedSold <= PRESALE_MAX_TOKEN) { soldListed[msg.sender].guaranteedSold = 0; amountIn = soldListed[msg.sender].guaranteedSold; soldListed[msg.sender].guaranteedSold = 0; } soldListed[msg.sender].guaranteedSold -= amountIn; } } soldListed[msg.sender].totalSold += amountIn; presale_sold += amountIn; emit BuyEvent(msg.sender, amountIn); }
7,126,882
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff. */ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { //@dev Emitted when `tokenId` token is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); //@dev Emitted when `owner` enables `approved` to manage the `tokenId` token. event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); //@dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); //@dev Returns the number of tokens in ``owner``'s account. function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from,address to,uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; //@dev Returns if the `operator` is allowed to manage all of the assets of `owner`. function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface IERC721Metadata is IERC721 { //@dev Returns the token collection name. function name() external view returns (string memory); //@dev Returns the token collection symbol. function symbol() external view returns (string memory); //@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) external view returns (string memory); } interface 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); } 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); } 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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); } } abstract contract Functionality { function toString(uint256 value) internal pure returns (string memory) { 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); } bool private _reentryKey = false; modifier reentryLock { require(!_reentryKey, "attempt to reenter a locked function"); _reentryKey = true; _; _reentryKey = false; } } // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** contract dice is IERC721, Ownable, Functionality { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; //for setting purchase limits per collection mapping(uint256 => mapping(address => uint256)) public numPurchased; struct diceGroup { bool diceLock; uint256 numTokens; //tokens minted so far uint256 maxTokens; //max tokens of this type uint256 startId; //Start location for tokenID uint256 price; //Cost in wei uint256 payoutPercent; uint256 payoutBalance; uint256 giveawayBalance; uint256 purchaseThreshold; string tokenURI; address payoutAddress; } diceGroup[] collection; //TokenID to collection ID mapping (uint256 => uint256) diceType; //Holder's Dice Bag mapping (address => uint256[]) diceBag; //Global Variables uint256 totalTokensReserved; uint256 primaryBalance; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "DICE"; _symbol = "DICE"; _baseURI = "https://triple7dice.club/metadata/contract.json"; } // **************************************** Internal Functions ******************* function createDice(uint256 maxTokens, uint256 price, string memory uri_, uint256 maxPurchase) external onlyOwner reentryLock { //initialize the new token diceGroup memory newDice; newDice.numTokens = 0; newDice.maxTokens = maxTokens; newDice.startId = totalTokensReserved; newDice.payoutAddress = address(0); newDice.payoutPercent = 0; newDice.giveawayBalance = 0; newDice.price = price; newDice.tokenURI = uri_; newDice.diceLock = true; newDice.purchaseThreshold = maxPurchase; //Incriment the allocation variable totalTokensReserved += maxTokens; //Add the new token to the collection collection.push(newDice); } function mint(uint256 ID, uint256 amount) external payable { diceGroup memory tempId = collection[ID]; uint256 price = tempId.price; require(amount > 0, "You must mint a positive number"); require(numPurchased[ID][_msgSender()] + amount <= tempId.purchaseThreshold, "Can't mint that many"); require(amount + tempId.numTokens + tempId.giveawayBalance <= tempId.maxTokens, "Not enough dice remaining"); require(msg.value >= price * amount, "You can't afford that"); require(!tempId.diceLock, "Those dice are not for sale"); //handle payouts uint256 reserve = (amount * price * tempId.payoutPercent) / 100; uint256 leftoverBalance = (price * amount) - reserve; collection[ID].payoutBalance += reserve; primaryBalance += leftoverBalance; //mint tokens and update tallies uint256 tokenStart = collection[ID].startId + collection[ID].numTokens; for ( uint256 i; i < amount; i++) { _safeMint(_msgSender(), tokenStart + i); diceType[tokenStart + i] = ID; } collection[ID].numTokens +=amount; if ((price * amount) < msg.value) { uint256 change = (msg.value - (price*amount)); (bool success, ) = msg.sender.call{value: change}(""); require(success, "Mint: unable to send change to user"); } } function founderMint(uint256 ID, address[] memory to) external reentryLock{ uint256 arraySize = to.length; require(_msgSender() == collection[ID].payoutAddress || _msgSender() == owner()); diceGroup memory tempId = collection[ID]; require(tempId.numTokens + tempId.giveawayBalance + arraySize <= tempId.maxTokens, "Not enough dice remaining"); uint256 tokenStart = tempId.startId + tempId.numTokens; collection[ID].numTokens += arraySize; if (collection[ID].giveawayBalance >= arraySize) { collection[ID].giveawayBalance -= arraySize; } else { collection[ID].giveawayBalance = 0; } for (uint256 i; i < arraySize; i++) { diceType[tokenStart + i] = ID; _safeMint(to[i], tokenStart + i); } } function assignFounder(uint256 ID, uint256 founderPercentage, address receiver, uint256 freebies) external onlyOwner { //Approve a sponsored account to receive payment or ammend contract terms collection[ID].payoutPercent = founderPercentage; collection[ID].payoutAddress = receiver; collection[ID].giveawayBalance = freebies; } function ownerFunds() external view onlyOwner returns(uint256) { return primaryBalance; } function withdraw(uint256 sendAmount) external onlyOwner { require(sendAmount <= primaryBalance); primaryBalance -= sendAmount; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function receiveFunds(uint256 ID) external reentryLock { //Verify ownership of the token class require(collection[ID].payoutAddress != address(0)); require(_msgSender() == collection[ID].payoutAddress, "Unauthorized Transaction!"); uint256 sendAmount = collection[ID].payoutBalance; collection[ID].payoutBalance = 0; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == dice.onERC721Received.selector; } // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } // ******************************* Dice Interface ******************************** function setPurchaseMax(uint groupID, uint256 maxPerWallet) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].purchaseThreshold = maxPerWallet; } function getType(uint256 tokenId) external view returns (uint256) { return diceType[tokenId]; } function getPrice(uint256 groupID) external view returns (uint256) { return collection[groupID].price; } function getDiceMinted(uint256 groupID) external view returns (uint256) { return collection[groupID].numTokens; } function getURI(uint256 groupID) external view returns (string memory) { return collection[groupID].tokenURI; } function getAllDice(address holder) external view returns (uint256[] memory) { return diceBag[holder]; } function setURI(uint256 groupID, string memory uri_) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].tokenURI = uri_; } function verifyFunds(uint256 ID) external view returns(uint256) { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); return collection[ID].payoutBalance; } function lockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = true; } function unlockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = false; } function checkLock(uint256 ID) external view returns(bool) { return collection[ID].diceLock; } // ************************** Internal Functions *********************************** function addDiceToBag(address holder, uint256 tokenId) internal { diceBag[holder].push(tokenId); } function removeDiceFromBag(address holder, uint256 tokenId) internal { uint256[] memory diceCollection = diceBag[holder]; bool foundIt; uint256 index; uint256 length = diceCollection.length; for (uint256 i; i < length; i++) { if (!foundIt) { if (diceCollection[i] == tokenId) { foundIt = true;} } if (foundIt) { if (i+1 < length) { diceCollection[i] = diceCollection[i+1]; index = i; break; } } } //make changes to the actual user bag if (index < length - 1) { diceBag[holder][index] = diceCollection[length - 1]; } diceBag[holder].pop(); } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _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 = 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 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(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(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(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @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) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @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 { //transfer functions take care of checks so we don't have to if(from != address(0)){ removeDiceFromBag(from, tokenId); } if(to != address(0)){ addDiceToBag(to, tokenId); } } //******************************************************** //**************** Fallback and Generic ****************** //******************************************************** //contractURI function for OpenSea, This is for ALL dice collections function contractURI() external view returns (string memory) { return string(abi.encodePacked(_baseURI)); } // TokenURI for OS function tokenURI(uint256 tokenId) public view returns (string memory) { uint256 groupID = diceType[tokenId]; ///require that token exists require((tokenId - collection[groupID].startId) < collection[groupID].numTokens); return string(abi.encodePacked(collection[groupID].tokenURI, toString((tokenId - collection[groupID].startId)), ".json")); } //Fallback function receive () external payable { primaryBalance += msg.value; } }
make changes to the actual user bag
function removeDiceFromBag(address holder, uint256 tokenId) internal { uint256[] memory diceCollection = diceBag[holder]; bool foundIt; uint256 index; uint256 length = diceCollection.length; for (uint256 i; i < length; i++) { if (!foundIt) { } if (foundIt) { if (i+1 < length) { diceCollection[i] = diceCollection[i+1]; index = i; break; } } } if (index < length - 1) { diceBag[holder][index] = diceCollection[length - 1]; } diceBag[holder].pop(); }
1,472,014
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================== ApeSwapLiquidityAMO ======================= // ==================================================================== // Provides Uniswap V2-style liquidity // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian import "../../../ERC20/ERC20.sol"; import "../../../ERC20/__CROSSCHAIN/CrossChainCanonicalFRAX.sol"; import "../../../ERC20/__CROSSCHAIN/CrossChainCanonicalFXS.sol"; import "../../../Bridges/BSC/CrossChainBridgeBacker_BSC_AnySwap.sol"; import "../../apeswap/IApePair.sol"; import "../../apeswap/IApeRouter.sol"; import "../../../Staking/Owned.sol"; import '../../../Uniswap/TransferHelper.sol'; contract ApeSwapLiquidityAMO is Owned { // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ // Core CrossChainCanonicalFRAX private canFRAX; CrossChainCanonicalFXS private canFXS; CrossChainBridgeBacker_BSC_AnySwap public cc_bridge_backer; ERC20 private collateral_token; address public canonical_frax_address; address public canonical_fxs_address; address public collateral_token_address; // Important addresses address public timelock_address; address public custodian_address; // Router IApeRouter public router = IApeRouter(0xcF0feBd3f17CEf5b47b0cD257aCf6025c5BFf3b7); // Positions address[] public frax_fxs_pair_addresses_array; mapping(address => bool) public frax_fxs_pair_addresses_allowed; // Slippages uint256 public add_rem_liq_slippage = 20000; // 2.0% // Constants uint256 public missing_decimals; uint256 private PRICE_PRECISION = 1e6; /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _custodian_address, address _canonical_frax_address, address _canonical_fxs_address, address _collateral_token_address, address _cc_bridge_backer_address, address[] memory _initial_pairs ) Owned(_owner_address) { // Core addresses canonical_frax_address = _canonical_frax_address; canonical_fxs_address = _canonical_fxs_address; collateral_token_address = _collateral_token_address; // Core instances canFRAX = CrossChainCanonicalFRAX(_canonical_frax_address); canFXS = CrossChainCanonicalFXS(_canonical_fxs_address); collateral_token = ERC20(_collateral_token_address); cc_bridge_backer = CrossChainBridgeBacker_BSC_AnySwap(_cc_bridge_backer_address); // Set the custodian custodian_address = _custodian_address; // Get the timelock address from the minter timelock_address = cc_bridge_backer.timelock_address(); // Get the missing decimals for the collateral missing_decimals = uint(18) - collateral_token.decimals(); // Set the initial pairs for (uint256 i = 0; i < _initial_pairs.length; i++){ _addTrackedLP(_initial_pairs[i]); } } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[17] memory allocations) { // Get the FXS price uint256 fxs_price = cc_bridge_backer.cross_chain_oracle().getPrice(canonical_fxs_address); // Loop through the lp tokens uint256[] memory lp_tallies = new uint256[](4); // 0 = FRAX, 1 = FXS, 2 = Collateral, 3 = USD value for (uint i = 0; i < frax_fxs_pair_addresses_array.length; i++){ address pair_address = frax_fxs_pair_addresses_array[i]; if (frax_fxs_pair_addresses_allowed[pair_address]) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the pair info uint256[4] memory lp_info_pack = lpTokenInfo(pair_address); // Get the lp token balance uint256 lp_token_balance = the_pair.balanceOf(address(this)); // Get the FRAX and FXS balances uint256 frax_amt = (lp_info_pack[0] * lp_token_balance) / 1e18; uint256 fxs_amt = (lp_info_pack[1] * lp_token_balance) / 1e18; uint256 collat_amt = (lp_info_pack[2] * lp_token_balance) / 1e18; // Add to the tallies lp_tallies[0] += frax_amt; lp_tallies[1] += fxs_amt; lp_tallies[2] += collat_amt; // Get the USD value if (lp_info_pack[3] == 0 || lp_info_pack[3] == 2){ // If FRAX is in the pair, just double the FRAX balance since it is 50/50 lp_tallies[3] += (frax_amt * 2); } else { // Otherwise, double the value of the FXS component lp_tallies[3] += ((fxs_amt * fxs_price) / PRICE_PRECISION) * 2; } } } // FRAX allocations[0] = canFRAX.balanceOf(address(this)); // Free FRAX allocations[1] = lp_tallies[0]; // FRAX in LP allocations[2] = allocations[0] + allocations[1]; // Total FRAX // FXS allocations[3] = canFXS.balanceOf(address(this)); // Free FXS, native E18 allocations[4] = (allocations[3] * fxs_price) / PRICE_PRECISION; // Free FXS USD value allocations[5] = lp_tallies[1]; // FXS in LP, native E18 allocations[6] = (allocations[5] * fxs_price) / PRICE_PRECISION; // FXS in LP USD value allocations[7] = allocations[3] + allocations[5]; // Total FXS, native E18 allocations[8] = allocations[4] + allocations[6]; // Total FXS USD Value // Collateral allocations[9] = collateral_token.balanceOf(address(this)); // Free Collateral, native precision allocations[10] = (allocations[9] * (10 ** missing_decimals)); // Free Collateral USD value allocations[11] = lp_tallies[2]; // Collateral in LP, native precision allocations[12] = (allocations[11] * (10 ** missing_decimals)); // Collateral in LP USD value allocations[13] = allocations[9] + allocations[11]; // Total Collateral, native precision allocations[14] = allocations[10] + allocations[12]; // Total Collateral USD Value // LP allocations[15] = lp_tallies[3]; // Total USD value in all LPs // Totals allocations[16] = allocations[2] + allocations[8] + allocations[14]; // Total USD value in entire AMO, including FXS } function showTokenBalances() public view returns (uint256[3] memory tkn_bals) { tkn_bals[0] = canFRAX.balanceOf(address(this)); // canFRAX tkn_bals[1] = canFXS.balanceOf(address(this)); // canFXS tkn_bals[2] = collateral_token.balanceOf(address(this)); // collateral_token } // [0] = FRAX per LP token // [1] = FXS per LP token // [2] = Collateral per LP token // [3] = pair_type function lpTokenInfo(address pair_address) public view returns (uint256[4] memory return_info) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the reserves uint256[] memory reserve_pack = new uint256[](3); // [0] = FRAX, [1] = FXS, [2] = Collateral (uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves()); { // Get the underlying tokens in the LP address token0 = the_pair.token0(); address token1 = the_pair.token1(); // Test token0 if (token0 == canonical_frax_address) reserve_pack[0] = reserve0; else if (token0 == canonical_fxs_address) reserve_pack[1] = reserve0; else if (token0 == collateral_token_address) reserve_pack[2] = reserve0; // Test token1 if (token1 == canonical_frax_address) reserve_pack[0] = reserve1; else if (token1 == canonical_fxs_address) reserve_pack[1] = reserve1; else if (token1 == collateral_token_address) reserve_pack[2] = reserve1; } // Get the token rates return_info[0] = (reserve_pack[0] * 1e18) / (the_pair.totalSupply()); return_info[1] = (reserve_pack[1] * 1e18) / (the_pair.totalSupply()); return_info[2] = (reserve_pack[2] * 1e18) / (the_pair.totalSupply()); // Set the pair type (used later) if (return_info[0] > 0 && return_info[1] == 0) return_info[3] = 0; // FRAX/XYZ else if (return_info[0] == 0 && return_info[1] > 0) return_info[3] = 1; // FXS/XYZ else if (return_info[0] > 0 && return_info[1] > 0) return_info[3] = 2; // FRAX/FXS else revert("Invalid pair"); } // Needed by CrossChainBridgeBacker function allDollarBalances() public view returns ( uint256 frax_ttl, uint256 fxs_ttl, uint256 col_ttl, // in native decimals() uint256 ttl_val_usd_e18 ) { uint256[17] memory allocations = showAllocations(); return (allocations[2], allocations[7], allocations[13], allocations[16]); } function borrowed_frax() public view returns (uint256) { return cc_bridge_backer.frax_lent_balances(address(this)); } function borrowed_fxs() public view returns (uint256) { return cc_bridge_backer.fxs_lent_balances(address(this)); } function borrowed_collat() public view returns (uint256) { return cc_bridge_backer.collat_lent_balances(address(this)); } function total_profit() public view returns (int256 profit) { // Get the FXS price uint256 fxs_price = cc_bridge_backer.cross_chain_oracle().getPrice(canonical_fxs_address); uint256[17] memory allocations = showAllocations(); // Handle FRAX profit = int256(allocations[2]) - int256(borrowed_frax()); // Handle FXS profit += ((int256(allocations[7]) - int256(borrowed_fxs())) * int256(fxs_price)) / int256(PRICE_PRECISION); // Handle Collat profit += (int256(allocations[13]) - int256(borrowed_collat())) * int256(10 ** missing_decimals); } // token_there_is_one_of means you want the return amount to be (X other token) per 1 token; function pair_reserve_ratio_E18(address pair_address, address token_there_is_one_of) public view returns (uint256) { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Get the token addresses address token0 = the_pair.token0(); address token1 = the_pair.token1(); uint256 decimals0 = ERC20(token0).decimals(); uint256 decimals1 = ERC20(token1).decimals(); (uint256 reserve0, uint256 reserve1, ) = (the_pair.getReserves()); uint256 miss_dec = (decimals0 >= decimals1) ? (decimals0 - decimals1) : (decimals1 - decimals0); // Put everything into E18. Since one of the pair tokens will always be FRAX or FXS, this is ok to assume. if (decimals0 >= decimals1){ reserve1 *= (10 ** miss_dec); } else { reserve0 *= (10 ** miss_dec); } // Return the ratio if (token0 == token_there_is_one_of){ return (uint256(1e18) * reserve0) / reserve1; } else if (token1 == token_there_is_one_of){ return (uint256(1e18) * reserve1) / reserve0; } else revert("Token not in pair"); } /* ========== Swap ========== */ // Swap tokens directly function swapTokens( address from_token_address, uint256 from_in, address to_token_address, uint256 to_token_out_min ) public onlyByOwnGov returns (uint256[] memory amounts) { // Approval ERC20(from_token_address).approve(address(router), from_in); // Create the path object (compiler doesn't like feeding it in directly) address[] memory the_path = new address[](2); the_path[0] = from_token_address; the_path[1] = to_token_address; // Swap amounts = router.swapExactTokensForTokens( from_in, to_token_out_min, the_path, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } // If you need a specific path function swapTokensWithCustomPath( address from_token_address, uint256 from_in, uint256 end_token_out_min, address[] memory path ) public onlyByOwnGov returns (uint256[] memory amounts) { // Approval ERC20(from_token_address).approve(address(router), from_in); // Swap amounts = router.swapExactTokensForTokens( from_in, end_token_out_min, path, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } /* ========== Add / Remove Liquidity ========== */ function addLiquidity( address lp_token_address, address tokenA_address, uint256 tokenA_amt, address tokenB_address, uint256 tokenB_amt ) public onlyByOwnGov returns (uint256 amountA, uint256 amountB, uint256 liquidity) { require(frax_fxs_pair_addresses_allowed[lp_token_address], "LP address not allowed"); // Approvals ERC20(tokenA_address).approve(address(router), tokenA_amt); ERC20(tokenB_address).approve(address(router), tokenB_amt); // Add liquidity (amountA, amountB, liquidity) = router.addLiquidity( tokenA_address, tokenB_address, tokenA_amt, tokenB_amt, tokenA_amt - ((tokenA_amt * add_rem_liq_slippage) / PRICE_PRECISION), tokenB_amt - ((tokenB_amt * add_rem_liq_slippage) / PRICE_PRECISION), address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } function removeLiquidity( address lp_token_address, uint256 lp_token_in ) public onlyByOwnGov returns (uint256 amountA, uint256 amountB) { require(frax_fxs_pair_addresses_allowed[lp_token_address], "LP address not allowed"); // Approvals ERC20(lp_token_address).approve(address(router), lp_token_in); // Get the token addresses address tokenA = IApePair(lp_token_address).token0(); address tokenB = IApePair(lp_token_address).token1(); // Remove liquidity (amountA, amountB) = router.removeLiquidity( tokenA, tokenB, lp_token_in, 0, 0, address(this), block.timestamp + 604800 // Expiration: 7 days from now ); } /* ========== Burns and givebacks ========== */ function giveFRAXBack(uint256 frax_amount, bool do_bridging) external onlyByOwnGov { canFRAX.approve(address(cc_bridge_backer), frax_amount); cc_bridge_backer.receiveBackViaAMO(canonical_frax_address, frax_amount, do_bridging); } function giveFXSBack(uint256 fxs_amount, bool do_bridging) external onlyByOwnGov { canFXS.approve(address(cc_bridge_backer), fxs_amount); cc_bridge_backer.receiveBackViaAMO(canonical_fxs_address, fxs_amount, do_bridging); } function giveCollatBack(uint256 collat_amount, bool do_bridging) external onlyByOwnGov { collateral_token.approve(address(cc_bridge_backer), collat_amount); cc_bridge_backer.receiveBackViaAMO(collateral_token_address, collat_amount, do_bridging); } /* ========== RESTRICTED FUNCTIONS ========== */ // Any pairs with FRAX and/or FXS must be whitelisted first before adding liquidity function _addTrackedLP(address pair_address) internal { // Instantiate the pair IApePair the_pair = IApePair(pair_address); // Make sure either FRAX or FXS is present bool frax_present = (the_pair.token0() == canonical_frax_address || the_pair.token1() == canonical_frax_address); bool fxs_present = (the_pair.token0() == canonical_fxs_address || the_pair.token1() == canonical_fxs_address); require(frax_present || fxs_present, "FRAX or FXS not in pair"); // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == false, "LP already exists"); frax_fxs_pair_addresses_allowed[pair_address] = true; frax_fxs_pair_addresses_array.push(pair_address); } function addTrackedLP(address pair_address) public onlyByOwnGov { _addTrackedLP(pair_address); } // Remove FRAX and FXS related pairs function removeTrackedLP(address pair_address) public onlyByOwnGov { // Adjust the state variables require(frax_fxs_pair_addresses_allowed[pair_address] == true, "LP not already present"); frax_fxs_pair_addresses_allowed[pair_address] = false; // 'Delete' from the array by setting the address to 0x0 for (uint i = 0; i < frax_fxs_pair_addresses_array.length; i++){ if (frax_fxs_pair_addresses_array[i] == pair_address) { frax_fxs_pair_addresses_array[i] = address(0); // This will leave a null in the array and keep the indices the same break; } } } function setCCBridgeBacker(address _cc_bridge_backer_address) external onlyByOwnGov { cc_bridge_backer = CrossChainBridgeBacker_BSC_AnySwap(_cc_bridge_backer_address); // Get the timelock addresses from the minter timelock_address = cc_bridge_backer.timelock_address(); // Make sure the new addresse is not address(0) require(timelock_address != address(0), "Invalid timelock"); } function setSlippages(uint256 _add_rem_liq_slippage) external onlyByOwnGov { add_rem_liq_slippage = _add_rem_liq_slippage; } function setCustodian(address _custodian_address) external onlyByOwnGov { require(_custodian_address != address(0), "Zero address detected"); custodian_address = _custodian_address; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
If you need a specific path Approval Swap
function swapTokensWithCustomPath( address from_token_address, uint256 from_in, uint256 end_token_out_min, address[] memory path ) public onlyByOwnGov returns (uint256[] memory amounts) { ERC20(from_token_address).approve(address(router), from_in); amounts = router.swapExactTokensForTokens( from_in, end_token_out_min, path, address(this), ); }
1,834,688
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "maki-swap-lib/contracts/math/SafeMath.sol"; import "maki-swap-lib/contracts/token/HRC20/IHRC20.sol"; import "maki-swap-lib/contracts/token/HRC20/SafeHRC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./MakiToken.sol"; import "./SoyBar.sol"; interface IMigratorChef { // Perform LP token migration from legacy MakiSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to MakiSwap LP tokens. // MakiSwap must mint EXACTLY the same amount of Maki LP tokens or // else something bad will happen. Traditional MakiSwap does not // do that so be careful! function migrate(IHRC20 token) external returns (IHRC20); } // MasterChef is the master of Maki. She can make Maki and she is a fair lady. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once MAKI is sufficiently // distributed and the community can show to govern itself. contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeHRC20 for IHRC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of MAKI // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accMakiPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accMakiPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IHRC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. MAKIs to distribute per block. uint256 lastRewardBlock; // Last block number that MAKIs distribution occurs. uint256 accMakiPerShare; // Accumulated MAKIs per share, times 1e12. See below. } //** ADDRESSES **// // The MAKI TOKEN! MakiToken public maki; // The SOY TOKEN! SoyBar public soy; // Team address, which recieves 1.5 MAKI per block (mutable by team) address public team = msg.sender; // Treasury address, which recieves 1.5 MAKI per block (mutable by team and treasury) address public treasury = msg.sender; // The migrator contract. It has a lot of power. Can only be set through governance (treasury). IMigratorChef public migrator; // ** GLOBAL VARIABLES ** // // MAKI tokens created per block. uint256 public makiPerBlock = 16e18; // 16 MAKI per block minted // Bonus muliplier for early maki makers. uint256 public bonusMultiplier = 1; // The block number when MAKI mining starts. uint256 public startBlock = block.number; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // ** POOL VARIABLES ** // // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; event Team(address team); event Treasury(address treasury); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MakiToken _maki, SoyBar _soy ) public { maki = _maki; soy = _soy; // staking pool poolInfo.push( PoolInfo({ lpToken: _maki, allocPoint: 1000, lastRewardBlock: startBlock, accMakiPerShare: 0 }) ); totalAllocPoint = 1000; } modifier validatePoolByPid(uint256 _pid) { require(_pid < poolInfo.length, "pool does not exist"); _; } // VALIDATION -- ELIMINATES POOL DUPLICATION RISK -- NONE function checkPoolDuplicate(IHRC20 _token ) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _token, "add: existing pool"); } } function updateMultiplier(uint256 multiplierNumber) public { require(msg.sender == treasury, "updateMultiplier: only treasury may update"); bonusMultiplier = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // ADD -- NEW LP TOKEN POOL -- OWNER function add(uint256 _allocPoint, IHRC20 _lpToken, bool _withUpdate) public onlyOwner { checkPoolDuplicate(_lpToken); addPool(_allocPoint, _lpToken, _withUpdate); } function addPool(uint256 _allocPoint, IHRC20 _lpToken, bool _withUpdate) internal { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accMakiPerShare: 0 }) ); updateStakingPool(); } // UPDATE -- ALLOCATION POINT -- OWNER function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner validatePoolByPid(_pid) { require(_pid < poolInfo.length, "set: pool does not exist"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add( _allocPoint ); updateStakingPool(); } } // UPDATE -- STAKING POOL -- INTERNAL function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add( points ); poolInfo[0].allocPoint = points; } } // SET -- MIGRATOR CONTRACT -- OWNER function setMigrator(IMigratorChef _migrator) public { require(msg.sender == treasury, "setMigrator: must be from treasury"); migrator = _migrator; } // MIGRATE -- LP TOKENS TO ANOTHER CONTRACT -- MIGRATOR function migrate(uint256 _pid) public validatePoolByPid(_pid) { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IHRC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IHRC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // VIEW -- BONUS MULTIPLIER -- PUBLIC function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(bonusMultiplier); } // VIEW -- PENDING MAKI function pendingMaki(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMakiPerShare = pool.accMakiPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 makiReward = multiplier.mul(makiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accMakiPerShare = accMakiPerShare.add( makiReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accMakiPerShare).div(1e12).sub(user.rewardDebt); } // UPDATE -- REWARD VARIABLES FOR ALL POOLS (HIGH GAS POSSIBLE) -- PUBLIC function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // UPDATE -- REWARD VARIABLES (POOL) -- PUBLIC function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 makiReward = multiplier.mul(makiPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); uint256 adminFee = makiReward.mul(1000).div(10650); uint256 netReward = makiReward.sub(adminFee.mul(2)); maki.mint(team, adminFee); // 1.50 MAKI per block to team (9.375%) maki.mint(treasury, adminFee); // 1.50 MAKI per block to treasury (9.375%) maki.mint(address(soy), netReward); pool.accMakiPerShare = pool.accMakiPerShare.add( netReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // DEPOSIT -- LP TOKENS -- LP OWNERS function deposit(uint256 _pid, uint256 _amount) public nonReentrant validatePoolByPid(_pid) { require(_pid != 0, "deposit MAKI by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { // already deposited assets uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { // sends pending rewards, if applicable safeMakiTransfer(msg.sender, pending); } } if (_amount > 0) { // if adding more pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accMakiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // WITHDRAW -- LP TOKENS -- STAKERS function withdraw(uint256 _pid, uint256 _amount) public nonReentrant validatePoolByPid(_pid) { require(_pid != 0, "withdraw MAKI by unstaking"); 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.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(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.accMakiPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // STAKE -- MAKI TO MASTERCHEF -- PUBLIC MAKI HOLDERS function enterStaking(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(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.accMakiPerShare).div(1e12); soy.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // WITHDRAW -- MAKI tokens from STAKING. function leaveStaking(uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(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.accMakiPerShare).div(1e12); soy.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); } // TRANSFER -- TRANSFERS SOY -- INTERNAL function safeMakiTransfer(address _to, uint256 _amount) internal { soy.safeMakiTransfer(_to, _amount); } // UPDATE -- TREASURY ADDRESS -- TREASURY || TEAM function newTreasury(address _treasury) public { require( msg.sender == treasury || msg.sender == team, "treasury: invalid permissions" ); treasury = _treasury; emit Treasury(_treasury); } // UPDATE -- TEAM ADDRESS -- TEAM function newTeam(address _team) public { require(msg.sender == team, "team: le who are you?"); team = _team; emit Team(_team); } }
DEPOSIT -- LP TOKENS -- LP OWNERS already deposited assets sends pending rewards, if applicable if adding more
function deposit(uint256 _pid, uint256 _amount) public nonReentrant validatePoolByPid(_pid) { require(_pid != 0, "deposit MAKI by staking"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accMakiPerShare).div(1e12).sub( user.rewardDebt ); if (pending > 0) { safeMakiTransfer(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.accMakiPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
15,849,335
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Junkeng { enum ParticipantStatus { NoRegistration, NoParticipating, Participated } enum MatchStatus { NoParticipating, Participated, Disclosed, Settled } enum HandShape { Undefined, Guu, Choki, Paa } struct ParticipantContext { uint current; // Current index of queue ParticipantStatus status; uint streak; // Win streak uint phase; // Increment every transaction. This helps frontend status transition } struct Queue { address addr; HandShape handShape; uint timestamp; // block.timestamp MatchStatus status; } address private admin; address private coin; // Match context Queue[] private queue; mapping (address => ParticipantContext) private participants; // User's asset mapping (address => uint) private coinStock; /** * Emit when participant joined. */ event Joined(address addr, uint index); /** * Emit when the match has been established. */ event Established(address a, uint a_index, address b, uint b_index, uint timestamp); /** * Emit when hand shape has been disclosed. (It cannot obtain hand shape value!) */ event Disclosed(address addr, uint index); /** * Emit when each participants disclosed their hand shape. */ event Settled(address a, uint a_index, uint8 a_handShape, address b, uint b_index, uint8 b_handShape); /** * Emit when awarded JunkCoin to winner */ event Earned(address addr, uint index, uint amount); /** * Emit when withdrew JunkCoin */ event Withdrew(address addr, uint amount); /** * Sender is registered */ modifier registered() { require(participants[msg.sender].status > ParticipantStatus.NoRegistration, "No registration"); _; } /** * Sender is participant */ modifier participating() { require(participants[msg.sender].status > ParticipantStatus.NoParticipating, "Not participants"); _; } /** * Sender is non participant */ modifier notParticipating() { require(participants[msg.sender].status <= ParticipantStatus.NoParticipating, "Already participated"); _; } /** * Calc opponent index */ function calcOpponentIndex(uint _index) pure private returns(uint) { return (_index & ~uint(1)) + ((_index + 1) & uint(1)); } /** * Get opponent index * Require exists */ function getOpponent(uint _index) view private returns(uint) { // Even vs Odd uint opponent = calcOpponentIndex(_index); require(opponent < queue.length, "Opponent not ready"); return opponent; } /** * Get maximum of a and b */ function bigger(uint _a, uint _b) pure private returns(uint) { return (_a > _b) ? _a : _b; } /** * Calculate duration from latest timestamp */ function calcDuration(uint _a, uint _b) view private returns(uint) { return block.timestamp - bigger(_a, _b); } /** * Expire at 5 minutes after the match was established. */ modifier timeout() { if (participants[msg.sender].status == ParticipantStatus.Participated) { uint index = participants[msg.sender].current; uint opponent = calcOpponentIndex(index); if (opponent < queue.length) { // Keep deadline uint duration = calcDuration(queue[index].timestamp, queue[opponent].timestamp); if (duration > 5 minutes) { // Timeout -> Reset participants[msg.sender].status = ParticipantStatus.NoParticipating; if (queue[index].handShape != HandShape.Undefined && queue[opponent].handShape == HandShape.Undefined) { // Opponent timeout -> DEFWIN // Get coin coinStock[msg.sender] += ++participants[msg.sender].streak; emit Earned(msg.sender, index, participants[msg.sender].streak); } else { // Self timeout or both timeout -> DEFLOSS participants[msg.sender].streak = 0; } queue[index].status = MatchStatus.Settled; } } } _; } /** * Some coins have been stocked */ modifier haveCoins() { require(coinStock[msg.sender] > 0, "No coins"); _; } /** * Advance phase value after the transaction process */ modifier phaseAdvance() { _; participants[msg.sender].phase++; } /** * Settle match result * result: 0 draw, 1 win, -1 lose */ function settle(uint _index, uint _opponent) view private returns(int8) { // FIXME: Constants of non-value type not yet implemented on solidity 0.7.x int8[4][4] memory lookupTable = [ [int8(0), int8(-1), int8(-1), int8(-1)], [int8(1), int8( 0), int8( 1), int8(-1)], [int8(1), int8(-1), int8( 0), int8( 1)], [int8(1), int8( 1), int8(-1), int8( 0)] ]; return lookupTable[uint8(queue[_index].handShape)][uint8(queue[_opponent].handShape)]; } /** * Constructor * Obtain JunkCoin address from args * Obtain admin address from msg.sender */ constructor(address _coin) { coin = _coin; admin = msg.sender; } /** * Join match queue */ function join() public timeout notParticipating phaseAdvance { uint index = queue.length; queue.push(Queue({ addr: msg.sender, handShape: HandShape.Undefined, timestamp: block.timestamp, status: MatchStatus.Participated })); if (participants[msg.sender].status == ParticipantStatus.NoRegistration) { // New registration participants[msg.sender] = ParticipantContext({ current: index, status: ParticipantStatus.Participated, streak: 0, phase: 0 }); } else { // Continuous participants[msg.sender].current = index; participants[msg.sender].status = ParticipantStatus.Participated; } emit Joined(msg.sender, index); if (index % 2 == 1) { // Establish match when index is odd. uint timestamp = bigger(queue[index - 1].timestamp, queue[index].timestamp); emit Established(queue[index - 1].addr, index - 1, queue[index].addr, index, timestamp); } } /** * Disclose hand shape each other. * _handShape: 1 Guu, 2 Choki, 3 Paa */ function disclose(uint8 _handShape) public participating phaseAdvance { uint index = participants[msg.sender].current; uint opponent = getOpponent(index); address opponentAddr = queue[opponent].addr; require(queue[index].status == MatchStatus.Participated, "Already disclosed" ); require(_handShape >= 1 && _handShape <= 3, "Invalid hand shape"); // Keep deadline uint duration = calcDuration(queue[index].timestamp, queue[opponent].timestamp); if (duration > 5 minutes) { // Timeout -> Lost or Draw(if opponent timeout too) queue[index].handShape = HandShape.Undefined; } else { queue[index].handShape = HandShape(_handShape); } queue[index].status = MatchStatus.Disclosed; emit Disclosed(msg.sender, index); if (queue[opponent].status == MatchStatus.Disclosed) { emit Settled( msg.sender, index, uint8(queue[index].handShape), opponentAddr, opponent, uint8(queue[opponent].handShape) ); // Settlement int8 result = settle(index, opponent); if (result == 1) { // Won -> Get coin coinStock[msg.sender] += ++participants[msg.sender].streak; participants[msg.sender].status = ParticipantStatus.NoParticipating; // Reset opponent status for next join participants[opponentAddr].status = ParticipantStatus.NoParticipating; participants[opponentAddr].streak = 0; emit Earned(msg.sender, index, participants[msg.sender].streak); } else if (result == -1) { // Lost -> The coin is taken by opponent coinStock[opponentAddr] += ++participants[opponentAddr].streak; participants[opponentAddr].status = ParticipantStatus.NoParticipating; // Reset own status for next join participants[msg.sender].status = ParticipantStatus.NoParticipating; participants[msg.sender].streak = 0; emit Earned(opponentAddr, opponent, participants[opponentAddr].streak); } else { // Draw -> No one get coin // Reset both status for next join participants[msg.sender].status = ParticipantStatus.NoParticipating; participants[msg.sender].streak = 0; participants[opponentAddr].status = ParticipantStatus.NoParticipating; participants[opponentAddr].streak = 0; } queue[index].status = MatchStatus.Settled; queue[opponent].status = MatchStatus.Settled; participants[opponentAddr].phase++; } } /** * Withdraw JunkCoin */ function withdraw() public timeout haveCoins phaseAdvance { uint amount = coinStock[msg.sender]; coinStock[msg.sender] = 0; IERC20(coin).transferFrom(admin, msg.sender, amount); emit Withdrew(msg.sender, amount); } /** * Get own status */ function getStatus() view public registered returns(address addr, uint index, uint8 status, uint timestamp, uint8 handShape, uint streak, uint phase) { addr = msg.sender; index = participants[msg.sender].current; status = uint8(queue[index].status); timestamp = queue[index].timestamp; handShape = uint8(queue[index].handShape); streak = participants[msg.sender].streak; phase = participants[msg.sender].phase; } /** * Get own coin balance * This is view function so `block.timestamp` isn't update. Obtain actual timestamp from args. */ function getCoinBalance(uint timestamp) view public returns(uint coins) { if (participants[msg.sender].status == ParticipantStatus.Participated) { // Keep deadline uint index = participants[msg.sender].current; if (queue[index].status == MatchStatus.Disclosed) { // No settled yet uint opponent = getOpponent(index); uint duration = timestamp - bigger(queue[index].timestamp, queue[opponent].timestamp); if (duration > 5 minutes && queue[index].handShape != HandShape.Undefined && queue[opponent].handShape == HandShape.Undefined) { // DEFWIN previous match, add (streak + 1) coins to balance coins += participants[msg.sender].streak + 1; } } } coins += coinStock[msg.sender]; } /** * Get opponent status */ function getOpponentStatus() view public registered returns(address addr, uint index, uint8 status, uint timestamp, uint8 handShape, uint streak, uint phase) { uint self = participants[msg.sender].current; index = getOpponent(self); addr = queue[index].addr; status = uint8(queue[index].status); timestamp = queue[index].timestamp; streak = participants[queue[index].addr].streak; phase = participants[queue[index].addr].phase; // You can obtain opponent hand shape when disclosed own hand shape handShape = uint8((queue[self].status >= MatchStatus.Disclosed) ? queue[index].handShape : HandShape.Undefined); } }
Calc opponent index/
function calcOpponentIndex(uint _index) pure private returns(uint) { return (_index & ~uint(1)) + ((_index + 1) & uint(1)); }
12,772,590
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IReign.sol"; import "../libraries/LibRewardsDistribution.sol"; contract GovRewards { // lib using SafeMath for uint256; using SafeMath for uint128; // state variables address private _rewardsVault; // contracts IERC20 private _reignToken; IReign private _reign; mapping(uint128 => uint256) private _sizeAtEpoch; mapping(uint128 => uint256) private _epochInitTime; mapping(address => uint128) private lastEpochIdHarvested; uint256 public epochDuration; // init from reignDiamond contract uint256 public epochStart; // init from reignDiamond contract uint128 public lastInitializedEpoch; // events event MassHarvest( address indexed user, uint256 epochsHarvested, uint256 totalValue ); event Harvest( address indexed user, uint128 indexed epochId, uint256 amount ); event InitEpoch(address indexed caller, uint128 indexed epochId); // constructor constructor( address reignTokenAddress, address reign, address rewardsVault ) { _reignToken = IERC20(reignTokenAddress); _reign = IReign(reign); _rewardsVault = rewardsVault; } //before this the epoch start date is 0 function initialize() public { require(epochStart == 0, "Can only be initialized once"); epochDuration = _reign.getEpochDuration(); epochStart = _reign.getEpoch1Start(); } // public method to harvest all the unharvested epochs until current epoch - 1 function massHarvest() external returns (uint256) { uint256 totalDistributedValue; uint256 epochId = _getEpochId().sub(1); // fails in epoch 0 for ( uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++ ) { // i = epochId // compute distributed Value and do one single transfer at the end uint256 userRewards = _harvest(i); totalDistributedValue = totalDistributedValue.add(userRewards); } emit MassHarvest( msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue ); _reignToken.transferFrom( _rewardsVault, msg.sender, totalDistributedValue ); return totalDistributedValue; } //gets the rewards for a single epoch function harvest(uint128 epochId) external returns (uint256) { // checks for requested epoch require(_getEpochId() > epochId, "This epoch is in the future"); require( lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order" ); // get amount to transfer and transfer it uint256 userReward = _harvest(epochId); if (userReward > 0) { _reignToken.transferFrom(_rewardsVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; } /* * internal methods */ function _harvest(uint128 epochId) internal returns (uint256) { // try to initialize an epoch if (lastInitializedEpoch < epochId) { _initEpoch(epochId); } // Set user state for last harvested lastEpochIdHarvested[msg.sender] = epochId; // exit if there is no stake on the epoch if (_sizeAtEpoch[epochId] == 0) { return 0; } // compute and return user total reward. // For optimization reasons the transfer have been moved to an upper layer // (i.e. massHarvest needs to do a single transfer) uint256 epochRewards = getRewardsForEpoch(); uint256 boostMultiplier = getBoost(msg.sender, epochId); uint256 userEpochRewards = epochRewards .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .mul(boostMultiplier) .div(_sizeAtEpoch[epochId]) .div(1 * 10**18); // apply boost multiplier return userEpochRewards; } function _initEpoch(uint128 epochId) internal { require( lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order" ); lastInitializedEpoch = epochId; _epochInitTime[epochId] = block.timestamp; // call the staking smart contract to init the epoch _sizeAtEpoch[epochId] = _getPoolSizeAtTs(block.timestamp); emit InitEpoch(msg.sender, epochId); } /* * VIEWS */ //returns the current epoch function getCurrentEpoch() external view returns (uint256) { return _getEpochId(); } // gets the total amount of rewards accrued to a pool during an epoch function getRewardsForEpoch() public view returns (uint256) { return LibRewardsDistribution.rewardsPerEpochStaking(epochStart); } // calls to the staking smart contract to retrieve user balance for an epoch function getEpochStake(address userAddress, uint128 epochId) external view returns (uint256) { return _getUserBalancePerEpoch(userAddress, epochId); } function userLastEpochIdHarvested() external view returns (uint256) { return lastEpochIdHarvested[msg.sender]; } // calls to the staking smart contract to retrieve the epoch total poolLP size function getPoolSizeAtTs(uint256 timestamp) external view returns (uint256) { return _getPoolSizeAtTs(timestamp); } // calls to the staking smart contract to retrieve the epoch total poolLP size function getPoolSize(uint128 epochId) external view returns (uint256) { return _sizeAtEpoch[epochId]; } // checks if the user has voted that epoch and returns accordingly function getBoost(address user, uint128 epoch) public view returns (uint256) { return _reign.stakingBoostAtEpoch(user, epoch); } // get how many rewards the user gets for an epoch function getUserRewardsForEpoch(uint128 epochId) public view returns (uint256) { // exit if there is no stake on the epoch if (_sizeAtEpoch[epochId] == 0) { return 0; } uint256 epochRewards = getRewardsForEpoch(); uint256 boostMultiplier = getBoost(msg.sender, epochId); uint256 userEpochRewards = epochRewards .mul(_getUserBalancePerEpoch(msg.sender, epochId)) .mul(boostMultiplier) .div(_sizeAtEpoch[epochId]) .div(1 * 10**18); // apply boost multiplier return userEpochRewards; } function _getPoolSizeAtTs(uint256 timestamp) internal view returns (uint256) { // retrieve unilp token balance return _reign.reignStakedAtTs(timestamp); } function _getUserBalancePerEpoch(address userAddress, uint128 epochId) internal view returns (uint256) { // retrieve unilp token balance per user per epoch return _reign.getEpochUserBalance(userAddress, epochId); } // compute epoch id from blocktimestamp and function _getEpochId() internal view returns (uint128 epochId) { if (block.timestamp < epochStart) { return 0; } epochId = uint128( block.timestamp.sub(epochStart).div(epochDuration).add(1) ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "../libraries/LibReignStorage.sol"; interface IReign { function BASE_MULTIPLIER() external view returns (uint256); // deposit allows a user to add more bond to his staked balance function deposit(uint256 amount) external; // withdraw allows a user to withdraw funds if the balance is not locked function withdraw(uint256 amount) external; // lock a user's currently staked balance until timestamp & add the bonus to his voting power function lock(uint256 timestamp) external; // delegate allows a user to delegate his voting power to another user function delegate(address to) external; // stopDelegate allows a user to take back the delegated voting power function stopDelegate() external; // lock the balance of a proposal creator until the voting ends; only callable by DAO function lockCreatorBalance(address user, uint256 timestamp) external; // balanceOf returns the current BOND balance of a user (bonus not included) function balanceOf(address user) external view returns (uint256); // balanceAtTs returns the amount of BOND that the user currently staked (bonus NOT included) function balanceAtTs(address user, uint256 timestamp) external view returns (uint256); // stakeAtTs returns the Stake object of the user that was valid at `timestamp` function stakeAtTs(address user, uint256 timestamp) external view returns (LibReignStorage.Stake memory); // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block function votingPower(address user) external view returns (uint256); // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // bondStaked returns the total raw amount of BOND staked at the current block function reignStaked() external view returns (uint256); // reignStakedAtTs returns the total raw amount of BOND users have deposited into the contract // it does not include any bonus function reignStakedAtTs(uint256 timestamp) external view returns (uint256); // delegatedPower returns the total voting power that a user received from other users function delegatedPower(address user) external view returns (uint256); // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time function delegatedPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // stakingBoost calculates the multiplier on the user's stake at the current timestamp function stakingBoost(address user) external view returns (uint256); // stackingBoostAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp function stackingBoostAtTs(address user, uint256 timestamp) external view returns (uint256); // userLockedUntil returns the timestamp until the user's balance is locked function userLockedUntil(address user) external view returns (uint256); // userDidDelegate returns the address to which a user delegated their voting power; address(0) if not delegated function userDelegatedTo(address user) external view returns (address); // returns the last timestamp in which the user intercated with the staking contarct function userLastAction(address user) external view returns (uint256); // reignCirculatingSupply returns the current circulating supply of BOND function reignCirculatingSupply() external view returns (uint256); function getEpochDuration() external view returns (uint256); function getEpoch1Start() external view returns (uint256); function getCurrentEpoch() external view returns (uint128); function stakingBoostAtEpoch(address, uint128) external view returns (uint256); function getEpochUserBalance(address, uint128) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; library LibRewardsDistribution { using SafeMath for uint256; uint256 public constant TOTAL_REIGN_SUPPLY = 1_000_000_000 * 10**18; uint256 public constant WRAPPING_TOKENS = 500_000_000 * 10**18; uint256 public constant TEAM = 140_000_000 * 10**18; uint256 public constant TREASURY_SALE = 120_000_000 * 10**18; uint256 public constant STAKING_TOKENS = 100_000_000 * 10**18; uint256 public constant TREASURY = 50_000_000 * 10**18; uint256 public constant DEV_FUND = 50_000_000 * 10**18; uint256 public constant LP_REWARDS_TOKENS = 40_000_000 * 10**18; uint256 public constant HALVING_PERIOD = 62899200; // 104 Weeks in Seconds uint256 public constant EPOCHS_IN_PERIOD = 104; // Weeks in 2 years uint256 public constant BLOCKS_IN_PERIOD = 2300000 * 2; uint256 public constant BLOCKS_IN_EPOCH = 44230; uint256 public constant TOTAL_ALLOCATION = 1000000000; /* * WRAPPING */ function wrappingRewardsPerEpochTotal(uint256 epoch1start) internal view returns (uint256) { return wrappingRewardsPerPeriodTotal(epoch1start) / EPOCHS_IN_PERIOD; } function wrappingRewardsPerPeriodTotal(uint256 epoch1start) internal view returns (uint256) { uint256 _timeElapsed = (block.timestamp.sub(epoch1start)); uint256 _periodNr = (_timeElapsed / HALVING_PERIOD).add(1); // this creates the 2 year step function return WRAPPING_TOKENS.div(2 * _periodNr); } /* * GOV STAKING */ function rewardsPerEpochStaking(uint256 epoch1start) internal view returns (uint256) { return stakingRewardsPerPeriodTotal(epoch1start) / EPOCHS_IN_PERIOD; } function stakingRewardsPerPeriodTotal(uint256 epoch1start) internal view returns (uint256) { if (epoch1start > block.timestamp) { return 0; } uint256 _timeElapsed = (block.timestamp.sub(epoch1start)); uint256 _periodNr = (_timeElapsed / HALVING_PERIOD).add(1); // this creates the 2 year step function return STAKING_TOKENS.div(2 * _periodNr); } /* * LP REWARDS */ function rewardsPerEpochLPRewards(uint256 totalAmount, uint256 nrOfEpochs) internal view returns (uint256) { return totalAmount / nrOfEpochs; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library LibReignStorage { bytes32 constant STORAGE_POSITION = keccak256("org.sovreign.reign.storage"); struct Checkpoint { uint256 timestamp; uint256 amount; } struct EpochBalance { uint128 epochId; uint128 multiplier; uint256 startBalance; uint256 newDeposits; } struct Stake { uint256 timestamp; uint256 amount; uint256 expiryTimestamp; address delegatedTo; uint256 stakingBoost; } struct Storage { bool initialized; // mapping of user address to history of Stake objects // every user action creates a new object in the history mapping(address => Stake[]) userStakeHistory; mapping(address => EpochBalance[]) userBalanceHistory; mapping(address => uint128) lastWithdrawEpochId; // array of reign staked Checkpoint // deposits/withdrawals create a new object in the history (max one per block) Checkpoint[] reignStakedHistory; // mapping of user address to history of delegated power // every delegate/stopDelegate call create a new checkpoint (max one per block) mapping(address => Checkpoint[]) delegatedPowerHistory; IERC20 reign; // the reign Token uint256 epoch1Start; uint256 epochDuration; } function reignStorage() internal pure returns (Storage storage ds) { bytes32 position = STORAGE_POSITION; assembly { ds.slot := position } } }
gets the rewards for a single epoch checks for requested epoch get amount to transfer and transfer it
function harvest(uint128 epochId) external returns (uint256) { require(_getEpochId() > epochId, "This epoch is in the future"); require( lastEpochIdHarvested[msg.sender].add(1) == epochId, "Harvest in order" ); uint256 userReward = _harvest(epochId); if (userReward > 0) { _reignToken.transferFrom(_rewardsVault, msg.sender, userReward); } emit Harvest(msg.sender, epochId, userReward); return userReward; }
11,959,586
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IHyperswapRouter.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IUniswapV2Router.sol"; import "./interfaces/IVault.sol"; import "./lib/TransferHelper.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Zapper is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ // @NATIVE - native token that is not a part of our zap-in LP address private NATIVE; struct LiquidityPair { address _token0; address _token1; uint256 _amountToken0; uint256 _amountToken1; uint256 _liqTokenAmt; } struct FunctionArgs { address _LP; address _in; address _out; address _recipient; address _routerAddr; address _token; uint256 _amount; uint256 _otherAmt; uint256 _swapAmt; } mapping(address => mapping(address => address)) private tokenBridgeForRouter; mapping (address => bool) public useNativeRouter; modifier whitelist(address route) { require(useNativeRouter[route], "route not allowed"); _; } // Based address here constructor(address _NATIVE) Ownable() { NATIVE = _NATIVE; } /* ========== External Functions ========== */ receive() external payable {} function NativeToken() public view returns (address) { return NATIVE; } // @_in - Token we want to throw in // @amount - amount of our _in // @out - address of LP we are going to get // @minAmountOfLp - will be calculated on UI including slippage set by user function zapInToken(address _in, uint256 amount, address out, address routerAddr, address recipient, uint256 minAmountOfLp) external whitelist(routerAddr) { // From an ERC20 to an LP token, through specified router, going through base asset if necessary IERC20(_in).safeTransferFrom(msg.sender, address(this), amount); // we'll need this approval to add liquidity _approveTokenIfNeeded(_in, routerAddr); uint256 amountOfLp = _swapTokenToLP(_in, amount, out, recipient, routerAddr); // add require after actual actioin of all functions - will revert lp creation if doesnt meet requirement require(amountOfLp >= minAmountOfLp, "lp amount too small"); } // @_in - Token we want to throw in // @amount - amount of our _in // @out - address of LP we are going to get function estimateZapInToken(address _in, address out, address router, uint256 amount) public view whitelist(router) returns (uint256, uint256) { // get pairs for desired lp // check if we already have one of the assets if (_in == IUniswapV2Pair(out).token0() || _in == IUniswapV2Pair(out).token1()) { // if so, we're going to sell half of in for the other token we need // figure out which token we need, and approve address other = _in == IUniswapV2Pair(out).token0() ? IUniswapV2Pair(out).token1() : IUniswapV2Pair(out).token0(); // calculate amount of in to sell uint256 sellAmount = amount.div(2); // calculate amount of other token for potential lp uint256 otherAmount = _estimateSwap(_in, sellAmount, other, router); if (_in == IUniswapV2Pair(out).token0()) { return (sellAmount, otherAmount); } else { return (otherAmount, sellAmount); } } else { // go through native token, that's not in our LP, for highest liquidity uint256 nativeAmount = _in == NATIVE ? amount : _estimateSwap(_in, amount, NATIVE, router); return estimateZapIn(out, router, nativeAmount); } } function estimateZapIn(address LP, address router, uint256 amount) public view whitelist(router) returns (uint256, uint256) { uint256 zapAmount = amount.div(2); IUniswapV2Pair pair = IUniswapV2Pair(LP); address token0 = pair.token0(); address token1 = pair.token1(); if (token0 == NATIVE || token1 == NATIVE) { address token = token0 == NATIVE ? token1 : token0; uint256 tokenAmount = _estimateSwap(NATIVE, zapAmount, token, router); if (token0 == NATIVE) { return (zapAmount, tokenAmount); } else { return (tokenAmount, zapAmount); } } else { uint256 amountToken0 = _estimateSwap(NATIVE, zapAmount, token0, router); uint256 amountToken1 = _estimateSwap(NATIVE, zapAmount, token1, router); return (amountToken0, amountToken1); } } // from Native to an LP token through the specified router // @ out - LP we want to get out of this // @ minAmountOfLp will be calculated on UI using estimate function and passed into this function function nativeZapIn(uint256 amount, address out, address routerAddr, address recipient, uint256 minAmountOfLp) external whitelist (routerAddr) { IERC20(NATIVE).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(NATIVE, routerAddr); uint256 amountOfLp = _swapNativeToLP(out, amount, recipient, routerAddr); require(amountOfLp >= minAmountOfLp); } // @ _fromLP - LP we want to throw in // @ _to - token we want to get out of our LP // @ minAmountToken0, minAmountToken1 - coming from UI (min amount of tokens coming from breaking our LP) function estimateZapOutToken(address _fromLp, address _to, address _router, uint256 minAmountToken0, uint256 minAmountToken1 ) public view whitelist(_router) returns (uint256) { address token0 = IUniswapV2Pair(_fromLp).token0(); address token1 = IUniswapV2Pair(_fromLp).token1(); if(_to == NATIVE) { if(token0 == NATIVE) { return _estimateSwap(token1, minAmountToken1, _to, _router).add(minAmountToken0); } else { return _estimateSwap(token0, minAmountToken0, _to, _router).add(minAmountToken1); } } if(token0 == NATIVE) { if(_to == token1) { return _estimateSwap(token0, minAmountToken0, _to, _router).add(minAmountToken1); } else { uint256 halfAmountof_to = _estimateSwap(token0, minAmountToken0, _to, _router); uint256 otherhalfAmountof_to = _estimateSwap(token1, minAmountToken1, _to, _router); return (halfAmountof_to.add(otherhalfAmountof_to)); } } else { if (_to == token0) { return _estimateSwap(token1, minAmountToken1, _to, _router).add(minAmountToken0); } else { uint256 halfAmountof_to = _estimateSwap(token0, minAmountToken0, _to, _router); uint256 otherhalfAmountof_to = _estimateSwap(token1, minAmountToken1, _to, _router); return halfAmountof_to.add(otherhalfAmountof_to); } } } // from an LP token to Native through specified router // @in - LP we want to throw in // @amount - amount of our LP function zapOutToNative(address _in, uint256 amount, address routerAddr, address recipient, uint256 minAmountNative) external whitelist(routerAddr) { // take the LP token IERC20(_in).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_in, routerAddr); LiquidityPair memory pair; // get pairs for LP pair._token0 = IUniswapV2Pair(_in).token0(); pair._token1 = IUniswapV2Pair(_in).token1(); _approveTokenIfNeeded(pair._token0, routerAddr); _approveTokenIfNeeded(pair._token1, routerAddr); (pair._amountToken0, pair._amountToken1) = IUniswapV2Router(routerAddr).removeLiquidity(pair._token0, pair._token1, amount, 0, 0, address(this), block.timestamp); if (pair._token0 != NATIVE) { pair._amountToken0 = _swapTokenForNative(pair._token0, pair._amountToken0, address(this), routerAddr); } if (pair._token1 != NATIVE) { pair._amountToken1 = _swapTokenForNative(pair._token1, pair._amountToken1, address(this), routerAddr); } require (pair._amountToken0.add(pair._amountToken1) >= minAmountNative, "token amt < minAmountNative"); IERC20(NATIVE).safeTransfer(recipient, pair._amountToken0.add(pair._amountToken1)); } // from an LP token to an ERC20 through specified router // from an LP token to Native through specified router // @in - LP we want to throw in // @amount - amount of our LP // @out - token we want to get function zapOutToToken(address _in, uint256 amount, address out, address routerAddr, address recipient, uint256 minAmountToken) whitelist(routerAddr) external { FunctionArgs memory args; LiquidityPair memory pair; args._amount = amount; args._out = out; args._recipient = recipient; args._routerAddr = routerAddr; args._in = _in; IERC20(args._in).safeTransferFrom(msg.sender, address(this), args._amount); _approveTokenIfNeeded(args._in, args._routerAddr); pair._token0 = IUniswapV2Pair(args._in).token0(); pair._token1 = IUniswapV2Pair(args._in).token1(); _approveTokenIfNeeded(pair._token0, args._routerAddr); _approveTokenIfNeeded(pair._token1, args._routerAddr); (pair._amountToken0, pair._amountToken1) = IUniswapV2Router(args._routerAddr).removeLiquidity(pair._token0, pair._token1, args._amount, 0, 0, address(this), block.timestamp); if (pair._token0 != args._out) { pair._amountToken0 = _swap(pair._token0, pair._amountToken0, args._out, address(this), args._routerAddr); } if (pair._token1 != args._out) { pair._amountToken1 = _swap(pair._token1, pair._amountToken1, args._out, address(this), args._routerAddr); } require (pair._amountToken0.add(pair._amountToken1) >= minAmountToken, "amt < minAmountToken"); IERC20(args._out).safeTransfer(args._recipient, pair._amountToken0.add(pair._amountToken1)); } // @_in - token we want to throw in // @amount - amount of our _in // @out - token we want to get out function _swap(address _in, uint256 amount, address out, address recipient, address routerAddr) public whitelist(routerAddr) returns (uint256) { IUniswapV2Router router = IUniswapV2Router(routerAddr); address fromBridge = tokenBridgeForRouter[_in][routerAddr]; address toBridge = tokenBridgeForRouter[out][routerAddr]; address[] memory path; if (fromBridge != address(0) && toBridge != address(0)) { if (fromBridge != toBridge) { path = new address[](5); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; path[3] = toBridge; path[4] = out; } else { path = new address[](3); path[0] = _in; path[1] = fromBridge; path[2] = out; } } else if (fromBridge != address(0)) { if (out == NATIVE) { path = new address[](3); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; } else { path = new address[](4); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; path[3] = out; } } else if (toBridge != address(0)) { path = new address[](4); path[0] = _in; path[1] = NATIVE; path[2] = toBridge; path[3] = out; } else if (_in == NATIVE || out == NATIVE) { path = new address[](2); path[0] = _in; path[1] = out; } else { // Go through Native path = new address[](3); path[0] = _in; path[1] = NATIVE; path[2] = out; } uint256 tokenAmountEst = _estimateSwap(_in, amount, out, routerAddr); uint256[] memory amounts = router.swapExactTokensForTokens(amount, tokenAmountEst, path, recipient, block.timestamp); require(amounts[amounts.length-1] >= tokenAmountEst, "amount smaller than estimate"); return amounts[amounts.length - 1]; } // @_in - token we want to throw in // @amount - amount of our _in // @out - token we want to get out function _estimateSwap(address _in, uint256 amount, address out, address routerAddr) public view whitelist(routerAddr) returns (uint256) { IUniswapV2Router router = IUniswapV2Router(routerAddr); address fromBridge = tokenBridgeForRouter[_in][routerAddr]; address toBridge = tokenBridgeForRouter[out][routerAddr]; address[] memory path; if (fromBridge != address(0) && toBridge != address(0)) { if (fromBridge != toBridge) { path = new address[](5); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; path[3] = toBridge; path[4] = out; } else { path = new address[](3); path[0] = _in; path[1] = fromBridge; path[2] = out; } } else if (fromBridge != address(0)) { if (out == NATIVE) { path = new address[](3); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; } else { path = new address[](4); path[0] = _in; path[1] = fromBridge; path[2] = NATIVE; path[3] = out; } } else if (toBridge != address(0)) { path = new address[](4); path[0] = _in; path[1] = NATIVE; path[2] = toBridge; path[3] = out; } else if (_in == NATIVE || out == NATIVE) { path = new address[](2); path[0] = _in; path[1] = out; } else { // Go through Native path = new address[](3); path[0] = _in; path[1] = NATIVE; path[2] = out; } uint256[] memory amounts = router.getAmountsOut(amount, path); return amounts[amounts.length - 1]; } /* ========== Private Functions ========== */ function _approveTokenIfNeeded(address token, address router) private { if (IERC20(token).allowance(address(this), router) == 0) { IERC20(token).safeApprove(router, type(uint256).max); } } function _swapTokenToLP(address _in, uint256 amount, address out, address recipient, address routerAddr) private returns (uint256) { FunctionArgs memory args; args._in = _in; args._amount = amount; args._out = out; args._recipient = recipient; args._routerAddr = routerAddr; LiquidityPair memory pair; if (args._in == IUniswapV2Pair(args._out).token0() || args._in == IUniswapV2Pair(args._out).token1()) { args._token = args._in == IUniswapV2Pair(args._out).token0() ? IUniswapV2Pair(args._out).token1() : IUniswapV2Pair(args._out).token0(); // calculate args._amount of _in to sell args._swapAmt = args._amount.div(2); args._otherAmt = _swap(args._in, args._swapAmt, args._token, address(this), args._routerAddr); _approveTokenIfNeeded(args._token, args._routerAddr); // execute swap (pair._amountToken0 , pair._amountToken1 , pair._liqTokenAmt) = IUniswapV2Router(args._routerAddr).addLiquidity( args._in, args._token, args._amount.sub(args._swapAmt), args._otherAmt, args._swapAmt , args._otherAmt, args._recipient, block.timestamp); if (args._in == IUniswapV2Pair(args._out).token0()) { _dustDistribution( args._swapAmt, args._otherAmt, pair._amountToken0, pair._amountToken1, args._in, args._token, args._recipient); } else { _dustDistribution( args._otherAmt, args._swapAmt, pair._amountToken1, pair._amountToken0, args._in, args._token, args._recipient); } return pair._liqTokenAmt; } else { // go through native token for highest liquidity uint256 nativeAmount = _swapTokenForNative(args._in, args._amount, address(this), args._routerAddr); return _swapNativeToLP(args._out, nativeAmount, args._recipient, args._routerAddr); } } // @amount - amount of our native token // @out - LP we want to get function _swapNativeToLP(address out, uint256 amount, address recipient, address routerAddress) private returns (uint256) { IUniswapV2Pair pair = IUniswapV2Pair(out); address token0 = pair.token0(); address token1 = pair.token1(); uint256 liquidity; liquidity = _swapNativeToEqualTokensAndProvide(token0, token1, amount, routerAddress, recipient); return liquidity; } function _dustDistribution(uint256 token0, uint256 token1, uint256 amountToken0, uint256 amountToken1, address native, address token, address recipient) private { uint256 nativeDust = token0.sub(amountToken0); uint256 tokenDust = token1.sub(amountToken1); if (nativeDust > 0) { IERC20(native).safeTransfer(recipient, nativeDust); } if (tokenDust > 0) { IERC20(token).safeTransfer(recipient, tokenDust); } } // @token0 - swap Native to this , and provide this to create LP // @token1 - swap Native to this , and provide this to create LP // @amount - amount of native token function _swapNativeToEqualTokensAndProvide(address token0, address token1, uint256 amount, address routerAddress, address recipient) private returns (uint256) { FunctionArgs memory args; args._amount = amount; args._recipient = recipient; args._routerAddr = routerAddress; args._swapAmt = args._amount.div(2); LiquidityPair memory pair; pair._token0 = token0; pair._token1 = token1; IUniswapV2Router router = IUniswapV2Router(args._routerAddr); if (pair._token0 == NATIVE) { args._otherAmt= _swapNativeForToken(pair._token1, args._swapAmt, address(this), args._routerAddr); _approveTokenIfNeeded(pair._token0, args._routerAddr); _approveTokenIfNeeded(pair._token1, args._routerAddr); (pair._amountToken0, pair._amountToken1, pair._liqTokenAmt) = router.addLiquidity( pair._token0, pair._token1, args._swapAmt, args._otherAmt, args._swapAmt, args._otherAmt, args._recipient, block.timestamp); _dustDistribution( args._swapAmt, args._otherAmt, pair._amountToken0, pair._amountToken1, pair._token0, pair._token1, args._recipient); return pair._liqTokenAmt; } else { args._otherAmt = _swapNativeForToken(pair._token0, args._swapAmt, address(this), args._routerAddr); _approveTokenIfNeeded( pair._token0, args._routerAddr); _approveTokenIfNeeded( pair._token1, args._routerAddr); (pair._amountToken0, pair._amountToken1, pair._liqTokenAmt) = router.addLiquidity(pair._token0, pair._token1, args._otherAmt, args._swapAmt, args._otherAmt, args._swapAmt, args._recipient, block.timestamp); _dustDistribution( args._otherAmt, args._swapAmt, pair._amountToken1, pair._amountToken0, pair._token1, pair._token0, args._recipient); return pair._liqTokenAmt; } } // @token - swap Native to this token // @amount - amount of native token function _swapNativeForToken(address token, uint256 amount, address recipient, address routerAddr) private returns (uint256) { address[] memory path; IUniswapV2Router router = IUniswapV2Router(routerAddr); if (tokenBridgeForRouter[token][routerAddr] != address(0)) { path = new address[](3); path[0] = NATIVE; path[1] = tokenBridgeForRouter[token][routerAddr]; path[2] = token; } else { path = new address[](2); path[0] = NATIVE; path[1] = token; } uint256 tokenAmt = _estimateSwap(NATIVE, amount, token, routerAddr); uint256[] memory amounts = router.swapExactTokensForTokens(amount, tokenAmt, path, recipient, block.timestamp); return amounts[amounts.length - 1]; } // @token - swap this token to Native // @amount - amount of native token function _swapTokenForNative(address token, uint256 amount, address recipient, address routerAddr) private returns (uint256) { address[] memory path; IUniswapV2Router router = IUniswapV2Router(routerAddr); if (tokenBridgeForRouter[token][routerAddr] != address(0)) { path = new address[](3); path[0] = token; path[1] = tokenBridgeForRouter[token][routerAddr]; path[2] = NATIVE; } else { path = new address[](2); path[0] = token; path[1] = NATIVE; } uint256 tokenAmt = _estimateSwap(token, amount, NATIVE, routerAddr); uint256[] memory amounts = router.swapExactTokensForTokens(amount, tokenAmt, path, recipient, block.timestamp); return amounts[amounts.length - 1]; } // @in - token we want to throw in // @amount - amount of our token // @out - token we want to get function swapToken(address _in, uint256 amount, address out, address routerAddr, address _recipient, uint256 minAmountOut) private { IERC20(_in).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_in, routerAddr); uint256 tokensOut = _swap(_in, amount, out, _recipient, routerAddr); require (tokensOut >= minAmountOut); } // @in - token we want to throw in // @amount - amount of our token function swapToNative(address _in, uint256 amount, address routerAddr, address _recipient, uint256 minAmountOut) private { IERC20(_in).safeTransferFrom(msg.sender, address(this), amount); _approveTokenIfNeeded(_in, routerAddr); uint256 amountNative = _swapTokenForNative(_in, amount, _recipient, routerAddr); require (amountNative >= minAmountOut); } /* ========== RESTRICTED FUNCTIONS ========== */ function setNativeToken(address _NATIVE) external onlyOwner { NATIVE = _NATIVE; } function setTokenBridgeForRouter(address token, address router, address bridgeToken) external onlyOwner { tokenBridgeForRouter[token][router] = bridgeToken; } function withdraw(address token) external onlyOwner { if (token == address(0)) { payable(owner()).transfer(address(this).balance); return; } IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))); } function setUseNativeRouter(address router) external onlyOwner { useNativeRouter[router] = true; } function removeNativeRouter(address router) external onlyOwner { useNativeRouter[router] = false; } }
@amount - amount of our native token @out - LP we want to get
function _swapNativeToLP(address out, uint256 amount, address recipient, address routerAddress) private returns (uint256) { IUniswapV2Pair pair = IUniswapV2Pair(out); address token0 = pair.token0(); address token1 = pair.token1(); uint256 liquidity; liquidity = _swapNativeToEqualTokensAndProvide(token0, token1, amount, routerAddress, recipient); return liquidity; }
12,639,305
/** *Submitted for verification at Etherscan.io on 2020-10-21 */ // SPDX-License-Identifier: MIT pragma solidity ^0.6.6; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "::SafeMath: addition overflow"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "::SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "::SafeMath: multiplication overflow"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { 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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } interface Governance { function proposeJob(address job) external returns (uint); } interface WETH9 { function deposit() external payable; function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); } interface Uniswap { function factory() 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); } interface UniswapPair { function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function balanceOf(address account) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function totalSupply() external view returns (uint); } interface Factory { function getPair(address tokenA, address tokenB) external view returns (address pair); } interface Keep3rHelper { function getQuoteLimit(uint gasUsed) external view returns (uint); } interface ERC20 { function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function balanceOf(address account) external view returns (uint); } contract Keep3r { using SafeMath for uint; /// @notice Keep3r Helper to set max prices for the ecosystem Keep3rHelper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "Keep3r"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KPR"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint 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 => uint)) internal allowances; mapping (address => uint) 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)"); /// @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 => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "::delegateBySig: invalid nonce"); require(now <= expiry, "::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = bonds[delegator][address(this)]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 7 days maximum downtime before being slashed uint constant public DOWNTIME = 7 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice 5% of funds slashed for downtime uint constant public DOWNTIMESLASH = 500; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the amount of job executions for a keeper mapping(address => uint) public work; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor() public { // Set governance for this token governance = msg.sender; _mint(msg.sender, 10000e18); } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "::addCreditETH: not a valid job"); credits[job][ETH] = credits[job][ETH].add(msg.value); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external { require(jobs[job], "::addCreditETH: not a valid job"); uint _before = ERC20(credit).balanceOf(address(this)); ERC20(credit).transferFrom(msg.sender, address(this), amount); uint _after = ERC20(credit).balanceOf(address(this)); credits[job][credit] = credits[job][credit].add(_after.sub(_before)); emit AddCredit(credit, job, msg.sender, block.number, _after.sub(_before)); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "::approveLiquidity: governance only"); require(!liquidityAccepted[liquidity], "::approveLiquidity: existing liquidity pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "::revokeLiquidity: governance only"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external { require(liquidityAccepted[liquidity], "::addLiquidityToJob: asset not accepted as liquidity"); UniswapPair(liquidity).transferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { Governance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "::addLiquidityToJob: asset not accepted as liquidity"); require(liquidityApplied[provider][liquidity][job] != 0, "::credit: submitJob first"); require(liquidityApplied[provider][liquidity][job] < now, "::credit: still bonding"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(liquidityAmount[msg.sender][liquidity][job]).div(UniswapPair(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[msg.sender][liquidity][job] = 0; emit ApplyCredit(job, msg.sender, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "::credit: pending credit, settle first"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "::unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "::removeJob: unbond first"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "::removeJob: still unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; UniswapPair(liquidity).transfer(msg.sender, _amount); emit RemoveJob(job, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external { require(msg.sender == governance, "::mint: governance only"); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // 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); } function _burn(address dst, uint amount) internal { require(dst != address(0), "::_burn: burn from the zero address"); balances[dst] = balances[dst].sub(amount, "::_burn: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "::workReceipt: only jobs can approve work"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "::workReceipt: spending over max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "::workReceipt: insuffient funds to pay keeper"); lastJob[keeper] = now; _bond(address(this), keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "::receipt: only jobs can approve work"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "::workReceipt: insuffient funds to pay keeper"); lastJob[keeper] = now; ERC20(credit).transfer(msg.sender, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) external { require(jobs[msg.sender], "::receipt: only jobs can approve work"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "::workReceipt: insuffient funds to pay keeper"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); totalBonded = totalBonded.add(_amount); if (_from == address(this)) { _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); totalBonded = totalBonded.sub(_amount); if (bonding == address(this)) { _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "::addJob: only governance can add jobs"); require(!jobs[job], "::addJob: job already known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "::removeJob: only governance can remove jobs"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(Keep3rHelper _kprh) external { require(msg.sender == governance, "::setKeep3rHelper: only governance can set"); KPRH = _kprh; } /** * @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: only governance can set"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "::acceptGovernance: only pendingGovernance can accept"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external { require(pendingbonds[msg.sender][bonding] == 0, "::bond: current pending bond"); require(!blacklist[msg.sender], "::bond: keeper is blacklisted"); bondings[msg.sender][bonding] = now.add(BOND); if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { ERC20(bonding).transferFrom(msg.sender, address(this), amount); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "::activate: keeper is blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "::activate: still bonding"); if (firstSeen[msg.sender] == 0) { firstSeen[msg.sender] = now; keeperList.push(msg.sender); lastJob[msg.sender] = now; } keepers[msg.sender] = true; _bond(bonding, msg.sender, pendingbonds[msg.sender][bonding]); pendingbonds[msg.sender][bonding] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender][bonding]); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now.add(UNBOND); _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external { require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "::withdraw: still unbonding"); require(!disputes[msg.sender], "::withdraw: pending disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { ERC20(bonding).transfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice slash a keeper for downtime * @param keeper the address being slashed */ function down(address keeper) external { require(keepers[msg.sender], "::down: not a keeper"); require(keepers[keeper], "::down: keeper not registered"); require(lastJob[keeper].add(DOWNTIME) < now, "::down: keeper safe"); uint _slash = bonds[keeper][address(this)].mul(DOWNTIMESLASH).div(BASE); _unbond(address(this), keeper, _slash); _bond(address(this), msg.sender, _slash); lastJob[keeper] = now; lastJob[msg.sender] = now; emit KeeperSlashed(keeper, msg.sender, block.number, _slash); } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external returns (uint) { require(msg.sender == governance, "::dispute: only governance can dispute"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public { require(msg.sender == governance, "::slash: only governance can resolve"); if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { ERC20(bonded).transfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "::slash: only governance can resolve"); keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "::resolve: only governance can resolve"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public 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, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(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: invalid signature"); require(signatory == owner, "::permit: unauthorized"); require(now <= deadline, "::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public 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, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "::_transferTokens: cannot transfer to the zero address"); balances[src] = balances[src].sub(amount, "::_transferTokens: transfer amount exceeds balance"); balances[dst] = balances[dst].add(amount, "::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Unbond liquidity for a job liquidity the pair being unbound job the job being unbound from amount the amount of liquidity being removed/
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "::credit: pending credit, settle first"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "::unbondLiquidityFromJob: insufficient funds"); uint _liquidity = balances[address(liquidity)]; uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; _burn(address(this), _credit); credits[job][address(this)].sub(_credit); } emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]); }
280,780
pragma solidity >=0.5.3<0.6.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; // Just inlining part of the standard ERC20 contract interface ERC20Token { function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } /** * @title Staking is a contract to support locking and releasing ERC-20 tokens * for the purposes of staking. */ contract Staking { struct PendingDeposit { address depositor; uint256 amount; } address public _owner; address public _authorizedNewOwner; address public _tokenAddress; address public _withdrawalPublisher; address public _fallbackPublisher; uint256 public _fallbackWithdrawalDelaySeconds = 1 weeks; // 1% of total supply uint256 public _immediatelyWithdrawableLimit = 100_000 * (10**18); address public _immediatelyWithdrawableLimitPublisher; uint256 public _depositNonce = 0; mapping(uint256 => PendingDeposit) public _nonceToPendingDeposit; uint256 public _maxWithdrawalRootNonce = 0; mapping(bytes32 => uint256) public _withdrawalRootToNonce; mapping(address => uint256) public _addressToWithdrawalNonce; mapping(address => uint256) public _addressToCumulativeAmountWithdrawn; bytes32 public _fallbackRoot; uint256 public _fallbackMaxDepositIncluded = 0; uint256 public _fallbackSetDate = 2**200; event WithdrawalRootHashAddition( bytes32 indexed rootHash, uint256 indexed nonce ); event WithdrawalRootHashRemoval( bytes32 indexed rootHash, uint256 indexed nonce ); event FallbackRootHashSet( bytes32 indexed rootHash, uint256 indexed maxDepositNonceIncluded, uint256 setDate ); event Deposit( address indexed depositor, uint256 indexed amount, uint256 indexed nonce ); event Withdrawal( address indexed toAddress, uint256 indexed amount, uint256 indexed rootNonce, uint256 authorizedAccountNonce ); event FallbackWithdrawal( address indexed toAddress, uint256 indexed amount ); event PendingDepositRefund( address indexed depositorAddress, uint256 indexed amount, uint256 indexed nonce ); event RenounceWithdrawalAuthorization( address indexed forAddress ); event FallbackWithdrawalDelayUpdate( uint256 indexed oldValue, uint256 indexed newValue ); event FallbackMechanismDateReset( uint256 indexed newDate ); event ImmediatelyWithdrawableLimitUpdate( uint256 indexed oldValue, uint256 indexed newValue ); event OwnershipTransferAuthorization( address indexed authorizedAddress ); event OwnerUpdate( address indexed oldValue, address indexed newValue ); event FallbackPublisherUpdate( address indexed oldValue, address indexed newValue ); event WithdrawalPublisherUpdate( address indexed oldValue, address indexed newValue ); event ImmediatelyWithdrawableLimitPublisherUpdate( address indexed oldValue, address indexed newValue ); constructor( address tokenAddress, address fallbackPublisher, address withdrawalPublisher, address immediatelyWithdrawableLimitPublisher ) public { _owner = msg.sender; _fallbackPublisher = fallbackPublisher; _withdrawalPublisher = withdrawalPublisher; _immediatelyWithdrawableLimitPublisher = immediatelyWithdrawableLimitPublisher; _tokenAddress = tokenAddress; } /******************** * STANDARD ACTIONS * ********************/ /** * @notice Deposits the provided amount of FXC from the message sender into this wallet. * Note: The sending address must own the provided amount of FXC to deposit, and * the sender must have indicated to the FXC ERC-20 contract that this contract is * allowed to transfer at least the provided amount from its address. * * @param amount The amount to deposit. * @return The deposit nonce for this deposit. This can be useful in calling * refundPendingDeposit(...). */ function deposit(uint256 amount) external returns(uint256) { require( amount > 0, "Cannot deposit 0" ); _depositNonce = SafeMath.add(_depositNonce, 1); _nonceToPendingDeposit[_depositNonce].depositor = msg.sender; _nonceToPendingDeposit[_depositNonce].amount = amount; emit Deposit( msg.sender, amount, _depositNonce ); bool transferred = ERC20Token(_tokenAddress).transferFrom( msg.sender, address(this), amount ); require(transferred, "Transfer failed"); return _depositNonce; } /** * @notice Indicates that this address would not like its withdrawable * funds to be available for withdrawal. This will prevent withdrawal * for this address until the next withdrawal root is published. * * Note: The caller does not need to know or prove the details of the current * withdrawal authorization in order to renounce it. * @param forAddress The address for which the withdrawal is being renounced. */ function renounceWithdrawalAuthorization(address forAddress) external { require( msg.sender == _owner || msg.sender == _withdrawalPublisher || msg.sender == forAddress, "Only the owner, withdrawal publisher, and address in question can renounce a withdrawal authorization" ); require( _addressToWithdrawalNonce[forAddress] < _maxWithdrawalRootNonce, "Address nonce indicates there are no funds withdrawable" ); _addressToWithdrawalNonce[forAddress] = _maxWithdrawalRootNonce; emit RenounceWithdrawalAuthorization(forAddress); } /** * @notice Executes a previously authorized token withdrawal. * @param toAddress The address to which the tokens are to be transferred. * @param amount The amount of tokens to be withdrawn. * @param maxAuthorizedAccountNonce The maximum authorized account nonce for the withdrawing * address encoded within the withdrawal authorization. Prevents double-withdrawals. * @param merkleProof The Merkle tree proof associated with the withdrawal * authorization. */ function withdraw( address toAddress, uint256 amount, uint256 maxAuthorizedAccountNonce, bytes32[] calldata merkleProof ) external { require( msg.sender == _owner || msg.sender == toAddress, "Only the owner or recipient can execute a withdrawal" ); require( _addressToWithdrawalNonce[toAddress] <= maxAuthorizedAccountNonce, "Account nonce in contract exceeds provided max authorized withdrawal nonce for this account" ); require( amount <= _immediatelyWithdrawableLimit, "Withdrawal would push contract over its immediately withdrawable limit" ); bytes32 leafDataHash = keccak256(abi.encodePacked( toAddress, amount, maxAuthorizedAccountNonce )); bytes32 calculatedRoot = calculateMerkleRoot(merkleProof, leafDataHash); uint256 withdrawalPermissionRootNonce = _withdrawalRootToNonce[calculatedRoot]; require( withdrawalPermissionRootNonce > 0, "Root hash unauthorized"); require( withdrawalPermissionRootNonce > maxAuthorizedAccountNonce, "Encoded nonce not greater than max last authorized nonce for this account" ); _immediatelyWithdrawableLimit -= amount; // amount guaranteed <= _immediatelyWithdrawableLimit _addressToWithdrawalNonce[toAddress] = withdrawalPermissionRootNonce; _addressToCumulativeAmountWithdrawn[toAddress] = SafeMath.add(amount, _addressToCumulativeAmountWithdrawn[toAddress]); emit Withdrawal( toAddress, amount, withdrawalPermissionRootNonce, maxAuthorizedAccountNonce ); bool transferred = ERC20Token(_tokenAddress).transfer( toAddress, amount ); require(transferred, "Transfer failed"); } /** * @notice Executes a fallback withdrawal transfer. * @param toAddress The address to which the tokens are to be transferred. * @param maxCumulativeAmountWithdrawn The lifetime withdrawal limit that this address is * subject to. This is encoded within the fallback authorization to prevent regular * withdrawal / fallback withdrawal double-spends * @param merkleProof The Merkle tree proof associated with the withdrawal authorization. */ function withdrawFallback( address toAddress, uint256 maxCumulativeAmountWithdrawn, bytes32[] calldata merkleProof ) external { require( msg.sender == _owner || msg.sender == toAddress, "Only the owner or recipient can execute a fallback withdrawal" ); require( SafeMath.add(_fallbackSetDate, _fallbackWithdrawalDelaySeconds) <= block.timestamp, "Fallback withdrawal period is not active" ); require( _addressToCumulativeAmountWithdrawn[toAddress] < maxCumulativeAmountWithdrawn, "Withdrawal not permitted when amount withdrawn is at lifetime withdrawal limit" ); bytes32 msgHash = keccak256(abi.encodePacked( toAddress, maxCumulativeAmountWithdrawn )); bytes32 calculatedRoot = calculateMerkleRoot(merkleProof, msgHash); require( _fallbackRoot == calculatedRoot, "Root hash unauthorized" ); // If user is triggering fallback withdrawal, invalidate all existing regular withdrawals _addressToWithdrawalNonce[toAddress] = _maxWithdrawalRootNonce; // _addressToCumulativeAmountWithdrawn[toAddress] guaranteed < maxCumulativeAmountWithdrawn uint256 withdrawalAmount = maxCumulativeAmountWithdrawn - _addressToCumulativeAmountWithdrawn[toAddress]; _addressToCumulativeAmountWithdrawn[toAddress] = maxCumulativeAmountWithdrawn; emit FallbackWithdrawal( toAddress, withdrawalAmount ); bool transferred = ERC20Token(_tokenAddress).transfer( toAddress, withdrawalAmount ); require(transferred, "Transfer failed"); } /** * @notice Refunds a pending deposit for the provided address, refunding the pending funds. * This may only take place if the fallback withdrawal period has lapsed. * @param depositNonce The deposit nonce uniquely identifying the deposit to cancel */ function refundPendingDeposit(uint256 depositNonce) external { address depositor = _nonceToPendingDeposit[depositNonce].depositor; require( msg.sender == _owner || msg.sender == depositor, "Only the owner or depositor can initiate the refund of a pending deposit" ); require( SafeMath.add(_fallbackSetDate, _fallbackWithdrawalDelaySeconds) <= block.timestamp, "Fallback withdrawal period is not active, so refunds are not permitted" ); uint256 amount = _nonceToPendingDeposit[depositNonce].amount; require( depositNonce > _fallbackMaxDepositIncluded && amount > 0, "There is no pending deposit for the specified nonce" ); delete _nonceToPendingDeposit[depositNonce]; emit PendingDepositRefund(depositor, amount, depositNonce); bool transferred = ERC20Token(_tokenAddress).transfer( depositor, amount ); require(transferred, "Transfer failed"); } /***************** * ADMIN ACTIONS * *****************/ /** * @notice Authorizes the transfer of ownership from _owner to the provided address. * NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). * This authorization may be removed by another call to this function authorizing * the null address. * @param authorizedAddress The address authorized to become the new owner. */ function authorizeOwnershipTransfer(address authorizedAddress) external { require( msg.sender == _owner, "Only the owner can authorize a new address to become owner" ); _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); } /** * @notice Transfers ownership of this contract to the _authorizedNewOwner. */ function assumeOwnership() external { require( msg.sender == _authorizedNewOwner, "Only the authorized new owner can accept ownership" ); address oldValue = _owner; _owner = _authorizedNewOwner; _authorizedNewOwner = address(0); emit OwnerUpdate(oldValue, _owner); } /** * @notice Updates the Withdrawal Publisher address, the only address other than the * owner that can publish / remove withdrawal Merkle tree roots. * @param newWithdrawalPublisher The address of the new Withdrawal Publisher */ function setWithdrawalPublisher(address newWithdrawalPublisher) external { require( msg.sender == _owner, "Only the owner can set the withdrawal publisher address" ); address oldValue = _withdrawalPublisher; _withdrawalPublisher = newWithdrawalPublisher; emit WithdrawalPublisherUpdate(oldValue, _withdrawalPublisher); } /** * @notice Updates the Fallback Publisher address, the only address other than * the owner that can publish / remove fallback withdrawal Merkle tree roots. * @param newFallbackPublisher The address of the new Fallback Publisher */ function setFallbackPublisher(address newFallbackPublisher) external { require( msg.sender == _owner, "Only the owner can set the fallback publisher address" ); address oldValue = _fallbackPublisher; _fallbackPublisher = newFallbackPublisher; emit FallbackPublisherUpdate(oldValue, _fallbackPublisher); } /** * @notice Updates the Immediately Withdrawable Limit Publisher address, the only address * other than the owner that can set the immediately withdrawable limit. * @param newImmediatelyWithdrawableLimitPublisher The address of the new Immediately * Withdrawable Limit Publisher */ function setImmediatelyWithdrawableLimitPublisher( address newImmediatelyWithdrawableLimitPublisher ) external { require( msg.sender == _owner, "Only the owner can set the immediately withdrawable limit publisher address" ); address oldValue = _immediatelyWithdrawableLimitPublisher; _immediatelyWithdrawableLimitPublisher = newImmediatelyWithdrawableLimitPublisher; emit ImmediatelyWithdrawableLimitPublisherUpdate( oldValue, _immediatelyWithdrawableLimitPublisher ); } /** * @notice Modifies the immediately withdrawable limit (the maximum amount that * can be withdrawn from withdrawal authorization roots before the limit needs * to be updated by Flexa) by the provided amount. * If negative, it will be decreased, if positive, increased. * This is to prevent contract funds from being drained by error or publisher malice. * This does not affect the fallback withdrawal mechanism. * @param amount amount to modify the limit by. */ function modifyImmediatelyWithdrawableLimit(int256 amount) external { require( msg.sender == _owner || msg.sender == _immediatelyWithdrawableLimitPublisher, "Only the immediately withdrawable limit publisher and owner can modify the immediately withdrawable limit" ); uint256 oldLimit = _immediatelyWithdrawableLimit; if (amount < 0) { uint256 unsignedAmount = uint256(-amount); _immediatelyWithdrawableLimit = SafeMath.sub(_immediatelyWithdrawableLimit, unsignedAmount); } else { uint256 unsignedAmount = uint256(amount); _immediatelyWithdrawableLimit = SafeMath.add(_immediatelyWithdrawableLimit, unsignedAmount); } emit ImmediatelyWithdrawableLimitUpdate(oldLimit, _immediatelyWithdrawableLimit); } /** * @notice Updates the time-lock period for a fallback withdrawal to be permitted if no * action is taken by Flexa. * @param newFallbackDelaySeconds The new delay period in seconds. */ function setFallbackWithdrawalDelay(uint256 newFallbackDelaySeconds) external { require( msg.sender == _owner, "Only the owner can set the fallback withdrawal delay" ); require( newFallbackDelaySeconds != 0, "New fallback delay may not be 0" ); uint256 oldDelay = _fallbackWithdrawalDelaySeconds; _fallbackWithdrawalDelaySeconds = newFallbackDelaySeconds; emit FallbackWithdrawalDelayUpdate(oldDelay, newFallbackDelaySeconds); } /** * @notice Adds the root hash of a merkle tree containing authorized token withdrawals. * @param root The root hash to be added to the repository. * @param nonce The nonce of the new root hash. Must be exactly one higher * than the existing max nonce. * @param replacedRoots The root hashes to be removed from the repository. */ function addWithdrawalRoot( bytes32 root, uint256 nonce, bytes32[] calldata replacedRoots ) external { require( msg.sender == _owner || msg.sender == _withdrawalPublisher, "Only the owner and withdrawal publisher can add and replace withdrawal root hashes" ); require( root != 0, "Added root may not be 0" ); require( // Overflowing uint256 by incrementing by 1 not plausible and guarded by nonce variable. _maxWithdrawalRootNonce + 1 == nonce, "Nonce must be exactly max nonce + 1" ); require( _withdrawalRootToNonce[root] == 0, "Root already exists and is associated with a different nonce" ); _withdrawalRootToNonce[root] = nonce; _maxWithdrawalRootNonce = nonce; emit WithdrawalRootHashAddition(root, nonce); for (uint256 i = 0; i < replacedRoots.length; i++) { deleteWithdrawalRoot(replacedRoots[i]); } } /** * @notice Removes root hashes of a merkle trees containing authorized * token withdrawals. * @param roots The root hashes to be removed from the repository. */ function removeWithdrawalRoots(bytes32[] calldata roots) external { require( msg.sender == _owner || msg.sender == _withdrawalPublisher, "Only the owner and withdrawal publisher can remove withdrawal root hashes" ); for (uint256 i = 0; i < roots.length; i++) { deleteWithdrawalRoot(roots[i]); } } /** * @notice Resets the _fallbackSetDate to the current block's timestamp. * This is mainly used to deactivate the fallback mechanism so new * fallback roots may be published. */ function resetFallbackMechanismDate() external { require( msg.sender == _owner || msg.sender == _fallbackPublisher, "Only the owner and fallback publisher can reset fallback mechanism date" ); _fallbackSetDate = block.timestamp; emit FallbackMechanismDateReset(_fallbackSetDate); } /** * @notice Sets the root hash of the Merkle tree containing fallback * withdrawal authorizations. This is used in scenarios where the contract * owner has stopped interacting with the contract, and therefore is no * longer honoring requests to unlock funds. After the configured fallback * delay elapses, the withdrawal authorizations included in the supplied * Merkle tree can be executed to recover otherwise locked funds. * @param root The root hash to be saved as the fallback withdrawal * authorizations. * @param maxDepositIncluded The max deposit nonce represented in this root. */ function setFallbackRoot(bytes32 root, uint256 maxDepositIncluded) external { require( msg.sender == _owner || msg.sender == _fallbackPublisher, "Only the owner and fallback publisher can set the fallback root hash" ); require( root != 0, "New root may not be 0" ); require( SafeMath.add(_fallbackSetDate, _fallbackWithdrawalDelaySeconds) > block.timestamp, "Cannot set fallback root while fallback mechanism is active" ); require( maxDepositIncluded >= _fallbackMaxDepositIncluded, "Max deposit included must remain the same or increase" ); require( maxDepositIncluded <= _depositNonce, "Cannot invalidate future deposits" ); _fallbackRoot = root; _fallbackMaxDepositIncluded = maxDepositIncluded; _fallbackSetDate = block.timestamp; emit FallbackRootHashSet( root, _fallbackMaxDepositIncluded, block.timestamp ); } /** * @notice Deletes the provided root from the collection of * withdrawal authorization merkle tree roots, invalidating the * withdrawals contained in the tree assocated with this root. * @param root The root hash to delete. */ function deleteWithdrawalRoot(bytes32 root) private { uint256 nonce = _withdrawalRootToNonce[root]; require( nonce > 0, "Root hash not set" ); delete _withdrawalRootToNonce[root]; emit WithdrawalRootHashRemoval(root, nonce); } /** * @notice Calculates the Merkle root for the unique Merkle tree described by the provided Merkle proof and leaf hash. * @param merkleProof The sibling node hashes at each level of the tree. * @param leafHash The hash of the leaf data for which merkleProof is an inclusion proof. * @return The calculated Merkle root. */ function calculateMerkleRoot( bytes32[] memory merkleProof, bytes32 leafHash ) private pure returns (bytes32) { bytes32 computedHash = leafHash; for (uint256 i = 0; i < merkleProof.length; i++) { bytes32 proofElement = merkleProof[i]; if (computedHash < proofElement) { computedHash = keccak256(abi.encodePacked( computedHash, proofElement )); } else { computedHash = keccak256(abi.encodePacked( proofElement, computedHash )); } } return computedHash; } }
Authorizes the transfer of ownership from _owner to the provided address. NOTE: No transfer will occur unless authorizedAddress calls assumeOwnership( ). This authorization may be removed by another call to this function authorizing the null address. authorizedAddress The address authorized to become the new owner./
function authorizeOwnershipTransfer(address authorizedAddress) external { require( msg.sender == _owner, "Only the owner can authorize a new address to become owner" ); _authorizedNewOwner = authorizedAddress; emit OwnershipTransferAuthorization(_authorizedNewOwner); }
12,781,441
pragma solidity ^0.4.23; import "../../../util/SafeMath.sol"; import "../../../storage/KeyValueStorage.sol"; /** * @title PatentToken is an ERC-721 NFT * Code is based on Open Zeppelin Library (https://github.com/OpenZeppelin/openzeppelin-solidity) * Includes modification for Patent metadata & licensing * Includes modifications to be upgradable by using Storage * @author Civic Ledger */ contract PatentToken { using SafeMath for uint256; event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); // Central storage contract KeyValueStorage internal storageContract; // Australian IPO uint256 internal ipoIndex = 0; // Patent IP right type string internal iprTypeName = "Patent"; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks to make sure the PatentRegistration contract is calling */ modifier onlyRegistrationContract() { address registrationAddress = storageContract.getAddress(keccak256("contract.name", "Registration", ipoIndex, iprTypeName)); require(msg.sender == registrationAddress); _; } /** * @dev Checks to make sure the Exchange contract is calling */ modifier onlyOwnerOrExchangeContract(uint256 _tokenId) { address exchangeAddress = storageContract.getAddress(keccak256("contract.name", "Exchange")); require(ownerOf(_tokenId) == msg.sender || msg.sender == exchangeAddress); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { address exchangeAddress = storageContract.getAddress(keccak256("contract.name", "Exchange")); require(isApprovedOrOwner(msg.sender, _tokenId) || msg.sender == exchangeAddress); _; } /** * @dev PatentToken constructor * @param _storageAddress Address of central storage contract */ constructor(address _storageAddress) public { storageContract = KeyValueStorage(_storageAddress); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return storageContract.getUint(keccak256("patent.owned.tokenCount", _owner)); } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = storageContract.getAddress(keccak256("patent.token.owner", _tokenId)); require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = storageContract.getAddress(keccak256("patent.token.owner", _tokenId)); return owner != address(0); } /** * @dev Gets whether the token is licensable */ function isLicensable(uint256 _tokenId) public view returns(bool) { return storageContract.getBool(keccak256("patent.licensable", _tokenId)); } /** * @dev Sets whether the token is licensable * @param _tokenId uint256 ID of the token to set licensibility * @param _licensable Is is licensable or not? */ function setLicensable(uint256 _tokenId, bool _licensable) external onlyOwnerOf(_tokenId) { storageContract.setBool(keccak256("patent.licensable", _tokenId), _licensable); } /** * @dev Gets whether the token is transferrable */ function isTransferrable(uint256 _tokenId) public view returns(bool) { return storageContract.getBool(keccak256("patent.transferrable", _tokenId)); } /** * @dev Gets whether an order type is valid for this token * @param _tokenId ID of the token to check * @param _orderType ID of the order type (0 = transfer, 1 = license) */ function isValidOrderType(uint256 _tokenId, uint256 _orderType) external view returns(bool) { if (_orderType == 1) { require(isTransferrable(_tokenId) == true); return true; } else if (_orderType == 2) { require(isLicensable(_tokenId) == true); return true; } return false; } /** * @dev Sets whether the token is transferrable * @param _tokenId uint256 ID of the token to set licensibility * @param _transferrable Is is licensable or not? */ function setTransferrable(uint256 _tokenId, bool _transferrable) external onlyOwnerOf(_tokenId) { storageContract.setBool(keccak256("patent.transferrable", _tokenId), _transferrable); } /// @dev Allows patent owner to license a patent to a licensee /// @dev Patent must be granted to be licensed /// @param _tokenId Index of patent to license /// @param _licenseeAddress Address of licensee to grant license to function license(uint256 _tokenId, address _licenseeAddress) public onlyOwnerOrExchangeContract(_tokenId) { // get license index uint256 nextIndex = storageContract.getUint(keccak256("patent.licenses.nextIndex", _tokenId)); storageContract.setBool(keccak256("patent.license", _tokenId, _licenseeAddress), true); // increment the license index storageContract.setUint(keccak256("patent.licenses.nextIndex", _tokenId), nextIndex++); } /// @dev Executes order /// @param _tokenId Index of token /// @param _orderType Type of order /// @param _from Patent owner /// @param _to Patent orderee function executeOrder(uint256 _tokenId, uint256 _orderType, address _from, address _to) external onlyOwnerOrExchangeContract(_tokenId) returns(bool) { require(_from == ownerOf(_tokenId)); require(_to != address(0)); if (_orderType == 1) { // transfer patent transferFrom(_from, _to, _tokenId); } else if (_orderType == 2) { // license patent license(_tokenId, _to); } return true; } /// @dev Queries whether an address has a license for the patent /// @param _tokenId Index of patent to check license /// @param _licenseeAddress Address of licensee to check license of function hasLicense(uint256 _tokenId, address _licenseeAddress) external view returns(bool) { return storageContract.getBool(keccak256("patent.license", _tokenId, _licenseeAddress)); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { storageContract.setAddress(keccak256("patent.token.approvals", _tokenId), _to); emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return storageContract.getAddress(keccak256("patent.token.approvals", _tokenId)); } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Function to mint a new token * @dev Reverts if not called by registration contract * @param _to The address that will own the minted token */ function mint(address _to) external onlyRegistrationContract returns(uint) { require(_to != address(0)); uint tokenCount = storageContract.getUint(keccak256("patent.tokenCount")); uint nextTokenId = tokenCount.add(1); addTokenTo(_to, nextTokenId); emit Transfer(address(0), _to, nextTokenId); return nextTokenId; } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (storageContract.getAddress(keccak256("patent.token.approvals", _tokenId)) != address(0)) { storageContract.setAddress(keccak256("patent.token.approvals", _tokenId), address(0)); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { address owner = storageContract.getAddress(keccak256("patent.token.owner", _tokenId)); require(owner == address(0)); storageContract.setAddress(keccak256("patent.token.owner", _tokenId), _to); // increase owner token count uint ownerTokenCount = storageContract.getUint(keccak256("patent.owned.tokenCount", _to)); storageContract.setUint(keccak256("patent.owned.tokenCount", _to), ownerTokenCount.add(1)); // increase overall token count uint tokenCount = storageContract.getUint(keccak256("patent.tokenCount")); storageContract.setUint(keccak256("patent.tokenCount"), tokenCount.add(1)); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); uint tokenCount = storageContract.getUint(keccak256("patent.owned.tokenCount", _from)); storageContract.setUint(keccak256("patent.owned.tokenCount", _from), tokenCount.sub(1)); storageContract.setAddress(keccak256("patent.token.owner", _tokenId), address(0)); } }
Queries whether an address has a license for the patent _tokenId Index of patent to check license _licenseeAddress Address of licensee to check license of
function hasLicense(uint256 _tokenId, address _licenseeAddress) external view returns(bool) { return storageContract.getBool(keccak256("patent.license", _tokenId, _licenseeAddress)); }
12,845,991
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; /** * @title EternalStorage * @dev An ownable contract that can be used as a storage where the variables * are stored in a set of mappings indexed by hash names. */ contract EternalStorage { struct Storage { mapping(bytes32 => bool) _bool; mapping(bytes32 => int256) _int; mapping(bytes32 => uint256) _uint; mapping(bytes32 => string) _string; mapping(bytes32 => address) _address; mapping(bytes32 => bytes) _bytes; mapping(bytes32 => bytes32) _bytes32; } Storage internal s; /** * @dev Get the value stored of a boolean variable by the hash name * @param h The keccak256 hash of the variable name */ function getBoolean(bytes32 h) public view returns (bool) { return s._bool[h]; } /** * @dev Get the value stored of a int variable by the hash name * @param h The keccak256 hash of the variable name */ function getInt(bytes32 h) public view returns (int) { return s._int[h]; } /** * @dev Get the value stored of a uint variable by the hash name * @param h The keccak256 hash of the variable name */ function getUint(bytes32 h) public view returns (uint256) { return s._uint[h]; } /** * @dev Get the value stored of a address variable by the hash name * @param h The keccak256 hash of the variable name */ function getAddress(bytes32 h) public view returns (address) { return s._address[h]; } /** * @dev Get the value stored of a string variable by the hash name * @param h The keccak256 hash of the variable name */ function getString(bytes32 h) public view returns (string) { return s._string[h]; } /** * @dev Get the value stored of a bytes variable by the hash name * @param h The keccak256 hash of the variable name */ function getBytes(bytes32 h) public view returns (bytes) { return s._bytes[h]; } /** * @dev Get the value stored of a bytes variable by the hash name * @param h The keccak256 hash of the variable name */ function getBytes32(bytes32 h) public view returns (bytes32) { return s._bytes32[h]; } /** * @dev Allows the owner to set a value for a boolean variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setBoolean(bytes32 h, bool v) internal { s._bool[h] = v; } /** * @dev Allows the owner to set a value for a int variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setInt(bytes32 h, int256 v) internal { s._int[h] = v; } /** * @dev Allows the owner to set a value for a boolean variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setUint(bytes32 h, uint256 v) internal { s._uint[h] = v; } /** * @dev Allows the owner to set a value for a address variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setAddress(bytes32 h, address v) internal { s._address[h] = v; } /** * @dev Allows the owner to set a value for a string variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setString(bytes32 h, string v) internal { s._string[h] = v; } /** * @dev Allows the owner to set a value for a bytes variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setBytes(bytes32 h, bytes v) internal { s._bytes[h] = v; } /** * @dev Allows the owner to set a value for a bytes32 variable * @param h The keccak256 hash of the variable name * @param v The value to be stored */ function _setBytes32(bytes32 h, bytes32 v) internal { s._bytes32[h] = v; } }
Get the value stored of a boolean variable by the hash name h The keccak256 hash of the variable name/
function getBoolean(bytes32 h) public view returns (bool) { return s._bool[h]; }
6,382,838
./full_match/1/0x7c804b088109C23d9129366a8C069448A4b219F8/sources/src/cores/TokenMetadata/ITokenMetadata.sol
events errors views
interface ITokenMetadataInternal { event NameUpdated(string name); event SymbolUpdated(string symbol); function name() external view returns (string calldata); function symbol() external view returns (string calldata); pragma solidity ^0.8.13; }
8,351,289
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } 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; } } 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); } } 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); } } } } 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); } abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface 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); } 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; } } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _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); } } 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; } } library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } contract PET721 is Context, ERC165, IERC721, Ownable{ using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; using Strings for uint8; using Strings for bool; using Strings for address; using Counters for Counters.Counter; // 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 = "NEKO INU"; // Token symbol string private _symbol = "NEKOINU"; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; // Map the number of tokens per mrId mapping(uint8 => uint256) public mrCount; // Map the number of tokens burnt per mrId mapping(uint8 => uint256) public mrBurnCount; // Used for generating the tokenId of new NFT minted Counters.Counter private _tokenIds; // Map the mrId for each tokenId mapping(uint256 => uint8) private mrIds; string[] public mrInfoIdList; // Used for generating the itemId of new NFT Item created Counters.Counter private _mrIdKindCount; // nft mr item struct struct MRinfo{ // nft item Id uint8 mrId; // nft item name string mrName; // nft item rate uint256 mrRate; // nft item price uint256 mrPrice; // nft item image URI string mrMetaDataURI; // nft item image thumnail URI uint256 maxCount; // paid currency kind 1:BNB, 2: LPLT uint8 currency; } // Map the nft mr item info for mrID mapping(uint8 => MRinfo) private mrInfos; // Map the owned nft mr item price for each tokenId mapping(uint256 => uint256) private ownedNftPrice; // Map the owned nft mr item sell state for each tokenId. 1: sell, 0: keep mapping(uint256=>uint8) private ownedNftState; constructor () { } //Returns the base URI set via {_setBaseURI}. This will be function baseURI() public view returns (string memory) { return _baseURI; } /** * @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_) public onlyOwner { _setBaseURI(baseURI_); } function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } // Returns the number of tokens in ``owner``'s account. function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } //Returns the owner of the `tokenId` token. function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } //Returns the token collection name. function name() public view returns (string memory) { return _name; } //Returns the token collection symbol. function symbol() public view returns (string memory) { return _symbol; } //Returns the Uniform Resource Identifier (URI) for `tokenId` token. function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).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(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } //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) public view returns (uint256) { return _holderTokens[owner].at(index); } //Returns the total amount of tokens stored by the contract. function totalSupply() public view returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } //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) public view returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /*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) public virtual override { require(_exists(tokenId), "nonexistent token"); address owner = 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); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } //dev Returns the account approved for `tokenId` token. function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /*Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * - The `operator` cannot be the caller. * Emits an {ApprovalForAll} event. */ 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); } //Returns if the `operator` is allowed to manage all of the assets of `owner`. function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. */ 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 Transfers `tokenId` token from `from` to `to`. * - `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) 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 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. * - `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) public virtual override { require(_exists(tokenId), "nonexistent token"); //require(msg.value >= ownedNftPrice[tokenId], "input the exact price."); safeTransferFrom(from, to, tokenId, ""); } /* @dev Safely transfers `tokenId` token from `from` to `to`. - `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 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. * - `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 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(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @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 _tokenOwners.contains(tokenId); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * - 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 Hook that is called before any token transfer. This includes minting * and burning. * - 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 { } /** * @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 == IERC721Receiver.onERC721Received.selector); } /** * @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 Sets `_tokenURI` as the tokenURI of `tokenId`. * Requirements: * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Mint NFTs. Only the owner can call it. */ function mintTokenByETH(address _to, uint8 _mrId, uint256 _count) public payable{ require(_count >0); // require(_count <= 10, "exceeded the mintable count of purchases in once."); require((mrCount[_mrId] + _count) <= mrInfos[_mrId].maxCount, "exceeded the maximum mintable count of purchases."); require(msg.value == mrInfos[_mrId].mrPrice * _count, "exceeded the balance."); require(mrInfos[_mrId].currency == 1); uint256 i; uint256 newId; for(i = 0; i < _count; i++) { newId = _tokenIds.current(); _tokenIds.increment(); mrIds[newId] = _mrId; mrCount[_mrId] = mrCount[_mrId].add(1); _mint(_to, newId); _setTokenURI(newId, mrInfos[_mrId].mrMetaDataURI); ownedNftPrice[newId] = mrInfos[_mrId].mrPrice; ownedNftState[newId] = 0; } } // buy item from MarketPlace function buyItemFromMarketPlace(uint256 tokenId) public payable{ require(ownedNftState[tokenId] == 1); uint256 price = getUserMrPrice(tokenId); require(price > 0); require(msg.value >= price); address ownerofToken = ownerOf(tokenId); uint256 fee = msg.value * 3 / 1000; IERC721(address(this)).transferFrom(ownerofToken, msg.sender, tokenId); payable(ownerofToken).transfer(msg.value - fee); ownedNftState[tokenId] = 0; } /** * @dev create new NFT MR item. Only the owner can call it. */ function mintMrId(string memory _mrName, uint256 _mrRate, uint256 _mrPrice, string memory _mrMetaDataURI, uint256 _maxCount) public onlyOwner returns (uint8){ require(_mrIdKindCount.current() < 256, "impossible to create a new kind of nft item any more."); uint8 newMrId = uint8(_mrIdKindCount.current()); _mrIdKindCount.increment(); MRinfo memory mrInfo; mrInfo = MRinfo(newMrId, _mrName, _mrRate, _mrPrice, _mrMetaDataURI, _maxCount, 1); mrInfos[newMrId] = mrInfo; mrInfoIdList.push(mrInfos[newMrId].mrName); return newMrId; } function getMrInfoIdList(uint256 index) public view returns (string memory) { return mrInfoIdList[index]; } /** * @dev Get mrId for a specific tokenId. */ function getMrId(uint256 _tokenId) public view returns (uint8) { require(_exists(_tokenId), "nonexistent token"); return mrIds[_tokenId]; } /** * @dev Get the associated mrName for a specific mrId. */ function getMrName(uint8 _mrId) public view returns (string memory){ return mrInfos[_mrId].mrName; } /** * @dev Set a unique name for each mrId. It is supposed to be called once. */ function setMrName(uint8 mrId_, string memory name_) public onlyOwner { mrInfos[mrId_].mrName = name_; } /** * @dev Get the associated rate for a specific mrId. */ function getMrRate(uint8 _mrId) public view returns (uint256){ return mrInfos[_mrId].mrRate; } /** * @dev Set a rate for each mrId. It is supposed to be called once. */ function setMrRate(uint8 mrId_, uint256 _rate) public onlyOwner { mrInfos[mrId_].mrRate = _rate; } /** * @dev Get the associated price for a specific mrId. */ function getMrPrice(uint8 _mrId) public view returns (uint256){ return mrInfos[_mrId].mrPrice; } /** * @dev Set a price for each mrId. It is supposed to be called once. */ function setMrPrice(uint8 mrId_, uint256 price_) public onlyOwner { mrInfos[mrId_].mrPrice = price_; } /** * @dev Get the associated mrName for a unique tokenId. */ function getMrNameOfTokenId(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId), "nonexistent token"); return mrInfos[mrIds[_tokenId]].mrName; } function getMrItemKindCount() public view returns (uint256){ return _mrIdKindCount.current(); } /** * @dev Get a MetaDataURI for each mrId. It is supposed to be called once. */ function getMrMetaDataURI(uint8 mrId_) public view returns (string memory) { string memory MetaData =mrInfos[mrId_].mrMetaDataURI; return MetaData; } /** * @dev Set a MetaDataURI for each mrId. It is supposed to be called once. */ function setMrMetaDataURI(uint8 mrId_, string memory _MetaData) public onlyOwner { mrInfos[mrId_].mrMetaDataURI = _MetaData; } /** * @dev Get a minted token count for each mrId. It is supposed to be called once. */ function getMrMintedTokenCount(uint8 mrId_) public view returns (uint256) { return mrCount[mrId_]; } /** * @dev Get a initial mintable max token count for each mrId. It is supposed to be called once. */ function getMrMaxTokenCount(uint8 mrId_) public view returns (uint256) { return mrInfos[mrId_].maxCount; } /** * @dev Set a maxCount for each mrId. It is supposed to be called once. */ function setMrMaxCount(uint8 mrId_, uint256 _maxCount) public onlyOwner { mrInfos[mrId_].maxCount = _maxCount; } /** * @dev Get a maxCount for each mrId. It is supposed to be called once. */ function getMrMaxCount(uint8 mrId_) public view returns (uint256) { return mrInfos[mrId_].maxCount; } /** * @dev Set a maxCount for each mrId. It is supposed to be called once. 1:BNB, 2:LPLT */ function setMrCurrencyKind(uint8 mrId_, uint8 _currency) public onlyOwner { _currency = _currency % 3; if (_currency == 0) _currency = 1; mrInfos[mrId_].currency = _currency; } /** * @dev Get a maxCount for each mrId. It is supposed to be called once. */ function getMrCurrencyKind(uint8 mrId_) public view returns (uint8) { return mrInfos[mrId_].currency; } /** * @dev Get a price for _tokenId. It is supposed to be called once. */ function getUserMrPrice(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId), "nonexistent token"); return ownedNftPrice[_tokenId]; } /** * @dev Set a price for _tokenId. It is supposed to be called once. */ function setUserMrPrice(uint256 _tokenId, uint256 _amount) public { require(msg.sender == ownerOf(_tokenId)); require(_exists(_tokenId), "nonexistent token"); ownedNftPrice[_tokenId] = _amount; } /** * @dev Get a salable state for _tokenId. It is supposed to be called once. true: salable, false: not salable */ function getUserNftSellState(uint256 _tokenId) public view returns (uint8){ require(_exists(_tokenId), "nonexistent token"); return ownedNftState[_tokenId]; } /** * @dev Set a salable state for _tokenId. It is supposed to be called once. true: salable, false: not salable */ function setUserNftSellState(uint256 _tokenId, uint256 _price, uint8 state) public { require(_exists(_tokenId), "nonexistent token"); require(msg.sender == ownerOf(_tokenId)); state = state % 2; setUserMrPrice(_tokenId, _price); if (state == 1) { approve(address(this), _tokenId); } else { approve(address(0), _tokenId); } ownedNftState[_tokenId] = state; } // get user item list info from user inventory function fetchUserInventory(address wallet) public view returns (string memory){ uint256 ownedTokenCount = balanceOf(wallet); string memory json; uint256 tokenId; uint8 itemId; json = "["; for (uint256 i = 0; i < ownedTokenCount; i++){ tokenId = tokenOfOwnerByIndex(wallet, i); itemId = getMrId(tokenId); json = string(abi.encodePacked(json, "{\"tokenId\":\"", tokenId.toString(), "\",\"tokenSellState\":\"", getUserNftSellState(tokenId).toString(), "\",\"itemId\":\"", itemId.toString(), "\", \"price\":\"", getUserMrPrice(tokenId).toString(), "\",\"rate\":\"", mrInfos[itemId].mrRate.toString(),"\",\"metaDataURI\":\"", tokenURI(tokenId), "\"}")); if(i != ownedTokenCount-1) json = string(abi.encodePacked(json, ",")); } json = string(abi.encodePacked(json, "]")); return json; } // get item list from Shop function fetchItemFromShop() public view returns (string memory){ uint256 itemKindCount = getMrItemKindCount(); string memory json; json = "["; for (uint8 i = 0; i < itemKindCount; i++){ json = string(abi.encodePacked(json, "{\"mrId\":\"", mrInfos[i].mrId.toString(), "\", \"mrMetaDataURI\":\"", mrInfos[i].mrMetaDataURI, "\", \"mrPrice\":\"", mrInfos[i].mrPrice.toString(), "\", \"currency\":\"", mrInfos[i].currency.toString(), "\", \"rate\":\"", mrInfos[i].mrRate.toString(),"\", \"curCount\":\"", getMrMintedTokenCount(i).toString(), "\", \"maxCount\":\"", mrInfos[i].maxCount.toString(), "\"}")); if(i != itemKindCount-1) json = string(abi.encodePacked(json, ",")); } json = string(abi.encodePacked(json, "]")); return json; } // get item list from marketplace function fetchItemFromMarketPlace() public view returns (string memory){ uint256 totalTokenCount = totalSupply(); uint256 tokenId; string memory json; json = "["; bool flag = false; for(uint256 i = 0; i < totalTokenCount; i++) { tokenId = tokenByIndex(i); if(getUserNftSellState(tokenId) == 1) { json = string(abi.encodePacked(json, "{\"tokenId\":\"", tokenId.toString(), "\", \"owner\":\"", toString(ownerOf(tokenId)), "\", \"price\":\"", getUserMrPrice(tokenId).toString(), "\", \"currency\":\"", mrInfos[getMrId(tokenId)].currency.toString(), "\", \"mrMetaDataURI\":\"", tokenURI(tokenId), "\", \"rate\":\"", mrInfos[getMrId(tokenId)].mrRate.toString(), "\", \"mrId\":\"", getMrId(tokenId).toString(), "\"}")); //if(i != totalTokenCount-1) json = string(abi.encodePacked(json, ",")); flag = true; } } if(flag == true) json = string(abi.encodePacked("", substring(json, 0,getStringLength2(json)-1))); json = string(abi.encodePacked(json, "]")); return json; } /* get Owner Count per MrId*/ function getOwnerCountByMrId(uint8 search_mrId, uint8 restrictedFlag) public view returns(uint256){ uint256 totalTokenCount = totalSupply(); uint256 tokenId; uint8 mrId; restrictedFlag = restrictedFlag % 2; address[] memory ownerArray = new address[](totalTokenCount); uint256 count = 0; address tokenOwner; bool flag; for(uint256 i = 0; i < totalTokenCount; i++){ if(restrictedFlag == 1 && getUserNftSellState(tokenId) != 1) continue; tokenId = tokenByIndex(i); mrId = getMrId(tokenId); if(mrId == search_mrId){ tokenOwner = ownerOf(tokenId); flag = false; for(uint256 j = 0; j < count; j++){ if(tokenOwner == ownerArray[j]){ flag = true; break; } } if(!flag){ ownerArray[count] = tokenOwner; count++; } } } return count; } /* get user total mining rate*/ function getUserTotalRate(address wallet) public view returns (uint256) { uint256 ownedTokenCount = balanceOf(wallet); uint8 itemId; uint256 itemKindCount = getMrItemKindCount(); uint256[] memory rateArray = new uint256[](itemKindCount); uint256 tokenId; uint256 totalRate = 0; for (uint256 i = 0; i < ownedTokenCount; i++) { tokenId = tokenOfOwnerByIndex(wallet, i); itemId = getMrId(tokenId); if(rateArray[itemId] == 0) { rateArray[itemId]++; totalRate += getMrRate(itemId); } } return totalRate; } function toString(address account) public pure returns(string memory) { return toString(abi.encodePacked(account)); } function toString(bytes memory data) public pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function substring(string memory str, uint startIndex, uint endIndex) public pure returns (string memory) { 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); } function getStringLength2(string memory str) public pure returns (uint256) { uint256 length = bytes(str).length; return length; } /** * @dev Burn a NFT token. Callable by owner only. */ function burn(uint256 _tokenId) public onlyOwner { require(_exists(_tokenId), "nonexistent token"); uint8 mrIdBurnt = mrIds[_tokenId]; mrCount[mrIdBurnt] = mrCount[mrIdBurnt].sub(1); mrBurnCount[mrIdBurnt] = mrBurnCount[mrIdBurnt].add(1); _burn(_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 = ownerOf(tokenId); _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); } function withdraw(uint256 amount) public onlyOwner{ require(amount <= address(this).balance, "Not enough tokens in the reserve"); address payable _owner = payable (owner()); _owner.transfer(amount); } function getContractBalance() public view returns (uint256) { return address(this).balance; } function changeOwner(address otherAddress) public onlyOwner () { transferOwnership(otherAddress); } function getContractOwner() public view returns (address){ return owner(); } }
Get a maxCount for each mrId. It is supposed to be called once./
function getMrMaxCount(uint8 mrId_) public view returns (uint256) { return mrInfos[mrId_].maxCount; }
6,986,724
./partial_match/1/0x61fED4F55a361775e734f6a90bB47aaEB7ceE20B/sources/contracts-eth/SmartChefWETH.sol
View function to see pending reward on frontend. _user: user address return Pending reward for a given user/
function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 stakedTokenSupply = stakedToken.balanceOf(address(this)); if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 appleReward = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add(appleReward.mul(PRECISION_FACTOR).div(stakedTokenSupply)); return user.amount.mul(adjustedTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt); } }
15,573,526
./partial_match/42/0x79a824F5DD18F15Ba48517dF81B0C8C7008Dd348/sources/HedgeyPutsV1.sol
now that we have made sure the openPut is open, the new one is not, neither are exercised, and the new bid is tradeableplus checked that all the details match except price of course - we close the new bid and assign the open put to new longassign the call.longclose out our new bid
function sellOpenPuttoNewBid(uint _p, uint _q) payable public { require(msg.sender == openPut.long, "you dont own this"); require(openPut.strike == newBid.strike, "not the right strike"); require(openPut.assetAmt == newBid.assetAmt, "not the right assetAmt"); require(openPut.expiry == newBid.expiry, "not the right expiry"); require(openPut.open && !newBid.open && newBid.tradeable && !openPut.exercised && !newBid.exercised && openPut.expiry > now && newBid.expiry > now, "something is wrong"); openPut.long = newBid.long; openPut.price = newBid.price; openPut.tradeable = false; newBid.exercised = true; newBid.tradeable = false; emit OpenPutSold(_p, _q); }
3,326,329
pragma solidity >=0.5.8; pragma experimental ABIEncoderV2; import "./lib/Authorizable.sol"; import "./lib/Transferable.sol"; import "./lib/Verifiable.sol"; /** * @title Atomic swap contract used by the Swap Protocol */ contract Swap is Authorizable, Transferable, Verifiable { // Status that an order may hold enum ORDER_STATUS { OPEN, TAKEN, CANCELED } // Maps makers to orders by nonce as TAKEN (0x01) or CANCELED (0x02) mapping (address => mapping (uint256 => ORDER_STATUS)) public makerOrderStatus; // Maps makers to an optionally set minimum valid nonce mapping (address => uint256) public makerMinimumNonce; // Emitted on Swap event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); // Emitted on Cancel event Cancel( uint256 indexed nonce, address indexed makerWallet ); // Emitted on SetMinimumNonce event SetMinimumNonce( uint256 indexed nonce, address indexed makerWallet ); /** * @notice Atomic Token Swap * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param order Order * @param signature Signature */ function swap( Order calldata order, Signature calldata signature ) external payable { // Ensure the order is not expired require(order.expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.TAKEN, "ORDER_ALREADY_TAKEN"); // Ensure the order has not already been canceled require(makerOrderStatus[order.maker.wallet][order.nonce] != ORDER_STATUS.CANCELED, "ORDER_ALREADY_CANCELED"); require(order.nonce >= makerMinimumNonce[order.maker.wallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (order.taker.wallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != order.taker.wallet) { require(isAuthorized(order.taker.wallet, msg.sender), "SENDER_UNAUTHORIZED"); } // Set the taker to be the specified taker finalTakerWallet = order.taker.wallet; } // Ensure the order signer is authorized require(isAuthorized(order.maker.wallet, signature.signer), "SIGNER_UNAUTHORIZED"); // Ensure the order signature is valid require(isValid(order, signature), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[order.maker.wallet][order.nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (order.taker.token == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == order.taker.param, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(order.maker.wallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker safeTransferAny( "TAKER", finalTakerWallet, order.maker.wallet, order.taker.param, order.taker.token ); } // Transfer token from maker to taker safeTransferAny( "MAKER", order.maker.wallet, finalTakerWallet, order.maker.param, order.maker.token ); // Transfer token from maker to affiliate if specified if (order.affiliate.wallet != address(0)) { safeTransferAny( "MAKER", order.maker.wallet, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } emit Swap(order.nonce, block.timestamp, order.maker.wallet, order.maker.param, order.maker.token, finalTakerWallet, order.taker.param, order.taker.token, order.affiliate.wallet, order.affiliate.param, order.affiliate.token ); } /** * @notice Atomic Token Swap (Simple) * @dev Determines type (ERC-20 or ERC-721) with ERC-165 * * @param nonce uint256 * @param expiry uint256 * @param makerWallet address * @param makerParam uint256 * @param makerToken address * @param takerWallet address * @param takerParam uint256 * @param takerToken address * @param v uint8 * @param r bytes32 * @param s bytes32 */ function swapSimple( uint256 nonce, uint256 expiry, address makerWallet, uint256 makerParam, address makerToken, address takerWallet, uint256 takerParam, address takerToken, uint8 v, bytes32 r, bytes32 s ) external payable { // Ensure the order is not expired require(expiry > block.timestamp, "ORDER_EXPIRED"); // Ensure the order has not already been taken or canceled require(makerOrderStatus[makerWallet][nonce] == ORDER_STATUS.OPEN, "ORDER_UNAVAILABLE"); require(nonce >= makerMinimumNonce[makerWallet], "NONCE_TOO_LOW"); // Ensure the order taker is set and authorized address finalTakerWallet; if (takerWallet == address(0)) { // Set a null taker to be the order sender finalTakerWallet = msg.sender; } else { // Ensure the order sender is authorized if (msg.sender != takerWallet) { require(isAuthorized(takerWallet, msg.sender), "SENDER_UNAUTHORIZED"); } finalTakerWallet = takerWallet; } // Ensure the order signature is valid require(isValidSimple( nonce, expiry, makerWallet, makerParam, makerToken, takerWallet, takerParam, takerToken, v, r, s ), "SIGNATURE_INVALID"); // Mark the order TAKEN (0x01) makerOrderStatus[makerWallet][nonce] = ORDER_STATUS.TAKEN; // A null taker token is an order for ether if (takerToken == address(0)) { // Ensure the ether sent matches the taker param require(msg.value == takerParam, "VALUE_MUST_BE_SENT"); // Transfer ether from taker to maker send(makerWallet, msg.value); } else { // Ensure the value sent is zero require(msg.value == 0, "VALUE_MUST_BE_ZERO"); // Transfer token from taker to maker transferAny(takerToken, finalTakerWallet, makerWallet, takerParam); } // Transfer token from maker to taker transferAny(makerToken, makerWallet, finalTakerWallet, makerParam); emit Swap(nonce, block.timestamp, makerWallet, makerParam, makerToken, finalTakerWallet, takerParam, takerToken, address(0), 0, address(0) ); } /** @notice Cancel a batch of orders for a maker * @dev Canceled orders are marked CANCELED (0x02) * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external { for (uint256 i = 0; i < nonces.length; i++) { if (makerOrderStatus[msg.sender][nonces[i]] == ORDER_STATUS.OPEN) { makerOrderStatus[msg.sender][nonces[i]] = ORDER_STATUS.CANCELED; emit Cancel(nonces[i], msg.sender); } } } /** @notice Set a minimum valid nonce for a maker * @dev Order nonces below the value will be rejected * @param minimumNonce uint256 */ function setMinimumNonce(uint256 minimumNonce) external { makerMinimumNonce[msg.sender] = minimumNonce; emit SetMinimumNonce(minimumNonce, msg.sender); } }
Set a minimum valid nonce for a maker Order nonces below the value will be rejected minimumNonce uint256/
function setMinimumNonce(uint256 minimumNonce) external { makerMinimumNonce[msg.sender] = minimumNonce; emit SetMinimumNonce(minimumNonce, msg.sender); }
7,220,701
pragma solidity 0.4.15; import './ownership/multiowned.sol'; import './crowdsale/FixedTimeBonuses.sol'; import './crowdsale/FundsRegistry.sol'; import './crowdsale/InvestmentAnalytics.sol'; import './security/ArgumentsChecker.sol'; import './STQToken.sol'; import 'zeppelin-solidity/contracts/ReentrancyGuard.sol'; import 'zeppelin-solidity/contracts/math/Math.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; /// @title Storiqa ICO contract contract STQCrowdsale is ArgumentsChecker, ReentrancyGuard, multiowned, InvestmentAnalytics { using Math for uint256; using SafeMath for uint256; using FixedTimeBonuses for FixedTimeBonuses.Data; enum IcoState { INIT, ICO, PAUSED, FAILED, DISTRIBUTING_BONUSES, SUCCEEDED } /// @dev bookkeeping for last investment bonus struct LastInvestment { address investor; uint payment; // time-based bonus which was already received by the investor uint timeBonus; } event StateChanged(IcoState _state); event FundTransfer(address backer, uint amount, bool isContribution); modifier requiresState(IcoState _state) { require(m_state == _state); _; } /// @dev triggers some state changes based on current time /// @param investor optional refund parameter /// @param payment optional refund parameter /// note: function body could be skipped! modifier timedStateChange(address investor, uint payment) { if (IcoState.INIT == m_state && getCurrentTime() >= getStartTime()) changeState(IcoState.ICO); if (IcoState.ICO == m_state && getCurrentTime() >= getEndTime()) { finishICO(); if (payment > 0) investor.transfer(payment); // note that execution of further (but not preceding!) modifiers and functions ends here } else { _; } } /// @dev automatic check for unaccounted withdrawals /// @param investor optional refund parameter /// @param payment optional refund parameter modifier fundsChecker(address investor, uint payment) { uint atTheBeginning = m_funds.balance; if (atTheBeginning < m_lastFundsAmount) { changeState(IcoState.PAUSED); if (payment > 0) investor.transfer(payment); // we cant throw (have to save state), so refunding this way // note that execution of further (but not preceding!) modifiers and functions ends here } else { _; if (m_funds.balance < atTheBeginning) { changeState(IcoState.PAUSED); } else { m_lastFundsAmount = m_funds.balance; } } } // PUBLIC interface function STQCrowdsale(address[] _owners, address _token, address _funds, address _teamTokens) multiowned(_owners, 2) validAddress(_token) validAddress(_funds) validAddress(_teamTokens) { require(3 == _owners.length); m_token = STQToken(_token); m_funds = FundsRegistry(_funds); m_teamTokens = _teamTokens; m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (1 weeks), bonus: 30})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (2 weeks), bonus: 25})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (3 weeks), bonus: 20})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (4 weeks), bonus: 15})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (5 weeks), bonus: 10})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: c_startTime + (8 weeks), bonus: 5})); m_bonuses.bonuses.push(FixedTimeBonuses.Bonus({endTime: 1514246400, bonus: 0})); m_bonuses.validate(true); deployer = msg.sender; } // PUBLIC interface: payments // fallback function as a shortcut function() payable { require(0 == msg.data.length); buy(); // only internal call here! } /// @notice ICO participation function buy() public payable { // dont mark as external! iaOnInvested(msg.sender, msg.value, false); } function iaOnInvested(address investor, uint payment, bool usingPaymentChannel) internal nonReentrant timedStateChange(investor, payment) fundsChecker(investor, payment) { require(m_state == IcoState.ICO || m_state == IcoState.INIT && isOwner(investor) /* for final test */); require(payment >= c_MinInvestment); uint startingInvariant = this.balance.add(m_funds.balance); // checking for max cap uint fundsAllowed = getMaximumFunds().sub(getTotalInvested()); assert(0 != fundsAllowed); // in this case state must not be IcoState.ICO payment = fundsAllowed.min256(payment); uint256 change = msg.value.sub(payment); // issue tokens var (stq, timeBonus) = calcSTQAmount(payment, usingPaymentChannel ? c_paymentChannelBonusPercent : 0); m_token.mint(investor, stq); // record payment m_funds.invested.value(payment)(investor); FundTransfer(investor, payment, true); recordInvestment(investor, payment, timeBonus); // check if ICO must be closed early if (change > 0) { assert(getMaximumFunds() == getTotalInvested()); finishICO(); // send change investor.transfer(change); assert(startingInvariant == this.balance.add(m_funds.balance).add(change)); } else assert(startingInvariant == this.balance.add(m_funds.balance)); } // PUBLIC interface: owners: maintenance /// @notice pauses ICO function pause() external timedStateChange(address(0), 0) requiresState(IcoState.ICO) onlyowner { changeState(IcoState.PAUSED); } /// @notice resume paused ICO function unpause() external timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { changeState(IcoState.ICO); checkTime(); } /// @notice consider paused ICO as failed function fail() external timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { changeState(IcoState.FAILED); } /// @notice In case we need to attach to existent token function setToken(address _token) external validAddress(_token) timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { m_token = STQToken(_token); } /// @notice In case we need to attach to existent funds function setFundsRegistry(address _funds) external validAddress(_funds) timedStateChange(address(0), 0) requiresState(IcoState.PAUSED) onlymanyowners(sha3(msg.data)) { m_funds = FundsRegistry(_funds); } /// @notice explicit trigger for timed state changes function checkTime() public timedStateChange(address(0), 0) onlyowner { } /// @notice computing and distributing post-ICO bonuses function distributeBonuses(uint investorsLimit) external timedStateChange(address(0), 0) requiresState(IcoState.DISTRIBUTING_BONUSES) { uint limitIndex = uint(m_lastInvestments.length).min256(m_nextUndestributedBonusIndex + investorsLimit); uint iterations = 0; uint startingGas = msg.gas; while (m_nextUndestributedBonusIndex < limitIndex) { if (c_lastInvestmentsBonus > m_lastInvestments[m_nextUndestributedBonusIndex].timeBonus) { uint bonus = c_lastInvestmentsBonus.sub(m_lastInvestments[m_nextUndestributedBonusIndex].timeBonus); uint bonusSTQ = m_lastInvestments[m_nextUndestributedBonusIndex].payment.mul(c_STQperETH).mul(bonus).div(100); m_token.mint(m_lastInvestments[m_nextUndestributedBonusIndex].investor, bonusSTQ); } m_nextUndestributedBonusIndex++; // preventing gas limit hit uint avgGasPerIteration = startingGas.sub(msg.gas).div(++iterations); if (msg.gas < avgGasPerIteration * 3) break; } if (m_nextUndestributedBonusIndex == m_lastInvestments.length) changeState(IcoState.SUCCEEDED); } function createMorePaymentChannels(uint limit) external returns (uint) { require(isOwner(msg.sender) || msg.sender == deployer); return createMorePaymentChannelsInternal(limit); } // INTERNAL functions function finishICO() private { if (getTotalInvested() < getMinFunds()) changeState(IcoState.FAILED); else changeState(IcoState.DISTRIBUTING_BONUSES); } /// @dev performs only allowed state transitions function changeState(IcoState _newState) private { assert(m_state != _newState); if (IcoState.INIT == m_state) { assert(IcoState.ICO == _newState); } else if (IcoState.ICO == m_state) { assert(IcoState.PAUSED == _newState || IcoState.FAILED == _newState || IcoState.DISTRIBUTING_BONUSES == _newState); } else if (IcoState.PAUSED == m_state) { assert(IcoState.ICO == _newState || IcoState.FAILED == _newState); } else if (IcoState.DISTRIBUTING_BONUSES == m_state) { assert(IcoState.SUCCEEDED == _newState); } else assert(false); m_state = _newState; StateChanged(m_state); // this should be tightly linked if (IcoState.SUCCEEDED == m_state) { onSuccess(); } else if (IcoState.FAILED == m_state) { onFailure(); } } function onSuccess() private { // mint tokens for owners uint tokensForTeam = m_token.totalSupply().mul(40).div(60); m_token.mint(m_teamTokens, tokensForTeam); m_funds.changeState(FundsRegistry.State.SUCCEEDED); m_funds.detachController(); m_token.disableMinting(); m_token.startCirculation(); m_token.detachController(); } function onFailure() private { m_funds.changeState(FundsRegistry.State.REFUNDING); m_funds.detachController(); } function getLargePaymentBonus(uint payment) private constant returns (uint) { if (payment > 5000 ether) return 20; if (payment > 3000 ether) return 15; if (payment > 1000 ether) return 10; if (payment > 800 ether) return 8; if (payment > 500 ether) return 5; if (payment > 200 ether) return 2; return 0; } /// @dev calculates amount of STQ to which payer of _wei is entitled function calcSTQAmount(uint _wei, uint extraBonus) private constant returns (uint stq, uint timeBonus) { timeBonus = m_bonuses.getBonus(getCurrentTime()); uint bonus = extraBonus.add(timeBonus).add(getLargePaymentBonus(_wei)); // apply bonus stq = _wei.mul(c_STQperETH).mul(bonus.add(100)).div(100); } /// @dev records investments in a circular buffer function recordInvestment(address investor, uint payment, uint timeBonus) private { uint writeTo; assert(m_lastInvestments.length <= getLastMaxInvestments()); if (m_lastInvestments.length < getLastMaxInvestments()) { // buffer is still expanding writeTo = m_lastInvestments.length++; } else { // reusing buffer writeTo = m_nextFreeLastInvestmentIndex++; if (m_nextFreeLastInvestmentIndex == m_lastInvestments.length) m_nextFreeLastInvestmentIndex = 0; } assert(writeTo < m_lastInvestments.length); m_lastInvestments[writeTo] = LastInvestment(investor, payment, timeBonus); } /// @dev start time of the ICO, inclusive function getStartTime() private constant returns (uint) { return c_startTime; } /// @dev end time of the ICO, inclusive function getEndTime() private constant returns (uint) { return m_bonuses.getLastTime(); } /// @dev to be overridden in tests function getCurrentTime() internal constant returns (uint) { return now; } /// @dev to be overridden in tests function getMinFunds() internal constant returns (uint) { return c_MinFunds; } /// @dev to be overridden in tests function getMaximumFunds() internal constant returns (uint) { return c_MaximumFunds; } /// @dev amount of investments during all crowdsales function getTotalInvested() internal constant returns (uint) { return m_funds.totalInvested().add(4426 ether /* FIXME update me */); } /// @dev to be overridden in tests function getLastMaxInvestments() internal constant returns (uint) { return c_maxLastInvestments; } // FIELDS /// @notice starting exchange rate of STQ uint public constant c_STQperETH = 100000; /// @notice minimum investment uint public constant c_MinInvestment = 10 finney; /// @notice minimum investments to consider ICO as a success uint public constant c_MinFunds = 30000 ether; /// @notice maximum investments to be accepted during ICO uint public constant c_MaximumFunds = 90000 ether; /// @notice start time of the ICO uint public constant c_startTime = 1508889600; /// @notice authorised payment bonus uint public constant c_paymentChannelBonusPercent = 2; /// @notice timed bonuses FixedTimeBonuses.Data m_bonuses; uint public constant c_maxLastInvestments = 100; uint public constant c_lastInvestmentsBonus = 30; /// @dev bookkeeping for last investment bonus LastInvestment[] public m_lastInvestments; uint m_nextFreeLastInvestmentIndex; uint m_nextUndestributedBonusIndex; /// @dev state of the ICO IcoState public m_state = IcoState.INIT; /// @dev contract responsible for token accounting STQToken public m_token; address public m_teamTokens; address public deployer; /// @dev contract responsible for investments accounting FundsRegistry public m_funds; /// @dev last recorded funds uint256 public m_lastFundsAmount; }
to be overridden in tests
function getLastMaxInvestments() internal constant returns (uint) { return c_maxLastInvestments; }
12,662,746
./full_match/73799/0xE50cFFc7F39D233F5627986D4C92B9Bb3625cDf4/sources/contracts/stability-pool.sol
if the deadline was not set it is set to NOW - as the swap will happen in the same block it will be soon enough the swap must yield at least 1 coin (in ETH parlance: 1 Wei) more than what was put in and the TX has 10 minutes to execute increase P by the arbitrage gain / total deposit
function arbitrage( uint256 _amountIn, address[] calldata _path, uint256 deadline ) public { require(_path[0] == address(stableCoin), "eafe8 must start with stable coin"); require(_path[_path.length - 1] == address(stableCoin), "eafe8 must end with stable coin"); deadline = deadline > 0 ? deadline : block.timestamp; uint256 startBalance = stableCoin.balanceOf(address(this)); router.swapExactTokensForTokens(_amountIn, _amountIn + 1, _path, address(this), deadline); uint256 amountOut = stableCoin.balanceOf(address(this)) - startBalance; _updateP((amountOut * DECIMAL_PRECISION) / totalDeposit, false); emit Arbitrage(_path, _amountIn, amountOut); }
16,363,772
/** *Submitted for verification at Etherscan.io on 2020-07-17 */ pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT /** * @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 /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered 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 /** * @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 /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT /** * @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 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ 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 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; } } // SPDX-License-Identifier: MIT /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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 (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS // 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 /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (block.timestamp != 0) { // Equivalent to contains(set, value) //injected CONTRACT AFFECTED BY MINERS // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT /** * @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 (block.number == 0) { // Equivalent to !contains(map, key) //injected CONTRACT AFFECTED BY MINERS 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 (block.timestamp != 0) { // Equivalent to contains(map, key) //injected CONTRACT AFFECTED BY MINERS // 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 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) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ 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(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(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(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // SPDX-License-Identifier: MIT /** * @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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT /** * @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 ^ 0xe985e9c ^ 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 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 override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, 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 returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view 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 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 = 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 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 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 mecanisms 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 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 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`. * * 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 = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (block.timestamp != 0) { //injected CONTRACT AFFECTED BY MINERS 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(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); _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); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, 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` 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 { } } // SPDX-License-Identifier: MIT /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } interface IDSSRegistry { event Resolve(uint256 indexed tokenId, address indexed to); function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); /** * @dev Sets the resolver of a given token ID to another address. * Requires the msg.sender to be the owner, approved, or operator. * @param to address the given token ID will resolve to * @param tokenId uint256 ID of the token to be transferred */ function resolveTo(address to, uint256 tokenId) external; /** * @dev Gets the resolver of the specified token ID. * @param tokenId uint256 ID of the token to query the resolver of * @return address currently marked as the resolver of the given token ID */ function resolverOf(uint256 tokenId) external view returns (address); function mint(address to,bytes32 extensionHash,string calldata uri,string calldata label) external; function mintMany(address[] calldata to,bytes32 extensionHash,string[] calldata uris,string[] calldata labels) external; function setResolver(address resolver) external; function getTokenExtensionHash(uint256 tokenId) external view returns(bytes32); } // SPDX-License-Identifier: MIT /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } contract Controller is AccessControl { bytes32 public constant ADMIN_ROLE = keccak256("admin"); modifier onlyAdmin { require(hasRole(ADMIN_ROLE, msg.sender) || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not admin"); _; } } // SPDX-License-Identifier: MIT /** * @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); } } contract DSSExtensionCreator is Controller { using Counters for Counters.Counter; struct Extension { mapping(address => bool) extensionMinters; mapping(address => bool) extensionSuperAdmins; Counters.Counter totalSU; string extension; bool added; } mapping(bytes32 => Extension) internal extensions; event ExtensionCreated(address indexed owner,bytes32 extensionHash,string extension); event AdminAdded(address indexed addr,bytes32 indexed extensionHash,string extension,bool indexed su); event AdminRemoved(address indexed addr,bytes32 indexed extensionHash,string extension,bool indexed su); modifier onlyExtensionMinter(bytes32 extensionHash) { require(extensions[extensionHash].extensionMinters[msg.sender], "Sender is not allowed to mint token from that extension"); _; } modifier onlyExtensionSuperAdmin(bytes32 extensionHash) { require(extensions[extensionHash].extensionSuperAdmins[msg.sender], "Sender is not super admin of that extension"); _; } constructor() public { _setupRole(DEFAULT_ADMIN_ROLE,msg.sender); } function createExtension(string memory extension) public onlyAdmin { bytes32 extensionHash = keccak256(abi.encodePacked(extension)); require(!_isExtensionUsed(extensionHash), "Extension already used"); _addSuperAdminRole(extensionHash,msg.sender); _addMinter(extensionHash,msg.sender); extensions[extensionHash].extension = extension; extensions[extensionHash].added = true; emit ExtensionCreated(msg.sender,extensionHash,extension); } function createExtensions(string[] memory exts) public onlyAdmin { for(uint256 i = 0;i<exts.length; i++){ createExtension(exts[i]); } } function addMinter(bytes32 extensionHash,address minter) public onlyExtensionSuperAdmin(extensionHash) { require(!extensions[extensionHash].extensionMinters[minter], "Address is minter of that extension"); _addMinter(extensionHash,minter); } function removeMinter(bytes32 extensionHash,address minter) public onlyExtensionSuperAdmin(extensionHash) { require(extensions[extensionHash].extensionMinters[minter], "Address is not minter of that extension"); _removeMinter(extensionHash,minter); } function renounceMinterRole(bytes32 extensionHash) public onlyExtensionMinter(extensionHash) { _removeMinter(extensionHash,msg.sender); } function addSuperAdminRole(bytes32 extensionHash,address admin) public onlyExtensionSuperAdmin(extensionHash) { require(extensions[extensionHash].extensionSuperAdmins[msg.sender], "Address is already super admin of that extension"); _addSuperAdminRole(extensionHash,admin); } function renounceSuperAdminRole(bytes32 extensionHash) public onlyExtensionSuperAdmin(extensionHash) { _renounceSuperAdminRole(extensionHash); } function transferSuperAdminRole(bytes32 extensionHash,address admin) public onlyExtensionSuperAdmin(extensionHash) { _addSuperAdminRole(extensionHash,admin); _renounceSuperAdminRole(extensionHash); } function getExtensionName(bytes32 extensionHash) public view returns(string memory){ return(extensions[extensionHash].extension); } function _isExtensionUsed(bytes32 extensionHash) private view returns(bool){ return(extensions[extensionHash].added); } function _addMinter(bytes32 extensionHash,address minter) private { extensions[extensionHash].extensionMinters[minter] = true; emit AdminAdded(minter,extensionHash,getExtensionName(extensionHash),false); } function _removeMinter(bytes32 extensionHash,address minter) private { extensions[extensionHash].extensionMinters[minter] = false; emit AdminRemoved(minter,extensionHash,getExtensionName(extensionHash),false); } function _addSuperAdminRole(bytes32 extensionHash,address admin) private { extensions[extensionHash].totalSU.increment(); extensions[extensionHash].extensionSuperAdmins[admin] = true; emit AdminAdded(admin,extensionHash,getExtensionName(extensionHash),true); } function _renounceSuperAdminRole(bytes32 extensionHash) private { require(extensions[extensionHash].totalSU.current() > 1, "Can not leave extension without any super admin"); extensions[extensionHash].totalSU.decrement(); extensions[extensionHash].extensionSuperAdmins[msg.sender] = false; if(extensions[extensionHash].extensionMinters[msg.sender]){ _removeMinter(extensionHash,msg.sender); } emit AdminRemoved(msg.sender,extensionHash,getExtensionName(extensionHash),true); } function isExtensionMinter(bytes32 extensionHash,address addr) public view returns(bool) { return(extensions[extensionHash].extensionMinters[addr]); } function isExtensionSuperAdmin(bytes32 extensionHash,address addr) public view returns(bool) { return(extensions[extensionHash].extensionSuperAdmins[addr]); } } /** * @title DSSRegistry * @dev An ERC721 Token see https://eips.ethereum.org/EIPS/eip-721. */ contract DSSRegistry is DSSExtensionCreator,IDSSRegistry,ERC721Burnable { mapping (uint256 => address) internal _tokenResolvers; mapping(uint256 => bytes32) internal _tokenExtension; mapping(bytes32 => mapping(bytes32 => bool)) internal _labelUsed; Counters.Counter private _tokenIds; // keccak256(abi.encodePacked(uint256(0x0), keccak256(abi.encodePacked("blockchains-domain")))) bytes32 public DSS_HASH; address public RESOLVER_ADDRESS; event ResolverDefined(address resolver); event Minted(address from,address indexed to,bytes32 indexed extensionHash, string extension,bytes32 indexed labelHash,string label, uint256 tokenId); modifier onlyApprovedOrOwner(uint256 tokenId) { require(_isApprovedOrOwner(msg.sender, tokenId)); _; } constructor(string memory name, string memory symbol) ERC721(name, symbol) public { _setBaseURI("ipfs://ipfs/"); _setupRole(DEFAULT_ADMIN_ROLE,msg.sender); DSS_HASH = keccak256(abi.encodePacked(uint256(0x0), keccak256(abi.encodePacked(name)))); } /// Ownership function isApprovedOrOwner(address spender, uint256 tokenId) external override view returns (bool) { return _isApprovedOrOwner(spender, tokenId); } /// Minting function mint(address to,bytes32 extensionHash,string memory uri,string memory label) public override onlyExtensionMinter(extensionHash) { bytes32 hashLabel = keccak256(abi.encodePacked(label)); require(extensions[extensionHash].added,"Extension was not created yet"); require(!_labelUsed[extensionHash][hashLabel],"Domain already registered"); require(uint256(RESOLVER_ADDRESS) != 0,"Need to set default resolver address to be able to mint"); _tokenIds.increment(); uint256 newItemId = uint256(keccak256(abi.encodePacked(uint256(_tokenIds.current()), keccak256(abi.encodePacked("blockchains-domains"))))); _mint(to, newItemId); _setTokenURI(newItemId, uri); _resolveTo(RESOLVER_ADDRESS,newItemId); _labelUsed[extensionHash][hashLabel] = true; _tokenExtension[newItemId] = extensionHash; emit Minted(msg.sender,to,extensionHash,getExtensionName(extensionHash),hashLabel,label,newItemId); } function mintMany(address[] memory to,bytes32 extensionHash,string[] memory uris,string[] memory labels) public override onlyExtensionMinter(extensionHash){ for (uint256 i = 0; i < uris.length; i++) { mint(to[i],extensionHash,uris[i],labels[i]); } } // Transfer function transferFrom(address from, address to, uint256 tokenId) public virtual override(ERC721) { _resetResolver(tokenId); super.transferFrom(from,to,tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override(ERC721) { _resetResolver(tokenId); super.safeTransferFrom(from,to,tokenId); } // Burning function burn(uint256 tokenId) public virtual override onlyApprovedOrOwner(tokenId) { super.burn(tokenId); // Clear resolver (if any) if (block.coinbase != address(0x0)) { //injected CONTRACT AFFECTED BY MINERS delete _tokenResolvers[tokenId]; } } // Get extension function getTokenExtensionHash(uint256 tokenId) public view override returns(bytes32){ return(_tokenExtension[tokenId]); } /// Resolution function setResolver(address resolver) public override { require(hasRole(DEFAULT_ADMIN_ROLE,msg.sender),"Sender must be super admin"); RESOLVER_ADDRESS = resolver; emit ResolverDefined(resolver); } function resolverOf(uint256 tokenId) external override view returns (address) { return(_tokenResolvers[tokenId]); } function resolveTo(address to, uint256 tokenId) external override onlyApprovedOrOwner(tokenId) { _resolveTo(to, tokenId); } function _resolveTo(address to, uint256 tokenId) private { require(_exists(tokenId)); emit Resolve(tokenId, to); _tokenResolvers[tokenId] = to; } function _resetResolver(uint256 tokenId) private { Resolver resolver = Resolver(RESOLVER_ADDRESS); resolver.reset(tokenId); } } contract Resolver { DSSRegistry internal _registry; event Set(uint256 indexed preset, string indexed key, string value, uint256 indexed tokenId); event SetPreset(uint256 indexed preset, uint256 indexed tokenId); // Mapping from token ID to preset id to key to value mapping (uint256 => mapping (uint256 => mapping (string => string))) internal _records; // Mapping from token ID to current preset id mapping (uint256 => uint256) _tokenPresets; constructor(DSSRegistry registry) public { _registry = registry; } function registry() external view returns (address) { return address(_registry); } /** * @dev Throws if called when not the resolver. */ modifier whenResolver(uint256 tokenId) { require(address(this) == _registry.resolverOf(tokenId), "Resolver: is not the resolver"); _; } function presetOf(uint256 tokenId) external view returns (uint256) { return _tokenPresets[tokenId]; } function reset(uint256 tokenId) external { require(_registry.isApprovedOrOwner(msg.sender, tokenId) || msg.sender == address(_registry), "Not aproved, owner or ERC721 contract to reset presets"); _setPreset(now, tokenId); } /** * @dev Function to get record. * @param key The key to query the value of. * @param tokenId The token id to fetch. * @return The value string. */ function get(string memory key, uint256 tokenId) public view whenResolver(tokenId) returns (string memory) { return _records[tokenId][_tokenPresets[tokenId]][key]; } /** * @dev Function to get multiple record. * @param keys The keys to query the value of. * @param tokenId The token id to fetch. * @return The values. */ function getMany(string[] calldata keys, uint256 tokenId) external view whenResolver(tokenId) returns (string[] memory) { uint256 keyCount = keys.length; string[] memory values = new string[](keyCount); uint256 preset = _tokenPresets[tokenId]; for (uint256 i = 0; i < keyCount; i++) { values[i] = _records[tokenId][preset][keys[i]]; } return values; } function setMany( string[] memory keys, string[] memory values, uint256 tokenId ) public { require(_registry.isApprovedOrOwner(msg.sender, tokenId)); _setMany(_tokenPresets[tokenId], keys, values, tokenId); } function _setPreset(uint256 presetId, uint256 tokenId) internal { _tokenPresets[tokenId] = presetId; emit SetPreset(presetId, tokenId); } /** * @dev Internal function to to set record. As opposed to set, this imposes * no restrictions on msg.sender. * @param preset preset to set key/values on * @param key key of record to be set * @param value value of record to be set * @param tokenId uint256 ID of the token */ function _set(uint256 preset, string memory key, string memory value, uint256 tokenId) internal { _records[tokenId][preset][key] = value; emit Set(preset, key, value, tokenId); } /** * @dev Internal function to to set multiple records. As opposed to setMany, this imposes * no restrictions on msg.sender. * @param preset preset to set key/values on * @param keys keys of record to be set * @param values values of record to be set * @param tokenId uint256 ID of the token */ function _setMany(uint256 preset, string[] memory keys, string[] memory values, uint256 tokenId) internal { uint256 keyCount = keys.length; for (uint256 i = 0; i < keyCount; i++) { _set(preset, keys[i], values[i], tokenId); } } } contract DSSResolver is Resolver { // Mapping from tokenId to token presets to key hash to address authorized to set key value mapping(uint256 => mapping(uint256 => mapping(bytes32 => address))) internal authorized; event Authorized(address indexed authorized,bytes32 indexed keyHash,string key); constructor(DSSRegistry registry) public Resolver(registry){ } /** * @dev Function to set record. * @param key The key set the value of. * @param value The value to set key to. * @param tokenId The token id to set. */ function set(string calldata key, string calldata value, uint256 tokenId) external { bytes32 keyHash = keccak256(abi.encodePacked(key)); require(_registry.isApprovedOrOwner(msg.sender, tokenId) || msg.sender == authorized[tokenId][_tokenPresets[tokenId]][keyHash], "Sender is not authorized to change value of that key"); _set(_tokenPresets[tokenId], key, value, tokenId); } /** * @dev Function to authorize address to change specific record's key. * To remove allowance token's owner must authorize for his wallet address or '0x0000000000000000000000000000000000000000'. * @param key The key allowed to be changed. * @param tokenId The token id to set. * @param target Wallet address allowed to change key's value */ function authorize(string memory key,uint256 tokenId,address target) public { require(_registry.isApprovedOrOwner(msg.sender, tokenId), "Sender is not authorized to change value of that key"); bytes32 keyHash = keccak256(abi.encodePacked(key)); require(authorized[tokenId][_tokenPresets[tokenId]][keyHash] != target, "Target address is already authorized to change that key value"); authorized[tokenId][_tokenPresets[tokenId]][keyHash] = target; Authorized(target,keyHash,key); } }
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 mecanisms 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"); }
987,587
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol pragma solidity ^0.4.24; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol pragma solidity ^0.4.24; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * 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(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/base/MintableToken.sol pragma solidity ^0.4.24; /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { return _mint(_to, _amount); } /** * @dev Internal 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 ) internal returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/lifecycle/Destructible.sol pragma solidity ^0.4.24; /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() public onlyOwner { selfdestruct(owner); } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol pragma solidity ^0.4.24; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol pragma solidity ^0.4.24; /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-solidity/contracts/access/rbac/Roles.sol pragma solidity ^0.4.24; /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage _role, address _addr) internal { _role.bearer[_addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage _role, address _addr) internal { _role.bearer[_addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage _role, address _addr) internal view { require(has(_role, _addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage _role, address _addr) internal view returns (bool) { return _role.bearer[_addr]; } } // File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol pragma solidity ^0.4.24; /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) public view { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) public view returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } // File: openzeppelin-solidity/contracts/access/Whitelist.sol pragma solidity ^0.4.24; /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) public onlyOwner { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) public onlyOwner { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } // File: openzeppelin-solidity/contracts/ECRecovery.sol pragma solidity ^0.4.24; /** * @title Elliptic curve signature operations * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param _hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param _sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 _hash, bytes _sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (_sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) v := byte(0, mload(add(_sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * and hash the result */ function toEthSignedMessageHash(bytes32 _hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash) ); } } // File: contracts/SilverToken.sol pragma solidity ^0.4.24; interface ASilverDollar { function purchaseWithSilverToken(address, uint256) external returns(bool); } contract SilverToken is Destructible, Pausable, MintableToken, BurnableToken, DetailedERC20("Silvertoken", "SLVT", 8), Whitelist { using SafeMath for uint256; using ECRecovery for bytes32; uint256 public transferFee = 10;//1% uint256 public transferDiscountFee = 8;//0.8% uint256 public redemptionFee = 40;//4% uint256 public convertFee = 10;//1% address public feeReturnAddress = 0xE34f13B2dadC938f44eCbC38A8dBe94B8bdB2109; uint256 public transferFreeAmount; uint256 public transferDiscountAmount; address public silverDollarAddress; address public SLVTReserve = 0x900122447a2Eaeb1655C99A91E20f506D509711B; bool public canPurchase = true; bool public canConvert = true; // Internal features uint256 internal multiplier; uint256 internal percentage = 1000; //ce4385affa8ad2cbec45b1660c6f6afcb691bf0a7a73ebda096ee1dfb670fe6f event TokenRedeemed(address from, uint256 amount); //3ceffd410054fdaed44f598ff5c1fb450658778e2241892da4aa646979dee617 event TokenPurchased(address addr, uint256 amount, uint256 tokens); //5a56a31cc0c9ebf5d0626c5189b951fe367d953afc1824a8bb82bf168713cc52 event FeeApplied(string name, address addr, uint256 amount); event Converted(address indexed sender, uint256 amountSLVT, uint256 amountSLVD, uint256 amountFee); modifier purchasable() { require(canPurchase == true, "can't purchase"); _; } modifier onlySilverDollar() { require(msg.sender == silverDollarAddress, "not silverDollar"); _; } modifier isConvertible() { require(canConvert == true, "SLVT conversion disabled"); _; } constructor () public { multiplier = 10 ** uint256(decimals); transferFreeAmount = 2 * multiplier; transferDiscountAmount = 500 * multiplier; owner = msg.sender; super.mint(msg.sender, 1 * 1000 * 1000 * multiplier); } // Settings begin function setTransferFreeAmount(uint256 value) public onlyOwner { transferFreeAmount = value; } function setTransferDiscountAmount(uint256 value) public onlyOwner { transferDiscountAmount = value; } function setRedemptionFee(uint256 value) public onlyOwner { redemptionFee = value; } function setFeeReturnAddress(address value) public onlyOwner { feeReturnAddress = value; } function setCanPurchase(bool value) public onlyOwner { canPurchase = value; } function setSilverDollarAddress(address value) public onlyOwner { silverDollarAddress = value; } function setCanConvert(bool value) public onlyOwner { canConvert = value; } function setConvertFee(uint256 value) public onlyOwner { convertFee = value; } function increaseTotalSupply(uint256 value) public onlyOwner returns (uint256) { super.mint(owner, value); return totalSupply_; } // Settings end // ERC20 re-implementation methods begin function transfer(address to, uint256 amount) public whenNotPaused returns (bool) { uint256 feesPaid = payFees(address(0), to, amount); require(super.transfer(to, amount.sub(feesPaid)), "failed transfer"); return true; } function transferFrom(address from, address to, uint256 amount) public whenNotPaused returns (bool) { uint256 feesPaid = payFees(from, to, amount); require(super.transferFrom(from, to, amount.sub(feesPaid)), "failed transferFrom"); return true; } // ERC20 re-implementation methods end // Silvertoken methods end function payFees(address from, address to, uint256 amount) private returns (uint256 fees) { if (msg.sender == owner || hasRole(from, ROLE_WHITELISTED) || hasRole(msg.sender, ROLE_WHITELISTED) || hasRole(to, ROLE_WHITELISTED)) return 0; fees = getTransferFee(amount); if (from == address(0)) { require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed"); } else { require(super.transferFrom(from, feeReturnAddress, fees), "transferFrom fee payment failed"); } emit FeeApplied("Transfer", to, fees); } function getTransferFee(uint256 amount) internal view returns(uint256) { if (transferFreeAmount > 0 && amount <= transferFreeAmount) return 0; if (transferDiscountAmount > 0 && amount >= transferDiscountAmount) return amount.mul(transferDiscountFee).div(percentage); return amount.mul(transferFee).div(percentage); } function transferTokens(address from, address to, uint256 amount) internal returns (bool) { require(balances[from] >= amount, "balance insufficient"); balances[from] = balances[from].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(from, to, amount); return true; } function purchase(uint256 tokens, uint256 fee, uint256 timestamp, bytes signature) public payable purchasable whenNotPaused { require( isSignatureValid( msg.sender, msg.value, tokens, fee, timestamp, signature ), "invalid signature" ); require(tokens > 0, "invalid number of tokens"); emit TokenPurchased(msg.sender, msg.value, tokens); transferTokens(owner, msg.sender, tokens); feeReturnAddress.transfer(msg.value); if (fee > 0) { emit FeeApplied("Purchase", msg.sender, fee); } } function purchasedSilverDollar(uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) { require(super._mint(SLVTReserve, amount), "minting of slvT failed"); return true; } function purchaseWithSilverDollar(address to, uint256 amount) public onlySilverDollar purchasable whenNotPaused returns (bool) { require(transferTokens(SLVTReserve, to, amount), "failed transfer of slvT from reserve"); return true; } function redeem(uint256 tokens) public whenNotPaused { require(tokens > 0, "amount of tokens redeemed must be > 0"); uint256 fee = tokens.mul(redemptionFee).div(percentage); _burn(msg.sender, tokens.sub(fee)); if (fee > 0) { require(super.transfer(feeReturnAddress, fee), "token transfer failed"); emit FeeApplied("Redeem", msg.sender, fee); } emit TokenRedeemed(msg.sender, tokens); } function isSignatureValid( address sender, uint256 amount, uint256 tokens, uint256 fee, uint256 timestamp, bytes signature ) public view returns (bool) { if (block.timestamp > timestamp + 10 minutes) return false; bytes32 hash = keccak256( abi.encodePacked( address(this), sender, amount, tokens, fee, timestamp ) ); return hash.toEthSignedMessageHash().recover(signature) == owner; } function isConvertSignatureValid( address sender, uint256 amountSLVT, uint256 amountSLVD, uint256 timestamp, bytes signature ) public view returns (bool) { if (block.timestamp > timestamp + 10 minutes) return false; bytes32 hash = keccak256( abi.encodePacked( address(this), sender, amountSLVT, amountSLVD, timestamp ) ); return hash.toEthSignedMessageHash().recover(signature) == owner; } function convertToSLVD( uint256 amountSLVT, uint256 amountSLVD, uint256 timestamp, bytes signature ) public isConvertible whenNotPaused returns (bool) { require( isConvertSignatureValid( msg.sender, amountSLVT, amountSLVD, timestamp, signature ), "convert failed, invalid signature" ); uint256 fees = amountSLVT.mul(convertFee).div(percentage); if (whitelist(msg.sender) && Whitelist(silverDollarAddress).whitelist(msg.sender)) fees = 0; super.transfer(SLVTReserve, amountSLVT.sub(fees)); require(super.transfer(feeReturnAddress, fees), "transfer fee payment failed"); require( ASilverDollar(silverDollarAddress).purchaseWithSilverToken(msg.sender, amountSLVD), "failed purchase of silverdollar with silvertoken" ); emit Converted(msg.sender, amountSLVD, amountSLVD, fees); return true; } }
add addresses to the whitelist _operators addresses return true if at least one address was added to the whitelist, false if all addresses were already in the whitelist/
function addAddressesToWhitelist(address[] _operators) public onlyOwner { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } }
969,429
./full_match/5/0x2A2c52bC0294656fD12bd23ceCe66bd3f539E2A9/sources/project_/contracts/InvasionMars.sol
... Rest of the contract code ...
function calculateMarketingFee(uint256 amount) public view returns (uint256) { return amount * BUY_TAX_PERCENT / 100; }
1,851,843
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import "./interfaces/IMySpace.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IBlackListAgent.sol"; import "./libraries/SafeMath256.sol"; contract SpaceLogic is IERC20, IMySpace { using SafeMath256 for uint; struct AdInfo { address coinType; uint64 endTime; uint numAudience; uint coinsPerAudience; } address private owner; address private chirp; address private voteCoin; uint private warmupTime; uint64 public nextThreadId; uint64 public nextVoteId; uint64 public nextAdId; address private blackListAgent; mapping(address => uint64/*timestamp*/) immatureFollowerTable; mapping(address => bool) followerTable; //accountName in blackList cannot be follower, if it already be, remove it mapping(bytes32 => bool) blackList; //voteConfig: 8bit, lsb represents if one vote only one ticket, silence vote coinAmount param; mapping(uint64/*vote id*/ => uint /*64bit end time | 8bit voteConfig | 8bit optionCount*/) voteTable; //no need hash mapping(bytes32 => uint) voteTallyTable; mapping(uint64/*ad id*/ => AdInfo) adTable; mapping(uint64 => mapping(address => bool)) adCoinReceivers; bool public coinLock; string private _name; uint8 private _decimal; string public _symbol; uint256 public _totalSupply; mapping(address => uint) public _balanceOf; mapping(address => mapping(address => uint)) public _allowance; function initCoin(string coinName, string coinSymbol, uint8 coinDecimal, uint initSupply) external { require(coinLock != true && msg.sender == owner); coinLock = true; _name = coinName; _symbol = coinSymbol; _decimal = coinDecimal; _totalSupply = initSupply; _balanceOf[owner] = initSupply; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function decimals() external view override returns (uint8) { return _decimal; } function _mint(address to, uint value) internal { _totalSupply = _totalSupply.add(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { _balanceOf[from] = _balanceOf[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address _owner, address spender, uint value) private { _allowance[_owner][spender] = value; emit Approval(_owner, spender, value); } function _transfer(address from, address to, uint value) private { _balanceOf[from] = _balanceOf[from].sub(value); _balanceOf[to] = _balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (_allowance[from][msg.sender] != uint256(2 ^ 256 - 1)) { _allowance[from][msg.sender] = _allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function mint(uint amount) external { require(msg.sender == owner); _totalSupply += amount; _balanceOf[owner] += amount; } function totalSupply() external view override returns (uint) { return _totalSupply; } function balanceOf(address _owner) external view override returns (uint) { return _balanceOf[_owner]; } function allowance(address _owner, address spender) external view override returns (uint) { return _allowance[_owner][spender]; } //todo: only call by register, when change owner function switchToNewOwner(address _owner) external override { require(msg.sender == chirp); owner = _owner; } // Get the owner of this contract function getOwner() external view override returns (address) { return owner; } // Add the accounts in badIdList into blacklist. operator-only. function addToBlacklist(bytes32[] calldata badIdList) external override { require(msg.sender == owner); for (uint i = 0; i < badIdList.length; i++) { bytes32 acc = badIdList[i]; if (blackList[acc] != true) { blackList[acc] = true; address _owner = IRegistry(chirp).getOwnerByAccountName(acc); delete immatureFollowerTable[_owner]; delete followerTable[_owner]; } } } // Remove the accounts in goodIdList from blacklist. owner-only. function removeFromBlacklist(bytes32[] calldata goodIdList) external override { require(msg.sender == owner); for (uint i = 0; i < goodIdList.length; i++) { delete blackList[goodIdList[i]]; } } // Add another contract as blacklist agent. owner-only. function addBlacklistAgent(address agent) external override { require(msg.sender == owner); blackListAgent = agent; } // Stop taking another contract as blacklist agent. owner-only. //todo: only support one agent now; function removeBlacklistAgent() external override { require(msg.sender == owner); blackListAgent = address(0); } // Query wether an acc is in the black list function isInBlacklist(bytes32 accountName) public override returns (bool) { return blackList[accountName] || (blackListAgent != address(0) && IBlackListAgent(blackListAgent).isInBlacklist(accountName)); } // Create a new thread. Only the owner can call this function. Returns the new thread's id function createNewThread(bytes memory content, bytes32[] calldata notifyList) external override returns (uint64) { require(msg.sender == owner); uint64 threadId = nextThreadId; emit NewThread(threadId, content); uint length = notifyList.length; for (uint i = 0; i < (length + 1) / 2; i++) { if (2 * i + 1 == length) { emit Notify(threadId, notifyList[2 * i], bytes32("")); } else { emit Notify(threadId, notifyList[2 * i], notifyList[2 * i + 1]); } } nextThreadId++; return threadId; } // Add a comment under a thread. Only the owner and the followers can call this function function comment(uint64 threadId, bytes memory content, address rewardTo, uint rewardAmount, address rewardCoin) external override { require(msg.sender == owner || isFollower(msg.sender)); if (threadId < nextThreadId) { //todo: not check transfer result IERC20(rewardCoin).transferFrom(msg.sender, rewardTo, rewardAmount); emit NewComment(threadId, msg.sender, content, rewardTo, rewardAmount, rewardCoin); } } // Returns the Id of the next thread function getNextThreadId() external view override returns (uint64) { return nextThreadId; } // Follow this contract's owner. function follow() external override { require(followerTable[msg.sender] != true); bytes32 acc = IRegistry(chirp).getAccountNameByOwner(msg.sender); require(!isInBlacklist(acc)); immatureFollowerTable[msg.sender] = uint64(block.timestamp); } // Unfollow this contract's owner. function unfollow() external override { delete immatureFollowerTable[msg.sender]; delete followerTable[msg.sender]; } // Query all the followers, with paging support. // function getFollowers(uint start, uint count) external override returns (bytes32[] memory) { // return bytes32[](0); // } // Set the warmup time for new followers: how many hours after becoming a follower can she comment? owner-only //change numHours to numSeconds function setWarmupTime(uint numSeconds) external override { require(msg.sender == owner && numSeconds != 0); warmupTime = numSeconds; } // Query the warmup time for new followers function getWarmupTime() external view override returns (uint) { return warmupTime; } // Start a new vote. owner-only. Can delete an old vote to save gas. function startVote(string memory detail, uint8 optionCount, uint8 voteConfig, uint endTime, uint64 deleteOldId) external override returns (uint64) { require(msg.sender == owner && endTime > block.timestamp); uint64 voteId = nextVoteId; if (deleteOldId < voteId) { //todo: deleteOldId may not end uint info = voteTable[deleteOldId]; uint8 _optionCount = uint8(info); if (_optionCount != 0) { for (uint8 i = 0; i < _optionCount; i++) { delete voteTallyTable[keccak256(abi.encode(deleteOldId << 8 | i))]; } } delete voteTable[deleteOldId]; } voteTable[voteId] = endTime << 16 | voteConfig << 8 | optionCount; emit StartVote(voteId, detail, optionCount, endTime); nextVoteId++; return voteId; } // Vote for an option. followers-only. //todo: optionId should be [0,optionCount) function vote(uint64 voteId, uint8 optionId, uint coinAmount) external override { require(isFollower(msg.sender)); uint info = voteTable[voteId]; uint64 endTime = uint64(info >> 16); uint8 config = uint8(info >> 8); uint8 optionCount = uint8(info); if (endTime != 0 && block.timestamp < endTime && optionId < optionCount) { //not like a on chain gov vote, pay coins is not refund to user, voteCoin may be address zero always; if ((config & 0x01 == 0x01) || voteCoin == address(0)) { voteTallyTable[keccak256(abi.encode(voteId << 8 | optionId))] += 1; emit Vote(msg.sender, voteId, optionId, 1); } else if (IERC20(voteCoin).transferFrom(msg.sender, owner, coinAmount)) { voteTallyTable[keccak256(abi.encode(voteId << 8 | optionId))] += coinAmount; emit Vote(msg.sender, voteId, optionId, coinAmount); } } } // Return the amounts of voted coins for each option. function getVoteResult(uint64 voteId) external view override returns (uint[] memory) { uint voteInfo = voteTable[voteId]; //todo: not check if vote is end uint8 optionCount = uint8(voteInfo); require(optionCount != 0); uint[] memory tallyInfo = new uint[](optionCount); for (uint8 i = 0; i < optionCount; i++) { tallyInfo[i] = voteTallyTable[keccak256(abi.encode(voteId << 8 | i))]; } return tallyInfo; } // Returns the Id of the next vote function getNextVoteId() external view override returns (uint64) { return nextVoteId; } // Publish a new Ad. owner-only. Can delete an old Ad to save gas and reclaim coins at the same time. function publishAd(string memory detail, uint numAudience, uint coinsPerAudience, address coinType, uint endTime, uint64 deleteOldId) external override returns (uint64) { //coinType should impl IERC20 require(msg.sender == owner && endTime > block.timestamp && coinType != address(0)); uint64 id = nextAdId; AdInfo memory info; info.coinType = coinType; info.numAudience = numAudience; info.coinsPerAudience = coinsPerAudience; info.endTime = uint64(endTime); adTable[id] = info; //todo: coinType == 0 => native coin require(IERC20(coinType).transferFrom(msg.sender, address(this), numAudience * coinsPerAudience)); emit PublishAd(id, detail, numAudience, coinsPerAudience, coinType, endTime); if (deleteOldId < id) { AdInfo memory oldInfo = adTable[deleteOldId]; if (oldInfo.endTime != 0) { //not check if old ad if end or not delete adTable[deleteOldId]; //not check result IERC20(oldInfo.coinType).transfer(msg.sender, oldInfo.coinsPerAudience * oldInfo.numAudience); } } nextAdId++; return id; } // Click an Ad and express whether I am interested. followers-only function clickAd(uint id, bool interested) external override { require(isFollower(msg.sender)); AdInfo memory info = adTable[uint64(id)]; require(info.endTime > block.timestamp); if (!interested && info.numAudience > 0) { IERC20(info.coinType).transfer(msg.sender, info.coinsPerAudience); info.numAudience--; adTable[uint64(id)] = info; } emit ClickAd(uint64(id), msg.sender, interested); } // Delete an old Ad to save gas and reclaim coins function deleteAd(uint id) external override { require(msg.sender == owner); AdInfo memory oldInfo = adTable[uint64(id)]; if (oldInfo.endTime != 0) { //not check if old ad if end or not delete adTable[uint64(id)]; //not check result IERC20(oldInfo.coinType).transfer(msg.sender, oldInfo.coinsPerAudience * oldInfo.numAudience); } } // Returns the Id of the next Ad function getNextAdId() external view override returns (uint64) { return nextAdId; } function setVoteCoin(address coin) external { voteCoin = coin; } function getVoteCoin() external view returns (address) { return voteCoin; } function isFollower(address user) internal returns (bool) { bool _isFollower; if (followerTable[user] == true) { _isFollower = true; } else if (immatureFollowerTable[user] + warmupTime > block.timestamp) { _isFollower = true; followerTable[user] = true; delete immatureFollowerTable[user]; } return _isFollower; } } contract Space { address private owner; address private chirp; constructor(address _owner, address _chirp){ owner = _owner; chirp = _chirp; } receive() external payable {} fallback() payable external { address space = IRegistry(chirp).getSpaceLogic(); assembly { let ptr := mload(0x40) let size := calldatasize() calldatacopy(ptr, 0, size) let result := delegatecall(gas(), space, ptr, size, 0, 0) size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } }
Unfollow this contract's owner.
function unfollow() external override { delete immatureFollowerTable[msg.sender]; delete followerTable[msg.sender]; }
7,277,812
pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./SelfServiceAccessControls.sol"; interface IKODAV2SelfServiceEditionCuration { function createActiveEdition( uint256 _editionNumber, bytes32 _editionData, uint256 _editionType, uint256 _startDate, uint256 _endDate, address _artistAccount, uint256 _artistCommission, uint256 _priceInWei, string _tokenUri, uint256 _totalAvailable ) external returns (bool); function artistsEditions(address _artistsAccount) external returns (uint256[1] _editionNumbers); function totalAvailableEdition(uint256 _editionNumber) external returns (uint256); function highestEditionNumber() external returns (uint256); } interface IKODAAuction { function setArtistsControlAddressAndEnabledEdition(uint256 _editionNumber, address _address) external; } // One invocation per time-period contract SelfServiceEditionCurationV3 is Ownable, Pausable { using SafeMath for uint256; event SelfServiceEditionCreated( uint256 indexed _editionNumber, address indexed _creator, uint256 _priceInWei, uint256 _totalAvailable, bool _enableAuction ); // Calling address IKODAV2SelfServiceEditionCuration public kodaV2; IKODAAuction public auction; SelfServiceAccessControls public accessControls; // Default artist commission uint256 public artistCommission = 85; // Config which enforces editions to not be over this size uint256 public maxEditionSize = 100; // Config the minimum price per edition uint256 public minPricePerEdition = 0.01 ether; // frozen out for.. uint256 public freezeWindow = 1 days; // When the current time period started mapping(address => uint256) public frozenTil; /** * @dev Construct a new instance of the contract */ constructor( IKODAV2SelfServiceEditionCuration _kodaV2, IKODAAuction _auction, SelfServiceAccessControls _accessControls ) public { kodaV2 = _kodaV2; auction = _auction; accessControls = _accessControls; } /** * @dev Called by artists, create new edition on the KODA platform */ function createEdition( uint256 _totalAvailable, uint256 _priceInWei, uint256 _startDate, string _tokenUri, bool _enableAuction ) public whenNotPaused returns (uint256 _editionNumber) { require(!_isFrozen(msg.sender), 'Sender currently frozen out of creation'); frozenTil[msg.sender] = block.timestamp.add(freezeWindow); return _createEdition(msg.sender, _totalAvailable, _priceInWei, _startDate, _tokenUri, _enableAuction); } /** * @dev Caller by owner, can create editions for other artists * @dev Only callable from owner regardless of pause state */ function createEditionFor( address _artist, uint256 _totalAvailable, uint256 _priceInWei, uint256 _startDate, string _tokenUri, bool _enableAuction ) public onlyOwner returns (uint256 _editionNumber) { return _createEdition(_artist, _totalAvailable, _priceInWei, _startDate, _tokenUri, _enableAuction); } /** * @dev Internal function for edition creation */ function _createEdition( address _artist, uint256 _totalAvailable, uint256 _priceInWei, uint256 _startDate, string _tokenUri, bool _enableAuction ) internal returns (uint256 _editionNumber){ // Enforce edition size require(_totalAvailable > 0, "Must be at least one available in edition"); require(_totalAvailable <= maxEditionSize, "Must not exceed max edition size"); // Enforce min price require(_priceInWei >= minPricePerEdition, "Price must be greater than minimum"); // If we are the owner, skip this artists check if (msg.sender != owner) { // Enforce who can call this if (!accessControls.openToAllArtist()) { require(accessControls.allowedArtists(_artist), "Only allowed artists can create editions for now"); } } // Find the next edition number we can use uint256 editionNumber = getNextAvailableEditionNumber(); // Attempt to create a new edition require( _createNewEdition(editionNumber, _artist, _totalAvailable, _priceInWei, _startDate, _tokenUri), "Failed to create new edition" ); // Enable the auction if desired if (_enableAuction) { auction.setArtistsControlAddressAndEnabledEdition(editionNumber, _artist); } // Trigger event emit SelfServiceEditionCreated(editionNumber, _artist, _priceInWei, _totalAvailable, _enableAuction); return editionNumber; } /** * @dev Internal function for calling external create methods with some none configurable defaults */ function _createNewEdition( uint256 _editionNumber, address _artist, uint256 _totalAvailable, uint256 _priceInWei, uint256 _startDate, string _tokenUri ) internal returns (bool) { return kodaV2.createActiveEdition( _editionNumber, 0x0, // _editionData - no edition data 1, // _editionType - KODA always type 1 _startDate, 0, // _endDate - 0 = MAX unit256 _artist, artistCommission, _priceInWei, _tokenUri, _totalAvailable ); } /** * @dev Internal function for checking is an account is frozen out yet */ function _isFrozen(address account) internal view returns (bool) { return (block.timestamp < frozenTil[account]); } /** * @dev Internal function for dynamically generating the next KODA edition number */ function getNextAvailableEditionNumber() internal returns (uint256 editionNumber) { // Get current highest edition and total in the edition uint256 highestEditionNumber = kodaV2.highestEditionNumber(); uint256 totalAvailableEdition = kodaV2.totalAvailableEdition(highestEditionNumber); // Add the current highest plus its total, plus 1 as tokens start at 1 not zero uint256 nextAvailableEditionNumber = highestEditionNumber.add(totalAvailableEdition).add(1); // Round up to next 100, 1000 etc based on max allowed size return ((nextAvailableEditionNumber + maxEditionSize - 1) / maxEditionSize) * maxEditionSize; } /** * @dev Sets the KODA address * @dev Only callable from owner */ function setKodavV2(IKODAV2SelfServiceEditionCuration _kodaV2) onlyOwner public { kodaV2 = _kodaV2; } /** * @dev Sets the KODA auction * @dev Only callable from owner */ function setAuction(IKODAAuction _auction) onlyOwner public { auction = _auction; } /** * @dev Sets the default commission for each edition * @dev Only callable from owner */ function setArtistCommission(uint256 _artistCommission) onlyOwner public { artistCommission = _artistCommission; } /** * @dev Sets the max edition size * @dev Only callable from owner */ function setMaxEditionSize(uint256 _maxEditionSize) onlyOwner public { maxEditionSize = _maxEditionSize; } /** * @dev Sets minimum price per edition * @dev Only callable from owner */ function setMinPricePerEdition(uint256 _minPricePerEdition) onlyOwner public { minPricePerEdition = _minPricePerEdition; } /** * @dev Sets freeze window * @dev Only callable from owner */ function setFreezeWindow(uint256 _freezeWindow) onlyOwner public { freezeWindow = _freezeWindow; } /** * @dev Checks to see if the account is currently frozen out */ function isFrozen(address account) public view returns (bool) { return _isFrozen(account); } /** * @dev Checks to see if the account can create editions */ function isEnabledForAccount(address account) public view returns (bool) { return accessControls.isEnabledForAccount(account); } /** * @dev Checks to see if the account can create editions */ function canCreateAnotherEdition(address account) public view returns (bool) { if (!isEnabledForAccount(account)) { return false; } return !_isFrozen(account); } /** * @dev Allows for the ability to extract stuck ether * @dev Only callable from owner */ function withdrawStuckEther(address _withdrawalAccount) onlyOwner public { require(_withdrawalAccount != address(0), "Invalid address provided"); _withdrawalAccount.transfer(address(this).balance); } }
Sets the KODA auction Only callable from owner/
function setAuction(IKODAAuction _auction) onlyOwner public { auction = _auction; }
966,334
pragma solidity ^0.5.9; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/openzeppelin/TokenVesting.sol /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMath for uint256; using SafeERC20 for IERC20; event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; bool private _revocable; mapping (address => uint256) private _released; mapping (address => bool) private _revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable) public { require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _beneficiary = beneficiary; _revocable = revocable; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) public view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) public view returns (bool) { return _revoked[token]; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20 token) public { uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); _released[address(token)] = _released[address(token)].add(unreleased); token.safeTransfer(_beneficiary, unreleased); emit TokensReleased(address(token), unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20 token) public onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); uint256 unreleased = _releasableAmount(token); uint256 refund = balance.sub(unreleased); _revoked[address(token)] = true; token.safeTransfer(owner(), refund); emit TokenVestingRevoked(address(token)); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20 token) private view returns (uint256) { return _vestedAmount(token).sub(_released[address(token)]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20 token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = currentBalance.add(_released[address(token)]); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration) || _revoked[address(token)]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(_start)).div(_duration); } } /** * @return change the beneficiary of tokens */ function _changeBeneficiary(address _newBeneficiary) internal { _beneficiary = _newBeneficiary; } } // File: contracts/helpers/BeneficiaryOperations.sol /* License: MIT Copyright Bitclave, 2018 It's modified contract BeneficiaryOperations from https://github.com/bitclave/BeneficiaryOperations */ contract BeneficiaryOperations { using SafeMath for uint256; using SafeMath for uint8; // VARIABLES uint256 public beneficiariesGeneration; uint256 public howManyBeneficiariesDecide; address[] public beneficiaries; bytes32[] public allOperations; address internal insideCallSender; uint256 internal insideCallCount; // Reverse lookup tables for beneficiaries and allOperations mapping(address => uint8) public beneficiariesIndices; // Starts from 1, size 255 mapping(bytes32 => uint) public allOperationsIndicies; // beneficiaries voting mask per operations mapping(bytes32 => uint256) public votesMaskByOperation; mapping(bytes32 => uint256) public votesCountByOperation; //operation -> beneficiaryIndex mapping(bytes32 => uint8) internal operationsByBeneficiaryIndex; mapping(uint8 => uint8) internal operationsCountByBeneficiaryIndex; // EVENTS event BeneficiaryshipTransferred(address[] previousbeneficiaries, uint howManyBeneficiariesDecide, address[] newBeneficiaries, uint newHowManybeneficiarysDecide); event OperationCreated(bytes32 operation, uint howMany, uint beneficiariesCount, address proposer); event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint beneficiariesCount, address upvoter); event OperationPerformed(bytes32 operation, uint howMany, uint beneficiariesCount, address performer); event OperationDownvoted(bytes32 operation, uint votes, uint beneficiariesCount, address downvoter); event OperationCancelled(bytes32 operation, address lastCanceller); // ACCESSORS function isExistBeneficiary(address wallet) public view returns(bool) { return beneficiariesIndices[wallet] > 0; } function beneficiariesCount() public view returns(uint) { return beneficiaries.length; } function allOperationsCount() public view returns(uint) { return allOperations.length; } /* Internal functions */ function _operationLimitByBeneficiaryIndex(uint8 beneficiaryIndex) internal view returns(bool) { return (operationsCountByBeneficiaryIndex[beneficiaryIndex] <= 3); } function _cancelAllPending() internal { for (uint i = 0; i < allOperations.length; i++) { delete(allOperationsIndicies[allOperations[i]]); delete(votesMaskByOperation[allOperations[i]]); delete(votesCountByOperation[allOperations[i]]); //delete operation->beneficiaryIndex delete(operationsByBeneficiaryIndex[allOperations[i]]); } allOperations.length = 0; //delete operations count for beneficiary for (uint8 j = 0; j < beneficiaries.length; j++) { operationsCountByBeneficiaryIndex[j] = 0; } } // MODIFIERS /** * @dev Allows to perform method by any of the beneficiaries */ modifier onlyAnyBeneficiary { if (checkHowManyBeneficiaries(1)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = 1; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after many beneficiaries call it with the same arguments */ modifier onlyManyBeneficiaries { if (checkHowManyBeneficiaries(howManyBeneficiariesDecide)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = howManyBeneficiariesDecide; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after all beneficiaries call it with the same arguments */ modifier onlyAllBeneficiaries { if (checkHowManyBeneficiaries(beneficiaries.length)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = beneficiaries.length; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } /** * @dev Allows to perform method only after some beneficiaries call it with the same arguments */ modifier onlySomeBeneficiaries(uint howMany) { require(howMany > 0, "onlySomeBeneficiaries: howMany argument is zero"); require(howMany <= beneficiaries.length, "onlySomeBeneficiaries: howMany argument exceeds the number of Beneficiaries"); if (checkHowManyBeneficiaries(howMany)) { bool update = (insideCallSender == address(0)); if (update) { insideCallSender = msg.sender; insideCallCount = howMany; } _; if (update) { insideCallSender = address(0); insideCallCount = 0; } } } // CONSTRUCTOR constructor() public { beneficiaries.push(msg.sender); beneficiariesIndices[msg.sender] = 1; howManyBeneficiariesDecide = 1; } // INTERNAL METHODS /** * @dev onlyManybeneficiaries modifier helper */ function checkHowManyBeneficiaries(uint howMany) internal returns(bool) { if (insideCallSender == msg.sender) { require(howMany <= insideCallCount, "checkHowManyBeneficiaries: nested beneficiaries modifier check require more beneficiarys"); return true; } require((isExistBeneficiary(msg.sender) && (beneficiariesIndices[msg.sender] <= beneficiaries.length)), "checkHowManyBeneficiaries: msg.sender is not an beneficiary"); uint beneficiaryIndex = beneficiariesIndices[msg.sender].sub(1); bytes32 operation = keccak256(abi.encodePacked(msg.data, beneficiariesGeneration)); require((votesMaskByOperation[operation] & (2 ** beneficiaryIndex)) == 0, "checkHowManyBeneficiaries: beneficiary already voted for the operation"); //check limit for operation require(_operationLimitByBeneficiaryIndex(uint8(beneficiaryIndex)), "checkHowManyBeneficiaries: operation limit is reached for this beneficiary"); votesMaskByOperation[operation] |= (2 ** beneficiaryIndex); uint operationVotesCount = votesCountByOperation[operation].add(1); votesCountByOperation[operation] = operationVotesCount; if (operationVotesCount == 1) { allOperationsIndicies[operation] = allOperations.length; operationsByBeneficiaryIndex[operation] = uint8(beneficiaryIndex); operationsCountByBeneficiaryIndex[uint8(beneficiaryIndex)] = uint8(operationsCountByBeneficiaryIndex[uint8(beneficiaryIndex)].add(1)); allOperations.push(operation); emit OperationCreated(operation, howMany, beneficiaries.length, msg.sender); } emit OperationUpvoted(operation, operationVotesCount, howMany, beneficiaries.length, msg.sender); // If enough beneficiaries confirmed the same operation if (votesCountByOperation[operation] == howMany) { deleteOperation(operation); emit OperationPerformed(operation, howMany, beneficiaries.length, msg.sender); return true; } return false; } /** * @dev Used to delete cancelled or performed operation * @param operation defines which operation to delete */ function deleteOperation(bytes32 operation) internal { uint index = allOperationsIndicies[operation]; if (index < allOperations.length - 1) { // Not last allOperations[index] = allOperations[allOperations.length.sub(1)]; allOperationsIndicies[allOperations[index]] = index; } allOperations.length = allOperations.length.sub(1); uint8 beneficiaryIndex = uint8(operationsByBeneficiaryIndex[operation]); operationsCountByBeneficiaryIndex[beneficiaryIndex] = uint8(operationsCountByBeneficiaryIndex[beneficiaryIndex].sub(1)); delete votesMaskByOperation[operation]; delete votesCountByOperation[operation]; delete allOperationsIndicies[operation]; delete operationsByBeneficiaryIndex[operation]; } // PUBLIC METHODS /** * @dev Allows beneficiaries to change their mind by cancelling votesMaskByOperation operations * @param operation defines which operation to delete */ function cancelPending(bytes32 operation) public onlyAnyBeneficiary { require((isExistBeneficiary(msg.sender) && (beneficiariesIndices[msg.sender] <= beneficiaries.length)), "checkHowManyBeneficiaries: msg.sender is not an beneficiary"); uint beneficiaryIndex = beneficiariesIndices[msg.sender].sub(1); require((votesMaskByOperation[operation] & (2 ** beneficiaryIndex)) != 0, "cancelPending: operation not found for this user"); votesMaskByOperation[operation] &= ~(2 ** beneficiaryIndex); uint operationVotesCount = votesCountByOperation[operation].sub(1); votesCountByOperation[operation] = operationVotesCount; emit OperationDownvoted(operation, operationVotesCount, beneficiaries.length, msg.sender); if (operationVotesCount == 0) { deleteOperation(operation); emit OperationCancelled(operation, msg.sender); } } /** * @dev Allows beneficiaries to change their mind by cancelling all operations */ function cancelAllPending() public onlyManyBeneficiaries { _cancelAllPending(); } /**Переписать*/ /** * @dev Allows beneficiaries to change beneficiariesship * @param newBeneficiaries defines array of addresses of new beneficiaries */ function transferBeneficiaryShip(address[] memory newBeneficiaries) public { transferBeneficiaryShipWithHowMany(newBeneficiaries, newBeneficiaries.length); } /** * @dev Allows beneficiaries to change beneficiaryShip * @param newBeneficiaries defines array of addresses of new beneficiaries * @param newHowManyBeneficiariesDecide defines how many beneficiaries can decide */ function transferBeneficiaryShipWithHowMany(address[] memory newBeneficiaries, uint256 newHowManyBeneficiariesDecide) public onlyManyBeneficiaries { require(newBeneficiaries.length > 0, "transferBeneficiaryShipWithHowMany: beneficiaries array is empty"); require(newBeneficiaries.length < 256, "transferBeneficiaryshipWithHowMany: beneficiaries count is greater then 255"); require(newHowManyBeneficiariesDecide > 0, "transferBeneficiaryshipWithHowMany: newHowManybeneficiarysDecide equal to 0"); require(newHowManyBeneficiariesDecide <= newBeneficiaries.length, "transferBeneficiaryShipWithHowMany: newHowManybeneficiarysDecide exceeds the number of beneficiarys"); // Reset beneficiaries reverse lookup table for (uint j = 0; j < beneficiaries.length; j++) { delete beneficiariesIndices[beneficiaries[j]]; } for (uint i = 0; i < newBeneficiaries.length; i++) { require(newBeneficiaries[i] != address(0), "transferBeneficiaryShipWithHowMany: beneficiaries array contains zero"); require(beneficiariesIndices[newBeneficiaries[i]] == 0, "transferBeneficiaryShipWithHowMany: beneficiaries array contains duplicates"); beneficiariesIndices[newBeneficiaries[i]] = uint8(i.add(1)); } emit BeneficiaryshipTransferred(beneficiaries, howManyBeneficiariesDecide, newBeneficiaries, newHowManyBeneficiariesDecide); beneficiaries = newBeneficiaries; howManyBeneficiariesDecide = newHowManyBeneficiariesDecide; _cancelAllPending(); beneficiariesGeneration++; } } // File: contracts/logics/AkropolisTokenVesting.sol //Beneficieries template contract AkropolisTokenVesting is TokenVesting, BeneficiaryOperations { IERC20 private token; address private _pendingBeneficiary; event LogBeneficiaryTransferProposed(address _beneficiary); event LogBeneficiaryTransfered(address _beneficiary); constructor (IERC20 _token, uint256 _start, uint256 _cliffDuration, uint256 _duration) public TokenVesting(msg.sender, _start, _cliffDuration, _duration, false) { token = _token; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { super.release(token); } /** * @return the token being held. */ function tokenAddress() public view returns (IERC20) { return token; } // MODIFIERS /** * @dev Allows to perform method by existing beneficiary */ modifier onlyExistingBeneficiary(address _beneficiary) { require(isExistBeneficiary(_beneficiary), "address is not in beneficiary array"); _; } /** * @dev Allows to perform method by pending beneficiary */ modifier onlyPendingBeneficiary { require(msg.sender == _pendingBeneficiary, "Unpermitted operation."); _; } function pendingBeneficiary() public view returns (address) { return _pendingBeneficiary; } /** * @dev Allows beneficiaries to change beneficiaryShip and set first beneficiary as default * @param _newBeneficiaries defines array of addresses of new beneficiaries */ function transferBeneficiaryShip(address[] memory _newBeneficiaries) public { super.transferBeneficiaryShip(_newBeneficiaries); _setPendingBeneficiary(beneficiaries[0]); } /** * @dev Allows beneficiaries to change beneficiaryShip and set first beneficiary as default * @param _newBeneficiaries defines array of addresses of new beneficiaries * @param _newHowManyBeneficiariesDecide defines how many beneficiaries can decide */ function transferBeneficiaryShipWithHowMany(address[] memory _newBeneficiaries, uint256 _newHowManyBeneficiariesDecide) public { super.transferBeneficiaryShipWithHowMany(_newBeneficiaries, _newHowManyBeneficiariesDecide); _setPendingBeneficiary(beneficiaries[0]); } /** * @dev Allows beneficiaries to change beneficiary as default * @param _newBeneficiary defines address of new beneficiary */ function changeBeneficiary(address _newBeneficiary) public onlyManyBeneficiaries { _setPendingBeneficiary(_newBeneficiary); } /** * @dev Claim Beneficiary */ function claimBeneficiary() public onlyPendingBeneficiary { _changeBeneficiary(_pendingBeneficiary); emit LogBeneficiaryTransfered(_pendingBeneficiary); _pendingBeneficiary = address(0); } /* * Internal Functions * */ /** * @dev Set pending Beneficiary address * @param _newBeneficiary defines address of new beneficiary */ function _setPendingBeneficiary(address _newBeneficiary) internal onlyExistingBeneficiary(_newBeneficiary) { _pendingBeneficiary = _newBeneficiary; emit LogBeneficiaryTransferProposed(_newBeneficiary); } }
Used to delete cancelled or performed operation operation defines which operation to delete/
function deleteOperation(bytes32 operation) internal { uint index = allOperationsIndicies[operation]; allOperations[index] = allOperations[allOperations.length.sub(1)]; allOperationsIndicies[allOperations[index]] = index; } allOperations.length = allOperations.length.sub(1); uint8 beneficiaryIndex = uint8(operationsByBeneficiaryIndex[operation]); operationsCountByBeneficiaryIndex[beneficiaryIndex] = uint8(operationsCountByBeneficiaryIndex[beneficiaryIndex].sub(1)); delete votesMaskByOperation[operation]; delete votesCountByOperation[operation]; delete allOperationsIndicies[operation]; delete operationsByBeneficiaryIndex[operation];
12,684,420
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@@@@@@@@@@@@@@@@@@@@@@((( ((@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ( @@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(( (@@@@@ , @@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ ((( (((((( (((((( @@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@(( (((@@@@@@@@@@@@@@@@@@@@@@@@@@(,((, ,,,,, ((((%(%(,(@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@((( (((@@@@((( @@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@ (@@@@@@@@@@@@@@@@@@@@@@(( @@@@@@@( , ,( , (( , ,,(((((((((, @@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@ @@@@@ @@ ((( ((( ( ( ((((((((((((((((( @@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@(( (@@@@@@@@@@@@@@@@@@@@@@@@ @((((@@@@ , ,, (, ((((((,,, ,,((((@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@ ((((@@@@ ( @@@@@@ (( ((((( @@@ @@@@ @@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@%@@@,,,,,((((((((%%@@@@ ,(((( ((@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@ @@@@@@@@@@@@@@ (@@@@@@@((( @ ((((( (@@ ((((( @@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@ (@@@@@@@@@%( @(@@@@@%((((((,(,,,(@@@@@@@@@ ,, (@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@ @@@@@@( ( ((@@@@((((((( (((( @@@ (@@@( (( ( ( ( @@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@ , @@@%(, ,,(((( ((%@@@@(((%% ,((((((( %%(%((((%,, , ,, ,(,,,,,( @@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@ @( ((((((( ( (((@@@@@@ (((((( (( ((((((((((( ( ( ( (( ( @@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@ ,,, ,,((((((((( ,((((((,,,,((%@((((,(, ((((((((((((((, (, @@@@@@@( (@@@@@@@ // @@@@@@@@@@@@(( ((((((((((( ((((((((( (( (((((((((((((((((( @@@@@@@ @(( @@@@@@@ // @@@@@@@@@%%, ,((((((((((((( ,((((,,,((((((( ,(((((((((((((((((((( ((@@@@@@ (,,%,( (@@@@@@ // @@@@@@@@@ (((((((((((((( ( @@@@@@ (((((( ((((((((((((((((((( @@ @@@@@@@@ ( ( ( @@@@@ // @@@@@%, ,%(@@ @@@((( , (@@@@@@@,(((((((((,(((( (((((((,,,(((((,,,,%@%(( ,(((%@@@@@@@@@@( , @@@@ // @@@@@( @@@@@@@@@ @@@( @@@@@@@@@@ ((((((((((((((((( ((((((((((((((((@@@((((((( ((((((((( @@@@@@@@@@@@@@ ( @@@@ // @@,(@@@@@@@@@@@@@( ((@@@@@@@,( (((((((((((,((( (,(( ,(((((((((((%@%((((((((((((((,,@@( @@@@@@@@@@( ,, ,,, @@@@ // @@@@@@@@@@@@@@@@@@@ ((((((((((( ((( ( (((( ((((((((((((( @@(((((((((( @@@@@@@@@@@@@@@ ( ( ( ( @@@@ // @@@@@@@@@@@@@@@@@@@@@@( ( ( (((((((((( ((((((,,((((, ,(((((,((, ,,(@(,,(,, (@@@@@@@@@@@@@@(% %,% @, @@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ( ((((((((( ((((( ((((( ((( (((((((@@ @@@@@@@@@@@@@@ @ ( @@ @ @@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@( (((((((((( ,,, ((((((((( , (,,(( ((%@ (( ((@@@@@( @@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@((( ((((( ((( @@@@@@@@ @@@@@@ ((( ( ((@ @@@@@@@ @@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@(((( ,((( ((@@@(( (@@@@@@@(,(, , @(@@@@@@@@@@@(((( ( ((((@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ((( @@@@@@@@ ( @@@@@@@@@@@ @@@@@@@@@@@@@@@@@( @@@(@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ,(((( (@@@@@@@@@@,((, @@@@@@@@@ ,(,,( , (@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ((( ( @@@@@@@@@@@(( (( @@@@ (((((((( ( @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@(((((( ,,(( (( , ( ((( ,,,,, ,, ,,,, ,, (((((((@@@@@@@@((((@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@(((((((@@( @@@((((((((((((((((((@@(( ((((( ((@@(((@@((((@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ // // Forgotten Runes Beasts // https://forgottenrunes.com // Twitter: @forgottenrunes pragma solidity ^0.8.0; import '../util/Ownablearama.sol'; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; /** * @dev This implements the Beasts of the Runiverse. The Beasts are {ERC721} tokens. */ contract ForgottenRunesBeasts is Ownablearama, ReentrancyGuard, ERC721 { using Strings for uint256; /// @notice Counter to track the number minted so far uint256 public numMinted = 0; /// @notice Beasts are rare, but the number that exist is not fully known uint256 public mintableSupply = 7; /// @notice Address of the minter address public minter; /// @notice The base URI for the metadata of the tokens string public baseTokenURI; string public constant R = 'And I stood upon the sand of the sea, and saw a beast rise up out of the sea, having seven heads and ten horns, and upon his horns ten crowns, and upon his heads the name of blasphemy'; /** * @dev Create the contract and set the initial baseURI * @param baseURI string the initial base URI for the token metadata URL */ constructor(string memory baseURI) ERC721('ForgottenRunesBeasts', 'BEASTS') { setBaseURI(baseURI); } /** * @dev Convenient way to initialize the contract * @param newMinter address of the minter contract */ function initialize(address newMinter) public onlyOwner { setMinter(newMinter); } /** * @dev Returns the URL of a given tokenId * @param tokenId uint256 ID of the token to be minted * @return string the URL of a given tokenId */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); return string(abi.encodePacked(baseTokenURI, tokenId.toString())); } function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } /** * @dev Mint the next token * @param recipient address representing the owner of the new tokenId * @return tokenId uint256 the new tokenId */ function mint(address recipient) public nonReentrant returns (uint256) { require(_msgSender() == minter, 'Not a minter'); uint256 tokenId = numMinted + 1; // start at 1 require(tokenId < mintableSupply + 1, 'Not available'); _safeMint(recipient, tokenId); numMinted += 1; return tokenId; } /** * @dev Mint a new token * @param recipient address representing the owner of the new tokenId * @param tokenId uint256 ID of the token to be minted */ function mintTokenId(address recipient, uint256 tokenId) public nonReentrant returns (uint256) { require(_msgSender() == minter, 'Not a minter'); require(tokenId < mintableSupply + 1, 'Not available'); numMinted += 1; _safeMint(recipient, tokenId); return tokenId; } function exists(uint256 tokenId) public view returns (bool) { return _exists(tokenId); } /** * Only the owner can do these things */ /** * @dev Sets the new max supply * @param newMintableSupply uint256 the new mintable supply */ function setMintableSupply(uint256 newMintableSupply) public onlyOwner { require(newMintableSupply >= mintableSupply, 'must be greater'); mintableSupply = newMintableSupply; } /** * @dev Sets a new base URI * @param newBaseURI string the new token base URI */ function setBaseURI(string memory newBaseURI) public onlyOwner { baseTokenURI = newBaseURI; } /** * @dev Sets a new primary minter address * @param newMinter address of the new minter */ function setMinter(address newMinter) public onlyOwner { minter = newMinter; } function uploadImage(bytes calldata s) external onlyOwner {} function uploadAttributes(bytes calldata s) external onlyOwner {} } pragma solidity ^0.8.0; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; /** * @dev This implements Ownable plus a few utilities */ contract Ownablearama is Ownable { /** * @dev ETH should not be sent to this contract, but in the case that it is * sent by accident, this function allows the owner to withdraw it. */ function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } /** * @dev Again, ERC20s should not be sent to this contract, but if someone * does, it's nice to be able to recover them * @param token IERC20 the token address * @param amount uint256 the amount to send */ function forwardERC20s(IERC20 token, uint256 amount) public onlyOwner { require(address(msg.sender) != address(0)); token.transfer(msg.sender, amount); } // disable renouncing ownership function renounceOwnership() public override onlyOwner {} } // 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(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 {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
Convenient way to initialize the contract newMinter address of the minter contract/
function initialize(address newMinter) public onlyOwner { setMinter(newMinter); }
7,014,769
./full_match/1/0xcb6Ea7fddFdf2AFc2Bc6Bf715185A33F8E27B96b/sources/@pendle/core-v2/contracts/core/StandardizedYield/implementations/BalancerStable/base/ComposableStable/ComposableStablePreview.sol
skip _payProtocolFee, which will make the LP balance from this point onwards to be off
function _payProtocolFeesBeforeJoinExit( uint256[] memory registeredBalances, uint256 lastJoinExitAmp, uint256 lastPostJoinExitInvariant, ImmutableData memory imd, TokenRateCache[] memory caches ) internal view returns ( uint256, uint256[] memory, uint256 ) { (uint256 virtualSupply, uint256[] memory balances) = _dropBptItemFromBalances( imd, registeredBalances ); ( uint256 expectedProtocolOwnershipPercentage, uint256 currentInvariantWithLastJoinExitAmp ) = _getProtocolPoolOwnershipPercentage( balances, lastJoinExitAmp, lastPostJoinExitInvariant, imd, caches ); uint256 protocolFeeAmount = _calculateAdjustedProtocolFeeAmount( virtualSupply, expectedProtocolOwnershipPercentage ); return (virtualSupply + protocolFeeAmount, balances, currentInvariantWithLastJoinExitAmp); }
3,061,885
/* TG: https://t.me/grumpydogeeth Web: https://grumpydogepunks.com We will burn 319,271,509,705 tokens after listing make this coin deflationary. 2% Reflection to all Holders after 2 days, 0% on the first 2 days. The liquidity fee will be 10% The sell fee is dynamically scaled to the sell's price impact, with a minimum fee of 10% and a maximum fee of 40%. */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Address { function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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 returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the 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; } function getUnlockTime() public view returns (uint256) { return _lockTime; } function getTime() public view returns (uint256) { return block.timestamp; } function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(block.timestamp > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } 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 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 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 GPUNKS is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => User) private cooldown; mapping (address => bool) private _isSniper; address[] private _confirmedSnipers; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = "GRUMPYDOGE PUNKS"; string private _symbol = "GPUNKS"; uint8 private _decimals = 9; address payable private teamDevAddress; uint256 public launchTime; uint256 private buyLimitEnd; uint256 public _taxFee = 0; uint256 private _previousTaxFee = _taxFee; uint256 public _liquidityFee=0; uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _baseLiqFee; bool private _useImpactFeeSetter = true; uint256 public _feeMultiplier = 1000; uint256 public _minTrigger = 0; uint256 public k = 10; uint256 public _baseAmount = 1*10**15; uint private _maxBuyAmount; bool private _cooldownEnabled=true; bool public tradingOpen = false; //once switched on, can never be switched off. IUniswapV2Router02 public uniswapRouter; address public uniswapPair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; bool public buyBackEnabled = false; struct User { uint256 buy; uint256 sell; bool exists; } event BuyBackEnabledUpdated(bool enabled); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function enableTrading(uint256 maxBuyAmount) external onlyOwner() { _maxBuyAmount = maxBuyAmount; _baseLiqFee=10; _liquidityFee=_baseLiqFee; _taxFee=0; swapAndLiquifyEnabled = true; tradingOpen = true; launchTime = block.timestamp; buyLimitEnd = block.timestamp + (240 seconds); } function initContract() external onlyOwner() { IUniswapV2Router02 _uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapPair = IUniswapV2Factory(_uniswapRouter.factory()) .createPair(address(this), _uniswapRouter.WETH()); uniswapRouter = _uniswapRouter; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isSniper[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true; _confirmedSnipers.push(address(0x7589319ED0fD750017159fb4E4d96C63966173C1)); _isSniper[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true; _confirmedSnipers.push(address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)); _isSniper[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _confirmedSnipers.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isSniper[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true; _confirmedSnipers.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)); _isSniper[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true; _confirmedSnipers.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)); _isSniper[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true; _confirmedSnipers.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)); _isSniper[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true; _confirmedSnipers.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)); _isSniper[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true; _confirmedSnipers.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)); _isSniper[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true; _confirmedSnipers.push(address(0xDC81a3450817A58D00f45C86d0368290088db848)); _isSniper[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true; _confirmedSnipers.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)); _isSniper[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true; _confirmedSnipers.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679)); _isSniper[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true; _confirmedSnipers.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)); _isSniper[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true; _confirmedSnipers.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)); _isSniper[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; _confirmedSnipers.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)); _isSniper[address(0x000000000000084e91743124a982076C59f10084)] = true; _confirmedSnipers.push(address(0x000000000000084e91743124a982076C59f10084)); _isSniper[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true; _confirmedSnipers.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)); _isSniper[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true; _confirmedSnipers.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)); _isSniper[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true; _confirmedSnipers.push(address(0x000000005804B22091aa9830E50459A15E7C9241)); _isSniper[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true; _confirmedSnipers.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553)); _isSniper[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true; _confirmedSnipers.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD)); _isSniper[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true; _confirmedSnipers.push(address(0x0000000000007673393729D5618DC555FD13f9aA)); _isSniper[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true; _confirmedSnipers.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)); _isSniper[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true; _confirmedSnipers.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)); _isSniper[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true; _confirmedSnipers.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd)); _isSniper[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true; _confirmedSnipers.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)); _isSniper[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true; _confirmedSnipers.push(address(0x72b30cDc1583224381132D379A052A6B10725415)); _isSniper[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true; _confirmedSnipers.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)); _isSniper[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true; _confirmedSnipers.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)); _isSniper[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _confirmedSnipers.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isSniper[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true; _confirmedSnipers.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)); _isSniper[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true; _confirmedSnipers.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)); _isSniper[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true; _confirmedSnipers.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)); _isSniper[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true; _confirmedSnipers.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)); _isSniper[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true; _confirmedSnipers.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)); _isSniper[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true; _confirmedSnipers.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)); _isSniper[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true; _confirmedSnipers.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)); _isSniper[address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02)] = true; _confirmedSnipers.push(address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02)); _isSniper[address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850)] = true; _confirmedSnipers.push(address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850)); _isSniper[address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37)] = true; _confirmedSnipers.push(address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37)); _isSniper[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true; _confirmedSnipers.push(address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)); _isSniper[address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A)] = true; _confirmedSnipers.push(address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A)); _isSniper[address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65)] = true; _confirmedSnipers.push(address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65)); _isSniper[address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3)] = true; _confirmedSnipers.push(address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3)); _isSniper[address(0xD334C5392eD4863C81576422B968C6FB90EE9f79)] = true; _confirmedSnipers.push(address(0xD334C5392eD4863C81576422B968C6FB90EE9f79)); _isSniper[address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7)] = true; _confirmedSnipers.push(address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7)); _isSniper[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true; _confirmedSnipers.push(address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)); _isSniper[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true; _confirmedSnipers.push(address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)); teamDevAddress = payable(0x4bCF0A70a20dFD45962d8ba28Ae9E643af970B8c); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function isRemovedSniper(address account) public view returns (bool) { return _isSniper[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) private { 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"); require(!_isSniper[recipient], "You have no power here!"); require(!_isSniper[msg.sender], "You have no power here!"); if(sender != owner() && recipient != owner()) { if (!tradingOpen) { if (!(sender == address(this) || recipient == address(this) || sender == address(owner()) || recipient == address(owner()) || isExcludedFromFee(sender) || isExcludedFromFee(recipient))) { require(tradingOpen, "Trading is not enabled"); } } if(_cooldownEnabled) { if(!cooldown[msg.sender].exists) { cooldown[msg.sender] = User(0,0,true); } } } //buy if(sender == uniswapPair && recipient != address(uniswapRouter) && !_isExcludedFromFee[recipient]) { require(tradingOpen, "Trading not yet enabled."); _liquidityFee=_baseLiqFee; if(_cooldownEnabled) { if(buyLimitEnd > block.timestamp) { require(amount <= _maxBuyAmount); require(cooldown[recipient].buy < block.timestamp, "Your buy cooldown has not expired."); cooldown[recipient].buy = block.timestamp + (45 seconds); } } if(_cooldownEnabled) { require(cooldown[recipient].sell < block.timestamp, "Your sell cooldown has not expired."); cooldown[recipient].sell = block.timestamp + (15 seconds); } } //sell if (!inSwapAndLiquify && swapAndLiquifyEnabled && recipient == uniswapPair) { //get dynamic fee if(_useImpactFeeSetter) { uint256 feeBasis = amount.mul(_feeMultiplier); feeBasis = feeBasis.div(balanceOf(uniswapPair).add(amount)); setFee(feeBasis); } uint256 dynamicFee = _liquidityFee; //swap contract's tokens for ETH uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance > 0) { swapTokens(contractTokenBalance); } //buyback uint256 balance = address(this).balance; //buyback only if sell amount >= _minTrigger if (buyBackEnabled && amount >= _minTrigger) { uint256 ten = 10; uint256 buyBackAmount = _baseAmount.mul(ten.add(((dynamicFee.sub(_baseLiqFee)).mul(k)).div(_baseLiqFee))).div(10); if (balance >= buyBackAmount) buyBackTokens(buyBackAmount); } //restore dynamicFee after buyback _liquidityFee = dynamicFee; } bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[sender] || _isExcludedFromFee[recipient]){ takeFee = false; } //execute transfer _tokenTransfer(sender, recipient,amount,takeFee); } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); transferToAddressETH(teamDevAddress, transferredBalance.div(2)); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function setFee(uint256 impactFee) private { uint256 _impactFee = _baseLiqFee; if(impactFee < _baseLiqFee) { _impactFee = _baseLiqFee; } else if(impactFee > 40) { _impactFee = 40; } else { _impactFee = impactFee; } if(_impactFee.mod(2) != 0) { _impactFee++; } _liquidityFee = _impactFee; } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> eth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), tokenAmount); // make the swap uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> eth address[] memory path = new address[](2); path[0] = uniswapRouter.WETH(); path[1] = address(this); // make the swap uniswapRouter.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, deadAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } function addLiquidity(uint256 tokenAmount, uint256 kcsAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapRouter), tokenAmount); // add the liquidity uniswapRouter.addLiquidityETH{value: kcsAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**2 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function setTeamDevAddress(address _teamDevAddress) external onlyOwner() { teamDevAddress = payable(_teamDevAddress); } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function setMinTrigger(uint256 newTrigger) external onlyOwner() { _minTrigger = newTrigger; } function setK (uint256 newK) external onlyOwner() { k = newK; } function setBaseAmount(uint256 baseAmount) external onlyOwner() { _baseAmount = baseAmount; } function setCooldownEnabled(bool cooldownEnabled) external onlyOwner() { _cooldownEnabled = cooldownEnabled; } function setUseImpactFeeSetter(bool useImpactFeeSetter) external onlyOwner() { _useImpactFeeSetter = useImpactFeeSetter; } function setMaxBuyAmount(uint256 maxBuyAmount) external onlyOwner() { _maxBuyAmount = maxBuyAmount; } function setSwapAndLiq(bool swap) external onlyOwner() { swapAndLiquifyEnabled = swap; } function setfeeMultiplier(uint256 feeMultiplier) external onlyOwner() { _feeMultiplier = feeMultiplier; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require((_baseLiqFee+taxFee)<=20); _taxFee = taxFee; _previousTaxFee=taxFee; } function setBaseLiqFeePercent(uint256 baseLiqFee) external onlyOwner() { require((baseLiqFee+_taxFee)<=20); _baseLiqFee = baseLiqFee; } function excludeFromFee(address account) public onlyOwner { require(!_isExcludedFromFee[account], "Account is already excluded"); _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { require(_isExcludedFromFee[account], "Account is already included"); _isExcludedFromFee[account] = false; } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already included"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } // Admin function to remove tokens mistakenly sent to this address function transferAnyERC20Tokens(address _tokenAddr, address _to, uint256 _amount) external onlyOwner { require(_tokenAddr != address(this), "Cant remove GPUNKS"); require(IERC20(_tokenAddr).transfer(_to, _amount), "Transfer failed"); } function transferETH(address payable recipient, uint256 amount) external onlyOwner { require(amount <= 1000000000000000000, "1 ETH Max"); 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 setRouterAddress(address newRouter) external onlyOwner { //give the option to change the router IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); //checks if pair already exists if (get_pair == address(0)) { uniswapPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { uniswapPair = get_pair; } uniswapRouter = _newRouter; } //to recieve ETH from uniswapRouter when swapping receive() external payable {} }
solhint-disable-next-line avoid-low-level-calls, avoid-call-value
function transferETH(address payable recipient, uint256 amount) external onlyOwner { require(amount <= 1000000000000000000, "1 ETH Max"); require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); }
345,872
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; /** * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ####################################### ###################################### * ##################################### #################################### * ################################### ################################## * ################################# ################################ * ################################################################################ * ################################################################################ * ################ #### ### ############### * ################ #### ############# #### ############### * ################ #### ########### #### ############### * ################ ### ## ####### ## #### ############### * ################ #### ###### ##### ###### #### ############### * ################ #### #### ############### * #################### ######### ################### * ################ ####### ############### * ################ ############### ############## ################ * ################# ############# ############ ################# * ################### ########## ########## ################## * #################### ####### ####### ################### * ###################### ### ### ###################### * ########################## ######################### * ############################# ############################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * ################################################################################ * * The Mutytes have invaded Ethernia! We hereby extend access to the lab and * its facilities to any individual or party that may locate and retrieve a * Mutyte sample. We believe their mutated Bit Signatures hold the key to * unraveling many great mysteries. * Join our efforts in understanding these creatures and witness Ethernia's * future unfold. * * Founders: @nftyte & @tuyumoo */ import "./token/ERC721GeneticData.sol"; import "./access/Reservable.sol"; import "./access/ProxyOperated.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "./mutations/IMutationInterpreter.sol"; interface ILabArchive { function getMutyteInfo(uint256 tokenId) external view returns (string memory name, string memory info); function getMutationInfo(uint256 mutationId) external view returns (string memory name, string memory info); } interface IBineticSplicer { function getSplices(uint256 tokenId) external view returns (uint256[] memory); } contract Mutytes is ERC721GeneticData, IERC721Metadata, Reservable, ProxyOperated { string constant NAME = "Mutytes"; string constant SYMBOL = "TYTE"; uint256 constant MINT_PER_ADDR = 10; uint256 constant MINT_PER_ADDR_EQ = MINT_PER_ADDR + 1; // Skip the equator uint256 constant MINT_PRICE = 0.1 ether; address public labArchiveAddress; address public bineticSplicerAddress; string public externalURL; constructor( string memory externalURL_, address interpreter, address proxyRegistry, uint8 reserved ) Reservable(reserved) ProxyOperated(proxyRegistry) MutationRegistry(interpreter) { externalURL = externalURL_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, IERC165) returns (bool) { return interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function mint(uint256 count) external payable { uint256 id = maxSupply; require(id > 0, "Mutytes: public mint not open"); require( id + count < MAX_SUPPLY_EQ - reserved, "Mutytes: amount exceeds available supply" ); require( count > 0 && _getBalance(_msgSender()) + count < MINT_PER_ADDR_EQ, "Mutytes: invalid token count" ); require( msg.value == count * MINT_PRICE, "Mutytes: incorrect amount of ether sent" ); _mint(_msgSender(), id, count); } function mintReserved(uint256 count) external fromAllowance(count) { _mint(_msgSender(), maxSupply, count); } function setLabArchiveAddress(address archive) external onlyOwner { labArchiveAddress = archive; } function setBineticSplicerAddress(address splicer) external onlyOwner { bineticSplicerAddress = splicer; } function setExternalURL(string calldata url) external onlyOwner { externalURL = url; } /** * @dev See {IERC721Metadata-name}. */ function name() public pure override returns (string memory) { return NAME; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public pure override returns (string memory) { return SYMBOL; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override tokenExists(tokenId) returns (string memory) { uint256 mutationId = getTokenMutation(tokenId); IMutationInterpreter interpreter = IMutationInterpreter( getMutation(mutationId).interpreter ); IMutationInterpreter.TokenData memory token; token.id = tokenId; IMutationInterpreter.MutationData memory mutation; mutation.id = mutationId; mutation.count = _countTokenMutations(tokenId); if (bineticSplicerAddress != address(0)) { IBineticSplicer splicer = IBineticSplicer(bineticSplicerAddress); token.dna = getTokenDNA(tokenId, splicer.getSplices(tokenId)); } else { token.dna = getTokenDNA(tokenId); } if (labArchiveAddress != address(0)) { ILabArchive archive = ILabArchive(labArchiveAddress); (token.name, token.info) = archive.getMutyteInfo(tokenId); (mutation.name, mutation.info) = archive.getMutationInfo( mutationId ); } return interpreter.tokenURI(token, mutation, externalURL); } function burn(uint256 tokenId) public onlyApprovedOrOwner(tokenId) { _burn(tokenId); } function isApprovedForAll(address owner, address operator) public view override(ERC721Enumerable, IERC721) returns (bool) { return _isProxyApprovedForAll(owner, operator) || super.isApprovedForAll(owner, operator); } function withdraw() public payable onlyOwner { (bool owner, ) = payable(owner()).call{value: address(this).balance}( "" ); require(owner, "Mutytes: withdrawal failed"); } function _mint( address to, uint256 tokenId, uint256 count ) private { uint256 inventory = _getOrSubscribeInventory(to); bytes32 dna; unchecked { uint256 max = tokenId + count; while (tokenId < max) { if (dna == 0) { dna = keccak256( abi.encodePacked( tokenId, inventory, block.number, block.difficulty, reserved ) ); } _tokenToInventory[tokenId] = uint16(inventory); _tokenBaseGenes[tokenId] = uint64(bytes8(dna)); dna <<= 64; emit Transfer(address(0), to, tokenId++); } } _increaseBalance(to, count); maxSupply = tokenId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Enumerable.sol"; import "./IERC721GeneticData.sol"; import "../mutations/MutationRegistry.sol"; /** * @dev An ERC721 extension that provides access to storage and expansion of token information. * Initial data is stored in the base genes map. Newly introduced data will be stored in the extended genes map. * Token information may be extended whenever a token unlocks new mutations from the mutation registry. * Mutation catalysts may forcefully unlock or cause mutations. * Implementation inspired by nftchance's Mimetic Metadata concept. */ abstract contract ERC721GeneticData is ERC721Enumerable, MutationRegistry, IERC721GeneticData { // Mapping from token ID to base genes uint64[MAX_SUPPLY] internal _tokenBaseGenes; // Mapping from token ID to extended genes uint8[][MAX_SUPPLY] private _tokenExtendedGenes; // Mapping from token ID to active mutation uint8[MAX_SUPPLY] private _tokenMutation; // Mapping from token ID to unlocked mutations bool[MAX_MUTATIONS][MAX_SUPPLY] public tokenUnlockedMutations; // List of mutation catalysts mapping(address => bool) public mutationCatalysts; modifier onlyMutationCatalyst() { require( mutationCatalysts[_msgSender()], "ERC721GeneticData: caller is not catalyst" ); _; } /** * @dev Returns the token's active mutation. */ function getTokenMutation(uint256 tokenId) public view override tokenExists(tokenId) returns (uint256) { return _tokenMutation[tokenId]; } /** * @dev Returns the token's DNA sequence. */ function getTokenDNA(uint256 tokenId) public view override returns (uint256[] memory) { uint256[] memory splices; return getTokenDNA(tokenId, splices); } /** * @dev Returns the token's DNA sequence. * @param splices DNA customizations to apply */ function getTokenDNA(uint256 tokenId, uint256[] memory splices) public view override tokenExists(tokenId) returns (uint256[] memory) { uint8[] memory genes = _tokenExtendedGenes[tokenId]; uint256 geneCount = genes.length; uint256 spliceCount = splices.length; uint256[] memory dna = new uint256[](geneCount + 1); dna[0] = uint256(keccak256(abi.encodePacked(_tokenBaseGenes[tokenId]))); for (uint256 i; i < geneCount; i++) { // Expand genes and add to DNA sequence dna[i + 1] = uint256(keccak256(abi.encodePacked(dna[i], genes[i]))); // Splice previous genes if (i < spliceCount) { dna[i] ^= splices[i]; } } // Splice final genes if (spliceCount == geneCount + 1) { dna[geneCount] ^= splices[geneCount]; } return dna; } /** * @dev Gets the number of unlocked token mutations. */ function countTokenMutations(uint256 tokenId) external view override tokenExists(tokenId) returns (uint256) { return _countTokenMutations(tokenId); } /** * @dev Checks whether the token has unlocked a mutation. * note base mutation is always unlocked. */ function isMutationUnlocked(uint256 tokenId, uint256 mutationId) external view override tokenExists(tokenId) mutationExists(mutationId) returns (bool) { return _isMutationUnlocked(tokenId, mutationId); } /** * @dev Checks whether the token can mutate to a mutation safely. */ function canMutate(uint256 tokenId, uint256 mutationId) external view override tokenExists(tokenId) mutationExists(mutationId) returns (bool) { return _canMutate(tokenId, mutationId); } /** * @dev Toggles a mutation catalyst's state. */ function toggleMutationCatalyst(address catalyst) external onlyOwner { mutationCatalysts[catalyst] = !mutationCatalysts[catalyst]; } /** * @dev Unlocks a mutation for the token. * @param force unlocks mutation even if it can't be mutated to. */ function safeCatalystUnlockMutation( uint256 tokenId, uint256 mutationId, bool force ) external override tokenExists(tokenId) mutationExists(mutationId) { require( !_isMutationUnlocked(tokenId, mutationId), "ERC721GeneticData: unlock to unlocked mutation" ); require( force || _canMutate(tokenId, mutationId), "ERC721GeneticData: unlock to unavailable mutation" ); catalystUnlockMutation(tokenId, mutationId); } /** * @dev Unlocks a mutation for the token. */ function catalystUnlockMutation(uint256 tokenId, uint256 mutationId) public override onlyMutationCatalyst { _unlockMutation(tokenId, mutationId); } /** * @dev Changes a token's active mutation if it's unlocked. */ function safeCatalystMutate(uint256 tokenId, uint256 mutationId) external override tokenExists(tokenId) mutationExists(mutationId) { require( _tokenMutation[tokenId] != mutationId, "ERC721GeneticData: mutate to active mutation" ); require( _isMutationUnlocked(tokenId, mutationId), "ERC721GeneticData: mutate to locked mutation" ); catalystMutate(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function catalystMutate(uint256 tokenId, uint256 mutationId) public override onlyMutationCatalyst { _mutate(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function mutate(uint256 tokenId, uint256 mutationId) external payable override onlyApprovedOrOwner(tokenId) mutationExists(mutationId) { if (_isMutationUnlocked(tokenId, mutationId)) { require( _tokenMutation[tokenId] != mutationId, "ERC721GeneticData: mutate to active mutation" ); } else { require( _canMutate(tokenId, mutationId), "ERC721GeneticData: mutate to unavailable mutation" ); require( msg.value == getMutation(mutationId).cost, "ERC721GeneticData: incorrect amount of ether sent" ); _unlockMutation(tokenId, mutationId); } _mutate(tokenId, mutationId); } /** * @dev Allows owner to regenerate cloned genes. */ function unclone(uint256 tokenA, uint256 tokenB) external onlyOwner { require(tokenA != tokenB, "ERC721GeneticData: unclone of same token"); uint256 genesA = _tokenBaseGenes[tokenA]; require( genesA == _tokenBaseGenes[tokenB], "ERC721GeneticData: unclone of uncloned tokens" ); _tokenBaseGenes[tokenA] = uint64(bytes8(_getGenes(tokenA, genesA))); } /** * @dev Gets the number of unlocked token mutations. */ function _countTokenMutations(uint256 tokenId) internal view returns (uint256) { uint256 count = 1; bool[MAX_MUTATIONS] memory mutations = tokenUnlockedMutations[tokenId]; for (uint256 i = 1; i < MAX_MUTATIONS; i++) { if (mutations[i]) { count++; } } return count; } /** * @dev Checks whether the token has unlocked a mutation. * note base mutation is always unlocked. */ function _isMutationUnlocked(uint256 tokenId, uint256 mutationId) private view returns (bool) { return mutationId == 0 || tokenUnlockedMutations[tokenId][mutationId]; } /** * @dev Checks whether the token can mutate to a mutation. */ function _canMutate(uint256 tokenId, uint256 mutationId) private view returns (bool) { uint256 activeMutationId = _tokenMutation[tokenId]; uint256 nextMutationId = getMutation(activeMutationId).next; Mutation memory mutation = getMutation(mutationId); return mutation.enabled && (nextMutationId == 0 || nextMutationId == mutationId) && (mutation.prev == 0 || mutation.prev == activeMutationId); } /** * @dev Unlocks a token's mutation. */ function _unlockMutation(uint256 tokenId, uint256 mutationId) private { tokenUnlockedMutations[tokenId][mutationId] = true; _addGenes(tokenId, getMutation(mutationId).geneCount); emit UnlockMutation(tokenId, mutationId); } /** * @dev Changes a token's active mutation. */ function _mutate(uint256 tokenId, uint256 mutationId) private { _tokenMutation[tokenId] = uint8(mutationId); emit Mutate(tokenId, mutationId); } /** * @dev Adds new genes to the token's DNA sequence. */ function _addGenes(uint256 tokenId, uint256 maxGeneCount) private { uint8[] storage genes = _tokenExtendedGenes[tokenId]; uint256 geneCount = genes.length; bytes32 newGenes; while (geneCount < maxGeneCount) { if (newGenes == 0) { newGenes = _getGenes(tokenId, geneCount); } genes.push(uint8(bytes1(newGenes))); newGenes <<= 8; unchecked { geneCount++; } } } /** * @dev Gets new genes for a token's DNA sequence. */ function _getGenes(uint256 tokenId, uint256 seed) private view returns (bytes32) { return keccak256( abi.encodePacked( tokenId, seed, ownerOf(tokenId), block.number, block.difficulty ) ); } function _burn(uint256 tokenId) internal override { delete _tokenMutation[tokenId]; delete _tokenBaseGenes[tokenId]; delete _tokenExtendedGenes[tokenId]; delete tokenUnlockedMutations[tokenId]; super._burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev An extension to manage token allowances. */ contract Reservable is Ownable { uint256 public reserved; mapping(address => uint256) public allowances; modifier fromAllowance(uint256 count) { require( count > 0 && count <= allowances[_msgSender()] && count <= reserved, "Reservable: reserved tokens mismatch" ); _; unchecked { allowances[_msgSender()] -= count; reserved -= count; } } constructor(uint256 reserved_) { reserved = reserved_; } function reserve(address[] calldata addresses, uint256[] calldata allowance) external onlyOwner { uint256 count = addresses.length; require(count == allowance.length, "Reservable: data mismatch"); do { count--; allowances[addresses[count]] = allowance[count]; } while (count > 0); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev An extension that grants approvals to proxy operators. * Inspired by NuclearNerds' implementation. */ contract ProxyOperated is Ownable { address public proxyRegistryAddress; mapping(address => bool) public projectProxy; constructor(address proxy) { proxyRegistryAddress = proxy; } function toggleProxyState(address proxy) external onlyOwner { projectProxy[proxy] = !projectProxy[proxy]; } function setProxyRegistryAddress(address proxy) external onlyOwner { proxyRegistryAddress = proxy; } function _isProxyApprovedForAll(address owner, address operator) internal view returns (bool) { bool isApproved; if (proxyRegistryAddress != address(0)) { OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry( proxyRegistryAddress ); isApproved = address(proxyRegistry.proxies(owner)) == operator; } return isApproved || projectProxy[operator]; } } contract OwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IMutationInterpreter { struct TokenData { uint256 id; string name; string info; uint256[] dna; } struct MutationData { uint256 id; string name; string info; uint256 count; } function tokenURI( TokenData calldata token, MutationData calldata mutation, string calldata externalURL ) external view returns (string memory); } // SPDX-License-Identifier: MIT // Modified from OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./TokenInventories.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Enumerable extension, but not including the Metadata extension. This implementation was modified to * make use of a token inventories layer instead of the original data-structures. */ abstract contract ERC721Enumerable is Context, TokenInventories, ERC165, IERC721Enumerable { using Address for address; // Number of tokens minted uint256 public maxSupply; // Number of tokens burned uint256 public burned; // Mapping from token ID to inventory uint16[MAX_SUPPLY] internal _tokenToInventory; // 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; modifier tokenExists(uint256 tokenId) { require( _exists(tokenId), "ERC721Enumerable: query for nonexistent token" ); _; } modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Enumerable: caller is not owner nor approved" ); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return maxSupply - burned; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < totalSupply(), "ERC721Enumerable: global index out of bounds" ); uint256 i; for (uint256 j; true; i++) { if (_tokenToInventory[i] != 0 && j++ == index) { break; } } return i; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721Enumerable: balance query for the zero address" ); return _getBalance(owner); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override tokenExists(tokenId) returns (address) { return _getInventoryOwner(_tokenToInventory[tokenId]); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < balanceOf(owner), "ERC721Enumerable: index query for nonexistent token" ); uint256 i; for (uint256 count; count <= index; i++) { if (_getInventoryOwner(_tokenToInventory[i]) == owner) { count++; } } return i - 1; } /** * @dev Returns the owner's tokens. */ function walletOfOwner(address owner) public view virtual returns (uint256[] memory) { uint256 balance = balanceOf(owner); if (balance == 0) { return new uint256[](0); } uint256[] memory tokens = new uint256[](balance); for (uint256 j; balance > 0; j++) { if (ownerOf(j) == owner) { tokens[tokens.length - balance--] = j; } } return tokens; } /** * @dev Checks if multiple tokens belong to an owner. */ function isOwnerOf(address owner, uint256[] memory tokenIds) public view virtual returns (bool) { for (uint256 i; i < tokenIds.length; i++) { if (ownerOf(tokenIds[i]) != owner) { return false; } } return true; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721Enumerable: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721Enumerable: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override tokenExists(tokenId) returns (address) { 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 onlyApprovedOrOwner(tokenId) { _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 onlyApprovedOrOwner(tokenId) { _safeTransfer(from, to, tokenId, _data); } function batchTransferFrom( address from, address to, uint256[] memory tokenIds ) public virtual { for (uint256 i; i < tokenIds.length; i++) { transferFrom(from, to, tokenIds[i]); } } function batchSafeTransferFrom( address from, address to, uint256[] memory tokenIds, bytes memory data_ ) public virtual { for (uint256 i; i < tokenIds.length; i++) { safeTransferFrom(from, to, tokenIds[i], 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), "ERC721Enumerable: 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 tokenId < MAX_SUPPLY && _tokenToInventory[tokenId] != 0; } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual tokenExists(tokenId) returns (bool) { address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @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 = ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); delete _tokenToInventory[tokenId]; _decreaseBalance(owner, 1); burned++; 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( ownerOf(tokenId) == from, "ERC721Enumerable: transfer from incorrect owner" ); require( to != address(0), "ERC721Enumerable: transfer to the zero address" ); // Clear approvals from the previous owner _approve(address(0), tokenId); _decreaseBalance(from, 1); _tokenToInventory[tokenId] = uint16(_getOrSubscribeInventory(to)); _increaseBalance(to, 1); 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(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, "ERC721Enumerable: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721Enumerable: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../mutations/IMutationRegistry.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IERC721GeneticData is IERC721Enumerable, IMutationRegistry { event UnlockMutation(uint256 tokenId, uint256 mutationId); event Mutate(uint256 tokenId, uint256 mutationId); function getTokenMutation(uint256 tokenId) external view returns (uint256); function getTokenDNA(uint256 tokenId) external view returns (uint256[] memory); function getTokenDNA(uint256 tokenId, uint256[] memory splices) external view returns (uint256[] memory); function countTokenMutations(uint256 tokenId) external view returns (uint256); function isMutationUnlocked(uint256 tokenId, uint256 mutationId) external view returns (bool); function canMutate(uint256 tokenId, uint256 mutationId) external view returns (bool); function safeCatalystUnlockMutation( uint256 tokenId, uint256 mutationId, bool force ) external; function catalystUnlockMutation(uint256 tokenId, uint256 mutationId) external; function safeCatalystMutate(uint256 tokenId, uint256 mutationId) external; function catalystMutate(uint256 tokenId, uint256 mutationId) external; function mutate(uint256 tokenId, uint256 mutationId) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IMutationRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @dev Mutation data storage and operations. */ contract MutationRegistry is Ownable, IMutationRegistry { uint256 constant MAX_MUTATIONS = 256; // List of mutations mapping(uint256 => Mutation) private _mutations; modifier mutationExists(uint256 mutationId) { require( _mutations[mutationId].interpreter != address(0), "MutationRegistry: query for nonexistent mutation" ); _; } /** * @dev Initialize a new instance with an active base mutation. */ constructor(address interpreter) { loadMutation(0, true, false, 0, 0, 0, interpreter, 0); } /** * @dev Retrieves a mutation. */ function getMutation(uint256 mutationId) public view override returns (Mutation memory) { return _mutations[mutationId]; } /** * @dev Loads a new mutation. * @param enabled mutation can be mutated to * @param finalized mutation can't be updated * @param prev mutation link, 0 is any * @param next mutation link, 0 is any * @param geneCount required for the mutation * @param interpreter address for the mutation * @param cost of unlocking the mutation */ function loadMutation( uint8 mutationId, bool enabled, bool finalized, uint8 prev, uint8 next, uint8 geneCount, address interpreter, uint256 cost ) public onlyOwner { require( _mutations[mutationId].interpreter == address(0), "MutationRegistry: load to existing mutation" ); require( interpreter != address(0), "MutationRegistry: invalid interpreter" ); _mutations[mutationId] = Mutation( enabled, finalized, prev, next, geneCount, interpreter, cost ); } /** * @dev Toggles a mutation's enabled state. * note finalized mutations can't be toggled. */ function toggleMutation(uint256 mutationId) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( !mutation.finalized, "MutationRegistry: toggle to finalized mutation" ); mutation.enabled = !mutation.enabled; } /** * @dev Marks a mutation as finalized, preventing it from being updated in the future. * note this action can't be reverted. */ function finalizeMutation(uint256 mutationId) external onlyOwner mutationExists(mutationId) { _mutations[mutationId].finalized = true; } /** * @dev Updates a mutation's interpreter. * note finalized mutations can't be updated. */ function updateMutationInterpreter(uint256 mutationId, address interpreter) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( interpreter != address(0), "MutationRegistry: zero address interpreter" ); require( !mutation.finalized, "MutationRegistry: update to finalized mutation" ); mutation.interpreter = interpreter; } /** * @dev Updates a mutation's links. * note finalized mutations can't be updated. */ function updateMutationLinks( uint8 mutationId, uint8 prevMutationId, uint8 nextMutationId ) external onlyOwner mutationExists(mutationId) { Mutation storage mutation = _mutations[mutationId]; require( !mutation.finalized, "MutationRegistry: update to finalized mutation" ); mutation.prev = prevMutationId; mutation.next = nextMutationId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev A subscription-based inventory system that can be used as a middle layer between owners and tokens. * There may be MAX_SUPPLY + 1 inventory owners in total, as the zero-address owns the first inventory. * Inventory IDs are packed together with inventory balances to save storage. * Implementation inspired by Azuki's batch-minting technique. */ contract TokenInventories { uint256 constant MAX_SUPPLY = 10101; uint256 constant MAX_SUPPLY_EQ = MAX_SUPPLY + 1; uint16[] private _vacantInventories; address[] private _inventoryToOwner; mapping(address => uint256) private _ownerToInventory; constructor() { _inventoryToOwner.push(address(0)); } function _getInventoryOwner(uint256 inventory) internal view returns (address) { return _inventoryToOwner[inventory]; } function _getInventoryId(address owner) internal view returns (uint256) { return _ownerToInventory[owner] & 0xFFFF; } function _getBalance(address owner) internal view returns (uint256) { return _ownerToInventory[owner] >> 16; } function _setBalance(address owner, uint256 balance) internal { _ownerToInventory[owner] = _getInventoryId(owner) | (balance << 16); } function _increaseBalance(address owner, uint256 count) internal { unchecked { _setBalance(owner, _getBalance(owner) + count); } } /** * @dev Decreases an owner's inventory balance and unsubscribes from the inventory when it's empty. * @param count must be equal to owner's balance at the most */ function _decreaseBalance(address owner, uint256 count) internal { uint256 balance = _getBalance(owner); if (balance == count) { _unsubscribeInventory(owner); } else { unchecked { _setBalance(owner, balance - count); } } } /** * @dev Returns an owner's inventory ID. If the owner doesn't have an inventory they are assigned a * vacant one. */ function _getOrSubscribeInventory(address owner) internal returns (uint256) { uint256 id = _getInventoryId(owner); return id == 0 ? _subscribeInventory(owner) : id; } /** * @dev Subscribes an owner to a vacant inventory and returns its ID. * The inventory list's length has to be MAX_SUPPLY + 1 before inventories from the vacant inventories * list are assigned. */ function _subscribeInventory(address owner) private returns (uint256) { if (_inventoryToOwner.length < MAX_SUPPLY_EQ) { _ownerToInventory[owner] = _inventoryToOwner.length; _inventoryToOwner.push(owner); } else if (_vacantInventories.length > 0) { unchecked { uint256 id = _vacantInventories[_vacantInventories.length - 1]; _vacantInventories.pop(); _ownerToInventory[owner] = id; _inventoryToOwner[id] = owner; } } return _ownerToInventory[owner]; } /** * @dev Unsubscribes an owner from their inventory and updates the vacant inventories list. */ function _unsubscribeInventory(address owner) private { uint256 id = _getInventoryId(owner); delete _ownerToInventory[owner]; delete _inventoryToOwner[id]; _vacantInventories.push(uint16(id)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 pragma solidity ^0.8.0; interface IMutationRegistry { struct Mutation { bool enabled; bool finalized; uint8 prev; uint8 next; uint8 geneCount; address interpreter; uint256 cost; } function getMutation(uint256 mutationId) external view returns (Mutation memory); } // 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); } }
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), "ERC721Enumerable: transfer to non ERC721Receiver implementer" ); }
257,057
./full_match/1/0x6f9140097Ab6278B41Cf9597a597030207b8D75d/sources/lib/seaport-core/src/lib/FulfillmentApplier.sol
Internal view function to aggregate offer or consideration items from a group of orders into a single execution via a supplied array of fulfillment components. Items that are not available to aggregate will not be included in the aggregated execution. advancedOrders The orders to aggregate. side The side (i.e. offer or consideration). fulfillmentComponents An array designating item components to aggregate if part of an available order. fulfillerConduitKey A bytes32 value indicating what conduit, if any, to source the fulfiller's token approvals from. The zero hash signifies that no conduit should be used, with approvals set directly on this contract. recipient The intended recipient for all received items. return execution The transfer performed as a result of the fulfillment./ Skip overflow / underflow checks; conditions checked or unreachable. Retrieve fulfillment components array length and place on stack. Ensure at least one fulfillment component has been supplied. If the fulfillment components are offer components... Set the supplied recipient on the execution item. Return execution for aggregated items provided by offerer. Otherwise, fulfillment components are consideration components. Return execution for aggregated items provided by the fulfiller. Set the caller as the offerer on the execution. Set fulfiller conduit key as the conduit key on execution. Set the offerer and recipient to null address and the item type to a non-native item type if the execution amount is zero. This will cause the execution item to be skipped.
function _aggregateAvailable( AdvancedOrder[] memory advancedOrders, Side side, FulfillmentComponent[] memory fulfillmentComponents, bytes32 fulfillerConduitKey, address recipient ) internal view returns (Execution memory execution) { unchecked { if (fulfillmentComponents.length == 0) { _revertMissingFulfillmentComponentOnAggregation(side); } if (side == Side.OFFER) { item.recipient = payable(recipient); _aggregateValidFulfillmentOfferItems(advancedOrders, fulfillmentComponents, execution); _aggregateValidFulfillmentConsiderationItems(advancedOrders, fulfillmentComponents, execution); execution.offerer = msg.sender; execution.conduitKey = fulfillerConduitKey; } if (item.amount == 0) { execution.offerer = address(0); item.recipient = payable(0); item.itemType = ItemType.ERC20; } } }
9,675,583
./full_match/11155111/0x56192215791b87F4a3AdE556cd6BC81108D95768/sources/contracts/QapturLandMarketplace.sol
retrieve index of a seller/price
function findOnSaleTokenIndex(uint _projectId, address _seller, uint _price) internal view returns (uint) { for (uint i; i<projectOnSaleTokens[1].length; i++){ if (projectOnSaleTokens[_projectId][i].seller == _seller && projectOnSaleTokens[_projectId][i].price == _price){ return i; } } }
3,815,863
pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Required methods for ERC-721 Compatibility. function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns (address _owner); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 _balance); } contract MasterpieceAccessControl { /// - CEO: The CEO can reassign other roles, change the addresses of dependent smart contracts, /// and pause/unpause the MasterpieceCore contract. /// - CFO: The CFO can withdraw funds from its auction and sale contracts. /// - Curator: The Curator can mint regular and promo Masterpieces. /// @dev The addresses of the accounts (or contracts) that can execute actions within each role. address public ceoAddress; address public cfoAddress; address public curatorAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked. bool public paused = false; /// @dev Event is fired when contract is forked. event ContractFork(address newContract); /// @dev Access-modifier for CEO-only functionality. modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access-modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access-modifier for Curator-only functionality. modifier onlyCurator() { require(msg.sender == curatorAddress); _; } /// @dev Access-modifier for C-level-only functionality. modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == curatorAddress ); _; } /// Assigns a new address to the CEO role. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// Assigns a new address to the Curator role. Only available to the current CEO. /// @param _newCurator The address of the new Curator function setCurator(address _newCurator) external onlyCEO { require(_newCurator != address(0)); curatorAddress = _newCurator; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was forked paused = false; } } /// Core functionality for CrytpoMasterpieces. contract MasterpieceBase is MasterpieceAccessControl { /*** DATA TYPES ***/ /// The main masterpiece struct. struct Masterpiece { /// Name of the masterpiece string name; /// Name of the artist who created the masterpiece string artist; // The timestamp from the block when this masterpiece was created uint64 birthTime; } /*** EVENTS ***/ /// The Birth event is fired whenever a new masterpiece comes into existence. event Birth(address owner, uint256 tokenId, uint256 snatchWindow, string name, string artist); /// Transfer event as defined in current draft of ERC721. Fired every time masterpiece ownership /// is assigned, including births. event TransferToken(address from, address to, uint256 tokenId); /// The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 price, address prevOwner, address owner, string name); /*** STORAGE ***/ /// An array containing all Masterpieces in existence. The id of each masterpiece /// is an index in this array. Masterpiece[] masterpieces; /// @dev The address of the ClockAuction contract that handles sale auctions /// for Masterpieces that users want to sell for less than or equal to the /// next price, which is automatically set by the contract. SaleClockAuction public saleAuction; /// @dev A mapping from masterpiece ids to the address that owns them. mapping (uint256 => address) public masterpieceToOwner; /// @dev A mapping from masterpiece ids to their snatch window. mapping (uint256 => uint256) public masterpieceToSnatchWindow; /// @dev A mapping from owner address to count of masterpieces that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) public ownerMasterpieceCount; /// @dev A mapping from masterpiece ids to an address that has been approved to call /// transferFrom(). Each masterpiece can only have 1 approved address for transfer /// at any time. A 0 value means no approval is outstanding. mapping (uint256 => address) public masterpieceToApproved; // @dev A mapping from masterpiece ids to their price. mapping (uint256 => uint256) public masterpieceToPrice; // @dev Returns the snatch window of the given token. function snatchWindowOf(uint256 _tokenId) public view returns (uint256 price) { return masterpieceToSnatchWindow[_tokenId]; } /// @dev Assigns ownership of a specific masterpiece to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Transfer ownership and update owner masterpiece counts. ownerMasterpieceCount[_to]++; masterpieceToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownerMasterpieceCount[_from]--; // clear any previously approved ownership exchange delete masterpieceToApproved[_tokenId]; } // Fire the transfer event. TransferToken(_from, _to, _tokenId); } /// @dev An internal method that creates a new masterpiece and stores it. /// @param _name The name of the masterpiece, e.g. Mona Lisa /// @param _artist The artist who created this masterpiece, e.g. Leonardo Da Vinci /// @param _owner The initial owner of this masterpiece function _createMasterpiece( string _name, string _artist, uint256 _price, uint256 _snatchWindow, address _owner ) internal returns (uint) { Masterpiece memory _masterpiece = Masterpiece({ name: _name, artist: _artist, birthTime: uint64(now) }); uint256 newMasterpieceId = masterpieces.push(_masterpiece) - 1; // Fire the birth event. Birth( _owner, newMasterpieceId, _snatchWindow, _masterpiece.name, _masterpiece.artist ); // Set the price for the masterpiece. masterpieceToPrice[newMasterpieceId] = _price; // Set the snatch window for the masterpiece. masterpieceToSnatchWindow[newMasterpieceId] = _snatchWindow; // This will assign ownership, and also fire the Transfer event as per ERC-721 draft. _transfer(0, _owner, newMasterpieceId); return newMasterpieceId; } } /// Pricing logic for CrytpoMasterpieces. contract MasterpiecePricing is MasterpieceBase { /*** CONSTANTS ***/ // Pricing steps. uint128 private constant FIRST_STEP_LIMIT = 0.05 ether; uint128 private constant SECOND_STEP_LIMIT = 0.5 ether; uint128 private constant THIRD_STEP_LIMIT = 2.0 ether; uint128 private constant FOURTH_STEP_LIMIT = 5.0 ether; /// @dev Computes the next listed price. /// @notice This contract doesn't handle setting the Masterpiece's next listing price. /// This next price is only used from inside bid() in MasterpieceAuction and inside /// purchase() in MasterpieceSale to set the next listed price. function setNextPriceOf(uint256 tokenId, uint256 salePrice) external whenNotPaused { // The next price of any token can only be set by the sale auction contract. // To set the next price for a token sold through the regular sale, use only // computeNextPrice and directly update the mapping. require(msg.sender == address(saleAuction)); masterpieceToPrice[tokenId] = computeNextPrice(salePrice); } /// @dev Computes next price of token given the current sale price. function computeNextPrice(uint256 salePrice) internal pure returns (uint256) { if (salePrice < FIRST_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 200), 95); } else if (salePrice < SECOND_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 135), 96); } else if (salePrice < THIRD_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 125), 97); } else if (salePrice < FOURTH_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 120), 97); } else { return SafeMath.div(SafeMath.mul(salePrice, 115), 98); } } /// @dev Computes the payment for the token, which is the sale price of the token /// minus the house's cut. function computePayment(uint256 salePrice) internal pure returns (uint256) { if (salePrice < FIRST_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 95), 100); } else if (salePrice < SECOND_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 96), 100); } else if (salePrice < FOURTH_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 97), 100); } else { return SafeMath.div(SafeMath.mul(salePrice, 98), 100); } } } /// Methods required for Non-Fungible Token Transactions in adherence to ERC721. contract MasterpieceOwnership is MasterpiecePricing, ERC721 { /// Name of the collection of NFTs managed by this contract, as defined in ERC721. string public constant NAME = "Masterpieces"; /// Symbol referencing the entire collection of NFTs managed in this contract, as /// defined in ERC721. string public constant SYMBOL = "CMP"; bytes4 public constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /// @dev Grant another address the right to transfer a specific Masterpiece via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Masterpiece that can be transferred if this call succeeds. /// @notice Required for ERC-20 and ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Fire approval event upon successful approval. Approval(msg.sender, _to, _tokenId); } /// @dev Transfers a Masterpiece to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 or else your /// Masterpiece may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Masterpiece to transfer. /// @notice Required for ERC-20 and ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Masterpieces (except very briefly // after a Masterpiece is created. require(_to != address(this)); // Disallow transfers to the auction contract to prevent accidental // misuse. Auction contracts should only take ownership of Masterpieces // through the approve and transferFrom flow. require(_to != address(saleAuction)); // You can only send your own Masterpiece. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, fire Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @dev Transfer a Masterpiece owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Masterpiece to be transfered. /// @param _to The address that should take ownership of the Masterpiece. Can be any /// address, including the caller. /// @param _tokenId The ID of the Masterpiece to be transferred. /// @notice Required for ERC-20 and ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and fires Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Returns a list of all Masterpiece IDs assigned to an address. /// @param _owner The owner whose Masterpieces we are interested in. /// This method MUST NEVER be called by smart contract code. First, it is fairly /// expensive (it walks the entire Masterpiece array looking for Masterpieces belonging /// to owner), but it also returns a dynamic array, which is only supported for web3 /// calls, and not contract-to-contract calls. Thus, this method is external rather /// than public. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Returns an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalMasterpieces = totalSupply(); uint256 resultIndex = 0; uint256 masterpieceId; for (masterpieceId = 0; masterpieceId <= totalMasterpieces; masterpieceId++) { if (masterpieceToOwner[masterpieceId] == _owner) { result[resultIndex] = masterpieceId; resultIndex++; } } return result; } } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721)); } // @notice Optional for ERC-20 compliance. function name() external pure returns (string) { return NAME; } // @notice Optional for ERC-20 compliance. function symbol() external pure returns (string) { return SYMBOL; } /// @dev Returns the address currently assigned ownership of a given Masterpiece. /// @notice Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = masterpieceToOwner[_tokenId]; require(owner != address(0)); } /// @dev Returns the total number of Masterpieces currently in existence. /// @notice Required for ERC-20 and ERC-721 compliance. function totalSupply() public view returns (uint) { return masterpieces.length; } /// @dev Returns the number of Masterpieces owned by a specific address. /// @param _owner The owner address to check. /// @notice Required for ERC-20 and ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 count) { return ownerMasterpieceCount[_owner]; } /// @dev Checks if a given address is the current owner of a particular Masterpiece. /// @param _claimant the address we are validating against. /// @param _tokenId Masterpiece id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return masterpieceToOwner[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Masterpieces on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { masterpieceToApproved[_tokenId] = _approved; } /// @dev Checks if a given address currently has transferApproval for a particular Masterpiece. /// @param _claimant the address we are confirming Masterpiece is approved for. /// @param _tokenId Masterpiece id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return masterpieceToApproved[_tokenId] == _claimant; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership MasterpieceOwnership public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 price, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct gets deleted. address seller = auction.seller; // Remove the auction before sending the fees to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); if (price > 0) { // Calculate the auctioneer's cut. uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); _transfer(msg.sender, _tokenId); // Update the next listing price of the token. nonFungibleContract.setNextPriceOf(_tokenId, price); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; MasterpieceOwnership candidateContract = MasterpieceOwnership(_nftAddress); require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Clock auction /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for the Masterpiece. Requires the sender /// is the Masterpiece Core contract because all bid methods /// should be wrapped. function bid(uint256 _tokenId) external payable { /* require(msg.sender == address(nonFungibleContract)); */ // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); } } contract MasterpieceAuction is MasterpieceOwnership { /// @dev Transfers the balance of the sale auction contract /// to the MasterpieceCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); } /// @notice The auction contract variable (saleAuction) is defined in MasterpieceBase /// to allow us to refer to them in MasterpieceOwnership to prevent accidental transfers. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - // https://github.com/Lunyr/crowdsale-contracts/blob/ // cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev The owner of a Masterpiece can put it up for auction. function createSaleAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Check that the Masterpiece to be put on an auction sale is owned by // its current owner. If it's already in an auction, this validation // will fail because the MasterpieceAuction contract owns the // Masterpiece once it is put on an auction sale. require(_owns(msg.sender, _tokenId)); _approve(_tokenId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer approval after escrow saleAuction.createAuction( _tokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract MasterpieceSale is MasterpieceAuction { // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable whenNotPaused { address newOwner = msg.sender; address oldOwner = masterpieceToOwner[_tokenId]; uint256 salePrice = masterpieceToPrice[_tokenId]; // Require that the masterpiece is either currently owned by the Masterpiece // Core contract or was born within the snatch window. require( (oldOwner == address(this)) || (now - masterpieces[_tokenId].birthTime <= masterpieceToSnatchWindow[_tokenId]) ); // Require that the owner of the token is not sending to self. require(oldOwner != newOwner); // Require that the Masterpiece is not in an auction by checking that // the Sale Clock Auction contract is not the owner. require(address(oldOwner) != address(saleAuction)); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Check that sent amount is greater than or equal to the sale price require(msg.value >= salePrice); uint256 payment = uint256(computePayment(salePrice)); uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice); // Set next listing price. masterpieceToPrice[_tokenId] = computeNextPrice(salePrice); // Transfer the Masterpiece to the buyer. _transfer(oldOwner, newOwner, _tokenId); // Pay seller of the Masterpiece if they are not this contract. if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, salePrice, masterpieceToPrice[_tokenId], oldOwner, newOwner, masterpieces[_tokenId].name); // Reimburse the buyer of any excess paid. msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return masterpieceToPrice[_tokenId]; } } contract MasterpieceMinting is MasterpieceSale { /*** CONSTANTS ***/ /// @dev Starting price of a regular Masterpiece. uint128 private constant STARTING_PRICE = 0.001 ether; /// @dev Limit of number of promo masterpieces that can be created. uint16 private constant PROMO_CREATION_LIMIT = 10000; /// @dev Counts the number of Promotional Masterpieces the contract owner has created. uint16 public promoMasterpiecesCreatedCount; /// @dev Reference to contract tracking Non Fungible Token ownership ERC721 public nonFungibleContract; /// @dev Creates a new Masterpiece with the given name and artist. function createMasterpiece( string _name, string _artist, uint256 _snatchWindow ) public onlyCurator returns (uint) { uint256 masterpieceId = _createMasterpiece(_name, _artist, STARTING_PRICE, _snatchWindow, address(this)); return masterpieceId; } /// @dev Creates a new promotional Masterpiece with the given name, artist, starting /// price, and owner. If the owner or the price is not set, we default them to the /// curator's address and the starting price for all masterpieces. function createPromoMasterpiece( string _name, string _artist, uint256 _snatchWindow, uint256 _price, address _owner ) public onlyCurator returns (uint) { require(promoMasterpiecesCreatedCount < PROMO_CREATION_LIMIT); address masterpieceOwner = _owner; if (masterpieceOwner == address(0)) { masterpieceOwner = curatorAddress; } if (_price <= 0) { _price = STARTING_PRICE; } uint256 masterpieceId = _createMasterpiece(_name, _artist, _price, _snatchWindow, masterpieceOwner); promoMasterpiecesCreatedCount++; return masterpieceId; } } /// CryptoMasterpieces: Collectible fine art masterpieces on the Ethereum blockchain. contract MasterpieceCore is MasterpieceMinting { // - MasterpieceAccessControl: This contract defines which users are granted the given roles that are // required to execute specific operations. // // - MasterpieceBase: This contract inherits from the MasterpieceAccessControl contract and defines // the core functionality of CryptoMasterpieces, including the data types, storage, and constants. // // - MasterpiecePricing: This contract inherits from the MasterpieceBase contract and defines // the pricing logic for CryptoMasterpieces. With every purchase made through the Core contract or // through a sale auction, the next listed price will multiply based on 5 price tiers. This ensures // that the Masterpiece bought through CryptoMasterpieces will always be adjusted to its fair market // value. // // - MasterpieceOwnership: This contract inherits from the MasterpiecePricing contract and the ERC-721 // (https://github.com/ethereum/EIPs/issues/721) contract and implements the methods required for // Non-Fungible Token Transactions. // // - MasterpieceAuction: This contract inherits from the MasterpieceOwnership contract. It defines // the Dutch "clock" auction mechanism for owners of a masterpiece to place it on sale. The auction // starts off at the automatically generated next price and until it is sold, decrements the price // as time passes. The owner of the masterpiece can cancel the auction at any point and the price // cannot go lower than the price that the owner bought the masterpiece for. // // - MasterpieceSale: This contract inherits from the MasterpieceAuction contract. It defines the // tiered pricing logic and handles all sales. It also checks that a Masterpiece is not in an // auction before approving a purchase. // // - MasterpieceMinting: This contract inherits from the MasterpieceSale contract. It defines the // creation of new regular and promotional masterpieces. // Set in case the core contract is broken and a fork is required address public newContractAddress; function MasterpieceCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Curator curatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes the fee on every /// masterpiece sold and any Ether sent directly to the contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific masterpiece. /// @param _tokenId The tokenId of the masterpiece of interest. function getMasterpiece(uint256 _tokenId) external view returns ( string name, string artist, uint256 birthTime, uint256 snatchWindow, uint256 sellingPrice, address owner ) { Masterpiece storage masterpiece = masterpieces[_tokenId]; name = masterpiece.name; artist = masterpiece.artist; birthTime = uint256(masterpiece.birthTime); snatchWindow = masterpieceToSnatchWindow[_tokenId]; sellingPrice = masterpieceToPrice[_tokenId]; owner = masterpieceToOwner[_tokenId]; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
Bids on an open auction, completing the auction and transferring ownership of the NFT if enough Ether is supplied. _tokenId - ID of token to bid on. _bid will throw if the bid or funds transfer fails
function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); }
13,019,527
./partial_match/1/0x5F1127EcbEeC10cb614A62869AD7DA2f9358343d/sources/NiftyBuilderInstance.sol
Determine whether it is possible to mint additional NFTs for this 'niftyType'./
function _getFinalized(uint256 niftyType) public view returns (bool) { bytes32 chunk = _finalized[niftyType / 256]; return (chunk & bytes32(1 << (niftyType % 256))) != 0x0; }
4,355,424
./full_match/5/0x08E378582640443af63a45630c4a3e2F37883E4A/sources/project_/contracts/KeyDictionary.sol
Authorizes a requested key. proposalId The ID of the key request proposal. key The key to authorize.
function authorizeKey(uint256 proposalId, bytes32 key) public { require(proposalId < proposalIdCounter, "KeyDictionary: invalid proposalId"); require(keyToWallet[key] == address(0), "KeyDictionary: key already exists"); CustomerData storage data = customerData[key]; require(data.registered == false, "KeyDictionary: key already registered"); data.registered = true; data.owner = msg.sender; walletToKey[data.wallet] = key; keyToWallet[key] = data.wallet; }
7,033,539
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract TheAO { address public theAO; address public nameTAOPositionAddress; // Check whether an address is whitelisted and granted access to transact // on behalf of others mapping (address => bool) public whitelist; constructor() public { theAO = msg.sender; } /** * @dev Checks if msg.sender is in whitelist. */ modifier inWhitelist() { require (whitelist[msg.sender] == true); _; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public { require (msg.sender == theAO); require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public { require (msg.sender == theAO); require (_account != address(0)); whitelist[_account] = _whitelist; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /** * @title TAOCurrency */ contract TAOCurrency is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals; // To differentiate denomination of TAO Currency uint256 public powerOfTen; uint256 public totalSupply; // This creates an array with all balances // address is the address of nameId, not the eth public address mapping (address => uint256) public balanceOf; // This generates a public event on the blockchain that will notify clients // address is the address of TAO/Name Id, not eth public address event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt // address is the address of TAO/Name Id, not eth public address event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) { _transfer(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) { _mintToken(target, mintedAmount); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title TAO */ contract TAO { using SafeMath for uint256; address public vaultAddress; string public name; // the name for this TAO address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address // TAO's data string public datHash; string public database; string public keyValue; bytes32 public contentId; /** * 0 = TAO * 1 = Name */ uint8 public typeId; /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress ) public { name = _name; originId = _originId; datHash = _datHash; database = _database; keyValue = _keyValue; contentId = _contentId; // Creating TAO typeId = 0; vaultAddress = _vaultAddress; } /** * @dev Checks if calling address is Vault contract */ modifier onlyVault { require (msg.sender == vaultAddress); _; } /** * @dev Allows Vault to transfer `_amount` of ETH from this TAO to `_recipient` * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferEth(address _recipient, uint256 _amount) public onlyVault returns (bool) { _recipient.transfer(_amount); return true; } /** * @dev Allows Vault to transfer `_amount` of ERC20 Token from this TAO to `_recipient` * @param _erc20TokenAddress The address of ERC20 Token * @param _recipient The recipient address * @param _amount The amount to transfer * @return true on success */ function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) { TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress); _erc20.transfer(_recipient, _amount); return true; } } /** * @title Position */ contract Position is TheAO { using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 4; uint256 constant public MAX_SUPPLY_PER_NAME = 100 * (10 ** 4); uint256 public totalSupply; // Mapping from Name ID to bool value whether or not it has received Position Token mapping (address => bool) public receivedToken; // Mapping from Name ID to its total available balance mapping (address => uint256) public balanceOf; // Mapping from Name's TAO ID to its staked amount mapping (address => mapping(address => uint256)) public taoStakedBalance; // Mapping from TAO ID to its total staked amount mapping (address => uint256) public totalTAOStakedBalance; // This generates a public event on the blockchain that will notify clients event Mint(address indexed nameId, uint256 value); event Stake(address indexed nameId, address indexed taoId, uint256 value); event Unstake(address indexed nameId, address indexed taoId, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor (uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply; // Update total supply balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Create `MAX_SUPPLY_PER_NAME` tokens and send it to `_nameId` * @param _nameId Address to receive the tokens * @return true on success */ function mintToken(address _nameId) public inWhitelist returns (bool) { // Make sure _nameId has not received Position Token require (receivedToken[_nameId] == false); receivedToken[_nameId] = true; balanceOf[_nameId] = balanceOf[_nameId].add(MAX_SUPPLY_PER_NAME); totalSupply = totalSupply.add(MAX_SUPPLY_PER_NAME); emit Mint(_nameId, MAX_SUPPLY_PER_NAME); return true; } /** * @dev Get staked balance of `_nameId` * @param _nameId The Name ID to be queried * @return total staked balance */ function stakedBalance(address _nameId) public view returns (uint256) { return MAX_SUPPLY_PER_NAME.sub(balanceOf[_nameId]); } /** * @dev Stake `_value` tokens on `_taoId` from `_nameId` * @param _nameId The Name ID that wants to stake * @param _taoId The TAO ID to stake * @param _value The amount to stake * @return true on success */ function stake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (balanceOf[_nameId] >= _value); // Check if the targeted balance is enough balanceOf[_nameId] = balanceOf[_nameId].sub(_value); // Subtract from the targeted balance taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].add(_value); // Add to the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].add(_value); emit Stake(_nameId, _taoId, _value); return true; } /** * @dev Unstake `_value` tokens from `_nameId`'s `_taoId` * @param _nameId The Name ID that wants to unstake * @param _taoId The TAO ID to unstake * @param _value The amount to unstake * @return true on success */ function unstake(address _nameId, address _taoId, uint256 _value) public inWhitelist returns (bool) { require (_value > 0 && _value <= MAX_SUPPLY_PER_NAME); require (taoStakedBalance[_nameId][_taoId] >= _value); // Check if the targeted staked balance is enough require (totalTAOStakedBalance[_taoId] >= _value); // Check if the total targeted staked balance is enough taoStakedBalance[_nameId][_taoId] = taoStakedBalance[_nameId][_taoId].sub(_value); // Subtract from the targeted staked balance totalTAOStakedBalance[_taoId] = totalTAOStakedBalance[_taoId].sub(_value); balanceOf[_nameId] = balanceOf[_nameId].add(_value); // Add to the targeted balance emit Unstake(_nameId, _taoId, _value); return true; } } /** * @title NameTAOLookup * */ contract NameTAOLookup is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; struct NameTAOInfo { string name; address nameTAOAddress; string parentName; uint256 typeId; // 0 = TAO. 1 = Name } uint256 public internalId; uint256 public totalNames; uint256 public totalTAOs; mapping (uint256 => NameTAOInfo) internal nameTAOInfos; mapping (bytes32 => uint256) internal internalIdLookup; /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a name exist in the list * @param _name The name to be checked * @return true if yes, false otherwise */ function isExist(string _name) public view returns (bool) { bytes32 _nameKey = keccak256(abi.encodePacked(_name)); return (internalIdLookup[_nameKey] > 0); } /** * @dev Add a new NameTAOInfo * @param _name The name of the Name/TAO * @param _nameTAOAddress The address of the Name/TAO * @param _parentName The parent name of the Name/TAO * @param _typeId If TAO = 0. Name = 1 * @return true on success */ function add(string _name, address _nameTAOAddress, string _parentName, uint256 _typeId) public onlyFactory returns (bool) { require (bytes(_name).length > 0); require (_nameTAOAddress != address(0)); require (bytes(_parentName).length > 0); require (_typeId == 0 || _typeId == 1); require (!isExist(_name)); internalId++; bytes32 _nameKey = keccak256(abi.encodePacked(_name)); internalIdLookup[_nameKey] = internalId; NameTAOInfo storage _nameTAOInfo = nameTAOInfos[internalId]; _nameTAOInfo.name = _name; _nameTAOInfo.nameTAOAddress = _nameTAOAddress; _nameTAOInfo.parentName = _parentName; _nameTAOInfo.typeId = _typeId; if (_typeId == 0) { totalTAOs++; } else { totalNames++; } return true; } /** * @dev Get the NameTAOInfo given a name * @param _name The name to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByName(string _name) public view returns (string, address, string, uint256) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Get the NameTAOInfo given an ID * @param _internalId The internal ID to be queried * @return the name of Name/TAO * @return the address of Name/TAO * @return the parent name of Name/TAO * @return type ID. 0 = TAO. 1 = Name */ function getByInternalId(uint256 _internalId) public view returns (string, address, string, uint256) { require (nameTAOInfos[_internalId].nameTAOAddress != address(0)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[_internalId]; return ( _nameTAOInfo.name, _nameTAOInfo.nameTAOAddress, _nameTAOInfo.parentName, _nameTAOInfo.typeId ); } /** * @dev Return the nameTAOAddress given a _name * @param _name The name to be queried * @return the nameTAOAddress of the name */ function getAddressByName(string _name) public view returns (address) { require (isExist(_name)); bytes32 _nameKey = keccak256(abi.encodePacked(_name)); NameTAOInfo memory _nameTAOInfo = nameTAOInfos[internalIdLookup[_nameKey]]; return _nameTAOInfo.nameTAOAddress; } } /** * @title NamePublicKey */ contract NamePublicKey { using SafeMath for uint256; address public nameFactoryAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; struct PublicKey { bool created; address defaultKey; address[] keys; } // Mapping from nameId to its PublicKey mapping (address => PublicKey) internal publicKeys; // Event to be broadcasted to public when a publicKey is added to a Name event AddKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is removed from a Name event RemoveKey(address indexed nameId, address publicKey, uint256 nonce); // Event to be broadcasted to public when a publicKey is set as default for a Name event SetDefaultKey(address indexed nameId, address publicKey, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name ID exist in the list of Public Keys * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return publicKeys[_id].created; } /** * @dev Store the PublicKey info for a Name * @param _id The ID of the Name * @param _defaultKey The default public key for this Name * @return true on success */ function add(address _id, address _defaultKey) public isName(_id) onlyFactory returns (bool) { require (!isExist(_id)); require (_defaultKey != address(0)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.created = true; _publicKey.defaultKey = _defaultKey; _publicKey.keys.push(_defaultKey); return true; } /** * @dev Get total publicKeys count for a Name * @param _id The ID of the Name * @return total publicKeys count */ function getTotalPublicKeysCount(address _id) public isName(_id) view returns (uint256) { require (isExist(_id)); return publicKeys[_id].keys.length; } /** * @dev Check whether or not a publicKey exist in the list for a Name * @param _id The ID of the Name * @param _key The publicKey to check * @return true if yes. false otherwise */ function isKeyExist(address _id, address _key) isName(_id) public view returns (bool) { require (isExist(_id)); require (_key != address(0)); PublicKey memory _publicKey = publicKeys[_id]; for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { return true; } } return false; } /** * @dev Add publicKey to list for a Name * @param _id The ID of the Name * @param _key The publicKey to be added */ function addKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (!isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.keys.push(_key); uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit AddKey(_id, _key, _nonce); } /** * @dev Get default public key of a Name * @param _id The ID of the Name * @return the default public key */ function getDefaultKey(address _id) public isName(_id) view returns (address) { require (isExist(_id)); return publicKeys[_id].defaultKey; } /** * @dev Get list of publicKeys of a Name * @param _id The ID of the Name * @param _from The starting index * @param _to The ending index * @return list of publicKeys */ function getKeys(address _id, uint256 _from, uint256 _to) public isName(_id) view returns (address[]) { require (isExist(_id)); require (_from >= 0 && _to >= _from); PublicKey memory _publicKey = publicKeys[_id]; require (_publicKey.keys.length > 0); address[] memory _keys = new address[](_to.sub(_from).add(1)); if (_to > _publicKey.keys.length.sub(1)) { _to = _publicKey.keys.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _keys[i.sub(_from)] = _publicKey.keys[i]; } return _keys; } /** * @dev Remove publicKey from the list * @param _id The ID of the Name * @param _key The publicKey to be removed */ function removeKey(address _id, address _key) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _key)); PublicKey storage _publicKey = publicKeys[_id]; // Can't remove default key require (_key != _publicKey.defaultKey); require (_publicKey.keys.length > 1); for (uint256 i = 0; i < _publicKey.keys.length; i++) { if (_publicKey.keys[i] == _key) { delete _publicKey.keys[i]; _publicKey.keys.length--; uint256 _nonce = _nameFactory.incrementNonce(_id); break; } } require (_nonce > 0); emit RemoveKey(_id, _key, _nonce); } /** * @dev Set a publicKey as the default for a Name * @param _id The ID of the Name * @param _defaultKey The defaultKey to be set * @param _signatureV The V part of the signature for this update * @param _signatureR The R part of the signature for this update * @param _signatureS The S part of the signature for this update */ function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) { require (isExist(_id)); require (isKeyExist(_id, _defaultKey)); bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey)); require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender); PublicKey storage _publicKey = publicKeys[_id]; _publicKey.defaultKey = _defaultKey; uint256 _nonce = _nameFactory.incrementNonce(_id); require (_nonce > 0); emit SetDefaultKey(_id, _defaultKey, _nonce); } } /** * @title NameFactory * * The purpose of this contract is to allow node to create Name */ contract NameFactory is TheAO { using SafeMath for uint256; address public positionAddress; address public nameTAOVaultAddress; address public nameTAOLookupAddress; address public namePublicKeyAddress; Position internal _position; NameTAOLookup internal _nameTAOLookup; NameTAOPosition internal _nameTAOPosition; NamePublicKey internal _namePublicKey; address[] internal names; // Mapping from eth address to Name ID mapping (address => address) public ethAddressToNameId; // Mapping from Name ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when a Name is created event CreateName(address indexed ethAddress, address nameId, uint256 index, string name); /** * @dev Constructor function */ constructor(address _positionAddress, address _nameTAOVaultAddress) public { positionAddress = _positionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _position = Position(positionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update Name's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == namePublicKeyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the NameTAOLookup Address * @param _nameTAOLookupAddress The address of NameTAOLookup */ function setNameTAOLookupAddress(address _nameTAOLookupAddress) public onlyTheAO { require (_nameTAOLookupAddress != address(0)); nameTAOLookupAddress = _nameTAOLookupAddress; _nameTAOLookup = NameTAOLookup(nameTAOLookupAddress); } /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(nameTAOPositionAddress); } /** * @dev The AO set the NamePublicKey Address * @param _namePublicKeyAddress The address of NamePublicKey */ function setNamePublicKeyAddress(address _namePublicKeyAddress) public onlyTheAO { require (_namePublicKeyAddress != address(0)); namePublicKeyAddress = _namePublicKeyAddress; _namePublicKey = NamePublicKey(namePublicKeyAddress); } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a Name * @param _nameId The ID of the Name * @return current nonce */ function incrementNonce(address _nameId) public canUpdateNonce returns (uint256) { // Check if _nameId exist require (nonces[_nameId] > 0); nonces[_nameId]++; return nonces[_nameId]; } /** * @dev Create a Name * @param _name The name of the Name * @param _datHash The datHash to this Name's profile * @param _database The database for this Name * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this Name */ function createName(string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId) public { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); // Only one Name per ETH address require (ethAddressToNameId[msg.sender] == address(0)); // The address is the Name ID (which is also a TAO ID) address nameId = new Name(_name, msg.sender, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[nameId]++; ethAddressToNameId[msg.sender] = nameId; // Store the name lookup information require (_nameTAOLookup.add(_name, nameId, 'human', 1)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(nameId, nameId, nameId, nameId)); // Store the public key information require (_namePublicKey.add(nameId, msg.sender)); names.push(nameId); // Need to mint Position token for this Name require (_position.mintToken(nameId)); emit CreateName(msg.sender, nameId, names.length.sub(1), _name); } /** * @dev Get Name information * @param _nameId The ID of the Name to be queried * @return The name of the Name * @return The originId of the Name (in this case, it's the creator node's ETH address) * @return The datHash of the Name * @return The database of the Name * @return The keyValue of the Name * @return The contentId of the Name * @return The typeId of the Name */ function getName(address _nameId) public view returns (string, address, string, string, string, bytes32, uint8) { Name _name = Name(_nameId); return ( _name.name(), _name.originId(), _name.datHash(), _name.database(), _name.keyValue(), _name.contentId(), _name.typeId() ); } /** * @dev Get total Names count * @return total Names count */ function getTotalNamesCount() public view returns (uint256) { return names.length; } /** * @dev Get list of Name IDs * @param _from The starting index * @param _to The ending index * @return list of Name IDs */ function getNameIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from); require (names.length > 0); address[] memory _names = new address[](_to.sub(_from).add(1)); if (_to > names.length.sub(1)) { _to = names.length.sub(1); } for (uint256 i = _from; i <= _to; i++) { _names[i.sub(_from)] = names[i]; } return _names; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be Name's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The name of the Name * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise */ function validateNameSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public view returns (bool) { require (_nameTAOLookup.isExist(_name)); address _nameId = _nameTAOLookup.getAddressByName(_name); address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_validateAddress != address(0)) { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _validateAddress && _namePublicKey.isKeyExist(_nameId, _validateAddress) ); } else { return ( _nonce == nonces[_nameId].add(1) && _signatureAddress == _namePublicKey.getDefaultKey(_nameId) ); } } } /** * @title AOStringSetting * * This contract stores all AO string setting variables */ contract AOStringSetting is TheAO { // Mapping from settingId to it's actual string value mapping (uint256 => string) public settingValue; // Mapping from settingId to it's potential string value that is at pending state mapping (uint256 => string) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The string value to be set */ function setPendingValue(uint256 _settingId, string _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { string memory _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBytesSetting * * This contract stores all AO bytes32 setting variables */ contract AOBytesSetting is TheAO { // Mapping from settingId to it's actual bytes32 value mapping (uint256 => bytes32) public settingValue; // Mapping from settingId to it's potential bytes32 value that is at pending state mapping (uint256 => bytes32) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bytes32 value to be set */ function setPendingValue(uint256 _settingId, bytes32 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bytes32 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOAddressSetting * * This contract stores all AO address setting variables */ contract AOAddressSetting is TheAO { // Mapping from settingId to it's actual address value mapping (uint256 => address) public settingValue; // Mapping from settingId to it's potential address value that is at pending state mapping (uint256 => address) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The address value to be set */ function setPendingValue(uint256 _settingId, address _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { address _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOBoolSetting * * This contract stores all AO bool setting variables */ contract AOBoolSetting is TheAO { // Mapping from settingId to it's actual bool value mapping (uint256 => bool) public settingValue; // Mapping from settingId to it's potential bool value that is at pending state mapping (uint256 => bool) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The bool value to be set */ function setPendingValue(uint256 _settingId, bool _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { bool _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOUintSetting * * This contract stores all AO uint256 setting variables */ contract AOUintSetting is TheAO { // Mapping from settingId to it's actual uint256 value mapping (uint256 => uint256) public settingValue; // Mapping from settingId to it's potential uint256 value that is at pending state mapping (uint256 => uint256) public pendingValue; /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /***** PUBLIC METHODS *****/ /** * @dev Set pending value * @param _settingId The ID of the setting * @param _value The uint256 value to be set */ function setPendingValue(uint256 _settingId, uint256 _value) public inWhitelist { pendingValue[_settingId] = _value; } /** * @dev Move value from pending to setting * @param _settingId The ID of the setting */ function movePendingToSetting(uint256 _settingId) public inWhitelist { uint256 _tempValue = pendingValue[_settingId]; delete pendingValue[_settingId]; settingValue[_settingId] = _tempValue; } } /** * @title AOSettingAttribute * * This contract stores all AO setting data/state */ contract AOSettingAttribute is TheAO { NameTAOPosition internal _nameTAOPosition; struct SettingData { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created the setting address creatorTAOId; // The taoId that created the setting address associatedTAOId; // The taoId that the setting affects string settingName; // The human-readable name of the setting /** * 1 => uint256 * 2 => bool * 3 => address * 4 => bytes32 * 5 => string (catch all) */ uint8 settingType; bool pendingCreate; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting string settingDataJSON; // Catch-all } struct SettingState { uint256 settingId; // Identifier of this setting bool pendingUpdate; // State when setting is in process of being updated address updateAdvocateNameId; // The nameId of the Advocate that performed the update /** * A child of the associatedTAOId with the update Logos. * This tells the setting contract that there is a proposal TAO that is a Child TAO * of the associated TAO, which will be responsible for deciding if the update to the * setting is accepted or rejected. */ address proposalTAOId; /** * Signature of the proposalTAOId and update value by the associatedTAOId * Advocate's Name's address. */ string updateSignature; /** * The proposalTAOId moves here when setting value changes successfully */ address lastUpdateTAOId; string settingStateJSON; // Catch-all } struct SettingDeprecation { uint256 settingId; // Identifier of this setting address creatorNameId; // The nameId that created this deprecation address creatorTAOId; // The taoId that created this deprecation address associatedTAOId; // The taoId that the setting affects bool pendingDeprecated; // State when associatedTAOId has not accepted setting bool locked; // State when pending anything (cannot change if locked) bool rejected; // State when associatedTAOId rejected this setting bool migrated; // State when this setting is fully migrated // holds the pending new settingId value when a deprecation is set uint256 pendingNewSettingId; // holds the new settingId that has been approved by associatedTAOId uint256 newSettingId; // holds the pending new contract address for this setting address pendingNewSettingContractAddress; // holds the new contract address for this setting address newSettingContractAddress; } struct AssociatedTAOSetting { bytes32 associatedTAOSettingId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSetting { bytes32 creatorTAOSettingId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } struct AssociatedTAOSettingDeprecation { bytes32 associatedTAOSettingDeprecationId; // Identifier address associatedTAOId; // The TAO ID that the setting is associated to uint256 settingId; // The Setting ID that is associated with the TAO ID } struct CreatorTAOSettingDeprecation { bytes32 creatorTAOSettingDeprecationId; // Identifier address creatorTAOId; // The TAO ID that the setting was created from uint256 settingId; // The Setting ID created from the TAO ID } // Mapping from settingId to it's data mapping (uint256 => SettingData) internal settingDatas; // Mapping from settingId to it's state mapping (uint256 => SettingState) internal settingStates; // Mapping from settingId to it's deprecation info mapping (uint256 => SettingDeprecation) internal settingDeprecations; // Mapping from associatedTAOSettingId to AssociatedTAOSetting mapping (bytes32 => AssociatedTAOSetting) internal associatedTAOSettings; // Mapping from creatorTAOSettingId to CreatorTAOSetting mapping (bytes32 => CreatorTAOSetting) internal creatorTAOSettings; // Mapping from associatedTAOSettingDeprecationId to AssociatedTAOSettingDeprecation mapping (bytes32 => AssociatedTAOSettingDeprecation) internal associatedTAOSettingDeprecations; // Mapping from creatorTAOSettingDeprecationId to CreatorTAOSettingDeprecation mapping (bytes32 => CreatorTAOSettingDeprecation) internal creatorTAOSettingDeprecations; /** * @dev Constructor function */ constructor(address _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Add setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return The ID of the "Associated" setting * @return The ID of the "Creator" setting */ function add(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) public inWhitelist returns (bytes32, bytes32) { // Store setting data/state require (_storeSettingDataState(_settingId, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData)); // Store the associatedTAOSetting info bytes32 _associatedTAOSettingId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSetting storage _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; _associatedTAOSetting.associatedTAOSettingId = _associatedTAOSettingId; _associatedTAOSetting.associatedTAOId = _associatedTAOId; _associatedTAOSetting.settingId = _settingId; // Store the creatorTAOSetting info bytes32 _creatorTAOSettingId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSetting storage _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; _creatorTAOSetting.creatorTAOSettingId = _creatorTAOSettingId; _creatorTAOSetting.creatorTAOId = _creatorTAOId; _creatorTAOSetting.settingId = _settingId; return (_associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Get Setting Data of a setting ID * @param _settingId The ID of the setting */ function getSettingData(uint256 _settingId) public view returns (uint256, address, address, address, string, uint8, bool, bool, bool, string) { SettingData memory _settingData = settingDatas[_settingId]; return ( _settingData.settingId, _settingData.creatorNameId, _settingData.creatorTAOId, _settingData.associatedTAOId, _settingData.settingName, _settingData.settingType, _settingData.pendingCreate, _settingData.locked, _settingData.rejected, _settingData.settingDataJSON ); } /** * @dev Get Associated TAO Setting info * @param _associatedTAOSettingId The ID of the associated tao setting */ function getAssociatedTAOSetting(bytes32 _associatedTAOSettingId) public view returns (bytes32, address, uint256) { AssociatedTAOSetting memory _associatedTAOSetting = associatedTAOSettings[_associatedTAOSettingId]; return ( _associatedTAOSetting.associatedTAOSettingId, _associatedTAOSetting.associatedTAOId, _associatedTAOSetting.settingId ); } /** * @dev Get Creator TAO Setting info * @param _creatorTAOSettingId The ID of the creator tao setting */ function getCreatorTAOSetting(bytes32 _creatorTAOSettingId) public view returns (bytes32, address, uint256) { CreatorTAOSetting memory _creatorTAOSetting = creatorTAOSettings[_creatorTAOSettingId]; return ( _creatorTAOSetting.creatorTAOSettingId, _creatorTAOSetting.creatorTAOId, _creatorTAOSetting.settingId ); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveAdd(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingData.locked = false; } else { // Reject the setting _settingData.pendingCreate = false; _settingData.rejected = true; } return true; } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeAdd(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == true && _settingData.locked == false && _settingData.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.creatorTAOId) ); // Update the setting data _settingData.pendingCreate = false; _settingData.locked = true; return true; } /** * @dev Store setting update data * @param _settingId The ID of the setting to be updated * @param _settingType The type of this setting * @param _associatedTAOAdvocate The setting's associatedTAOId's advocate's name address * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by _associatedTAOAdvocate * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function update(uint256 _settingId, uint8 _settingType, address _associatedTAOAdvocate, address _proposalTAOId, string _updateSignature, string _extraData) public inWhitelist returns (bool) { // Make sure setting is created SettingData memory _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.settingType == _settingType && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) && bytes(_updateSignature).length > 0 ); // Make sure setting is not in the middle of updating SettingState storage _settingState = settingStates[_settingId]; require (_settingState.pendingUpdate == false); // Make sure setting is not yet deprecated SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; if (_settingDeprecation.settingId == _settingId) { require (_settingDeprecation.migrated == false); } // Store the SettingState data _settingState.pendingUpdate = true; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; _settingState.proposalTAOId = _proposalTAOId; _settingState.updateSignature = _updateSignature; _settingState.settingStateJSON = _extraData; return true; } /** * @dev Get setting state * @param _settingId The ID of the setting */ function getSettingState(uint256 _settingId) public view returns (uint256, bool, address, address, string, address, string) { SettingState memory _settingState = settingStates[_settingId]; return ( _settingState.settingId, _settingState.pendingUpdate, _settingState.updateAdvocateNameId, _settingState.proposalTAOId, _settingState.updateSignature, _settingState.lastUpdateTAOId, _settingState.settingStateJSON ); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _proposalTAOAdvocate The advocate of the proposal TAO * @param _approved Whether to approve or reject * @return true on success */ function approveUpdate(uint256 _settingId, address _proposalTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == true && _settingData.rejected == false); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _proposalTAOAdvocate != address(0) && _proposalTAOAdvocate == _nameTAOPosition.getAdvocate(_settingState.proposalTAOId) ); if (_approved) { // Unlock the setting so that advocate of associatedTAOId can finalize the update _settingData.locked = false; } else { // Set pendingUpdate to false _settingState.pendingUpdate = false; _settingState.proposalTAOId = address(0); } return true; } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized * @param _associatedTAOAdvocate The advocate of the associated TAO * @return true on success */ function finalizeUpdate(uint256 _settingId, address _associatedTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting is created SettingData storage _settingData = settingDatas[_settingId]; require (_settingData.settingId == _settingId && _settingData.pendingCreate == false && _settingData.locked == false && _settingData.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingData.associatedTAOId) ); // Make sure setting update exists and needs approval SettingState storage _settingState = settingStates[_settingId]; require (_settingState.settingId == _settingId && _settingState.pendingUpdate == true && _settingState.proposalTAOId != address(0)); // Update the setting data _settingData.locked = true; // Update the setting state _settingState.pendingUpdate = false; _settingState.updateAdvocateNameId = _associatedTAOAdvocate; address _proposalTAOId = _settingState.proposalTAOId; _settingState.proposalTAOId = address(0); _settingState.lastUpdateTAOId = _proposalTAOId; return true; } /** * @dev Add setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return The ID of the "Associated" setting deprecation * @return The ID of the "Creator" setting deprecation */ function addDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) public inWhitelist returns (bytes32, bytes32) { require (_storeSettingDeprecation(_settingId, _creatorNameId, _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress)); // Store the associatedTAOSettingDeprecation info bytes32 _associatedTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _associatedTAOId, _settingId)); AssociatedTAOSettingDeprecation storage _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId = _associatedTAOSettingDeprecationId; _associatedTAOSettingDeprecation.associatedTAOId = _associatedTAOId; _associatedTAOSettingDeprecation.settingId = _settingId; // Store the creatorTAOSettingDeprecation info bytes32 _creatorTAOSettingDeprecationId = keccak256(abi.encodePacked(this, _creatorTAOId, _settingId)); CreatorTAOSettingDeprecation storage _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId = _creatorTAOSettingDeprecationId; _creatorTAOSettingDeprecation.creatorTAOId = _creatorTAOId; _creatorTAOSettingDeprecation.settingId = _settingId; return (_associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Get Setting Deprecation info of a setting ID * @param _settingId The ID of the setting */ function getSettingDeprecation(uint256 _settingId) public view returns (uint256, address, address, address, bool, bool, bool, bool, uint256, uint256, address, address) { SettingDeprecation memory _settingDeprecation = settingDeprecations[_settingId]; return ( _settingDeprecation.settingId, _settingDeprecation.creatorNameId, _settingDeprecation.creatorTAOId, _settingDeprecation.associatedTAOId, _settingDeprecation.pendingDeprecated, _settingDeprecation.locked, _settingDeprecation.rejected, _settingDeprecation.migrated, _settingDeprecation.pendingNewSettingId, _settingDeprecation.newSettingId, _settingDeprecation.pendingNewSettingContractAddress, _settingDeprecation.newSettingContractAddress ); } /** * @dev Get Associated TAO Setting Deprecation info * @param _associatedTAOSettingDeprecationId The ID of the associated tao setting deprecation */ function getAssociatedTAOSettingDeprecation(bytes32 _associatedTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { AssociatedTAOSettingDeprecation memory _associatedTAOSettingDeprecation = associatedTAOSettingDeprecations[_associatedTAOSettingDeprecationId]; return ( _associatedTAOSettingDeprecation.associatedTAOSettingDeprecationId, _associatedTAOSettingDeprecation.associatedTAOId, _associatedTAOSettingDeprecation.settingId ); } /** * @dev Get Creator TAO Setting Deprecation info * @param _creatorTAOSettingDeprecationId The ID of the creator tao setting deprecation */ function getCreatorTAOSettingDeprecation(bytes32 _creatorTAOSettingDeprecationId) public view returns (bytes32, address, uint256) { CreatorTAOSettingDeprecation memory _creatorTAOSettingDeprecation = creatorTAOSettingDeprecations[_creatorTAOSettingDeprecationId]; return ( _creatorTAOSettingDeprecation.creatorTAOSettingDeprecationId, _creatorTAOSettingDeprecation.creatorTAOId, _creatorTAOSettingDeprecation.settingId ); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves deprecation * @param _settingId The ID of the setting to approve * @param _associatedTAOAdvocate The advocate of the associated TAO * @param _approved Whether to approve or reject * @return true on success */ function approveDeprecation(uint256 _settingId, address _associatedTAOAdvocate, bool _approved) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == true && _settingDeprecation.rejected == false && _associatedTAOAdvocate != address(0) && _associatedTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.associatedTAOId) ); if (_approved) { // Unlock the setting so that advocate of creatorTAOId can finalize the creation _settingDeprecation.locked = false; } else { // Reject the setting _settingDeprecation.pendingDeprecated = false; _settingDeprecation.rejected = true; } return true; } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized * @param _creatorTAOAdvocate The advocate of the creator TAO * @return true on success */ function finalizeDeprecation(uint256 _settingId, address _creatorTAOAdvocate) public inWhitelist returns (bool) { // Make sure setting exists and needs approval SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; require (_settingDeprecation.settingId == _settingId && _settingDeprecation.migrated == false && _settingDeprecation.pendingDeprecated == true && _settingDeprecation.locked == false && _settingDeprecation.rejected == false && _creatorTAOAdvocate != address(0) && _creatorTAOAdvocate == _nameTAOPosition.getAdvocate(_settingDeprecation.creatorTAOId) ); // Update the setting data _settingDeprecation.pendingDeprecated = false; _settingDeprecation.locked = true; _settingDeprecation.migrated = true; uint256 _newSettingId = _settingDeprecation.pendingNewSettingId; _settingDeprecation.pendingNewSettingId = 0; _settingDeprecation.newSettingId = _newSettingId; address _newSettingContractAddress = _settingDeprecation.pendingNewSettingContractAddress; _settingDeprecation.pendingNewSettingContractAddress = address(0); _settingDeprecation.newSettingContractAddress = _newSettingContractAddress; return true; } /** * @dev Check if a setting exist and not rejected * @param _settingId The ID of the setting * @return true if exist. false otherwise */ function settingExist(uint256 _settingId) public view returns (bool) { SettingData memory _settingData = settingDatas[_settingId]; return (_settingData.settingId == _settingId && _settingData.rejected == false); } /** * @dev Get the latest ID of a deprecated setting, if exist * @param _settingId The ID of the setting * @return The latest setting ID */ function getLatestSettingId(uint256 _settingId) public view returns (uint256) { (,,,,,,, bool _migrated,, uint256 _newSettingId,,) = getSettingDeprecation(_settingId); while (_migrated && _newSettingId > 0) { _settingId = _newSettingId; (,,,,,,, _migrated,, _newSettingId,,) = getSettingDeprecation(_settingId); } return _settingId; } /***** Internal Method *****/ /** * @dev Store setting data/state * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist * @return true on success */ function _storeSettingDataState(uint256 _settingId, address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal returns (bool) { // Store setting data SettingData storage _settingData = settingDatas[_settingId]; _settingData.settingId = _settingId; _settingData.creatorNameId = _creatorNameId; _settingData.creatorTAOId = _creatorTAOId; _settingData.associatedTAOId = _associatedTAOId; _settingData.settingName = _settingName; _settingData.settingType = _settingType; _settingData.pendingCreate = true; _settingData.locked = true; _settingData.settingDataJSON = _extraData; // Store setting state SettingState storage _settingState = settingStates[_settingId]; _settingState.settingId = _settingId; return true; } /** * @dev Store setting deprecation * @param _settingId The ID of the setting * @param _creatorNameId The nameId that created the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _newSettingId The new settingId value to route * @param _newSettingContractAddress The address of the new setting contract to route * @return true on success */ function _storeSettingDeprecation(uint256 _settingId, address _creatorNameId, address _creatorTAOId, address _associatedTAOId, uint256 _newSettingId, address _newSettingContractAddress) internal returns (bool) { // Make sure this setting exists require (settingDatas[_settingId].creatorNameId != address(0) && settingDatas[_settingId].rejected == false && settingDatas[_settingId].pendingCreate == false); // Make sure deprecation is not yet exist for this setting Id require (settingDeprecations[_settingId].creatorNameId == address(0)); // Make sure newSettingId exists require (settingDatas[_newSettingId].creatorNameId != address(0) && settingDatas[_newSettingId].rejected == false && settingDatas[_newSettingId].pendingCreate == false); // Make sure the settingType matches require (settingDatas[_settingId].settingType == settingDatas[_newSettingId].settingType); // Store setting deprecation info SettingDeprecation storage _settingDeprecation = settingDeprecations[_settingId]; _settingDeprecation.settingId = _settingId; _settingDeprecation.creatorNameId = _creatorNameId; _settingDeprecation.creatorTAOId = _creatorTAOId; _settingDeprecation.associatedTAOId = _associatedTAOId; _settingDeprecation.pendingDeprecated = true; _settingDeprecation.locked = true; _settingDeprecation.pendingNewSettingId = _newSettingId; _settingDeprecation.pendingNewSettingContractAddress = _newSettingContractAddress; return true; } } /** * @title AOTokenInterface */ contract AOTokenInterface is TheAO, TokenERC20 { using SafeMath for uint256; // To differentiate denomination of AO uint256 public powerOfTen; /***** NETWORK TOKEN VARIABLES *****/ uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; mapping (address => uint256) public stakedBalance; mapping (address => uint256) public escrowedBalance; // This generates a public event on the blockchain that will notify clients event FrozenFunds(address target, bool frozen); event Stake(address indexed from, uint256 value); event Unstake(address indexed from, uint256 value); event Escrow(address indexed from, address indexed to, uint256 value); event Unescrow(address indexed from, uint256 value); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TokenERC20(initialSupply, tokenName, tokenSymbol) public { powerOfTen = 0; decimals = 0; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Prevent/Allow target from sending & receiving tokens * @param target Address to be frozen * @param freeze Either to freeze it or not */ function freezeAccount(address target, bool freeze) public onlyTheAO { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * @dev Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * @param newSellPrice Price users can sell to the contract * @param newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) public onlyTheAO { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /***** NETWORK TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive * @return true on success */ function mintToken(address target, uint256 mintedAmount) public inWhitelist returns (bool) { _mintToken(target, mintedAmount); return true; } /** * @dev Stake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */ function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; } /** * @dev Unstake `_value` tokens on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @return true on success */ function unstakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (stakedBalance[_from] >= _value); // Check if the targeted staked balance is enough stakedBalance[_from] = stakedBalance[_from].sub(_value); // Subtract from the targeted staked balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unstake(_from, _value); return true; } /** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens to put in escrow * @return true on success */ function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; } /** * @dev Create `mintedAmount` tokens and send it to `target` escrow balance * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive in escrow */ function mintTokenEscrow(address target, uint256 mintedAmount) public inWhitelist returns (bool) { escrowedBalance[target] = escrowedBalance[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Escrow(this, target, mintedAmount); return true; } /** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network tokens to be released * @return true on success */ function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; } /** * * @dev Whitelisted address remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } /** * @dev Whitelisted address transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function whitelistTransferFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool success) { _transfer(_from, _to, _value); return true; } /***** PUBLIC METHODS *****/ /** * @dev Buy tokens from contract by sending ether */ function buy() public payable { require (buyPrice > 0); uint256 amount = msg.value.div(buyPrice); _transfer(this, msg.sender, amount); } /** * @dev Sell `amount` tokens to contract * @param amount The amount of tokens to be sold */ function sell(uint256 amount) public { require (sellPrice > 0); address myAddress = this; require (myAddress.balance >= amount.mul(sellPrice)); _transfer(msg.sender, this, amount); msg.sender.transfer(amount.mul(sellPrice)); } /***** INTERNAL METHODS *****/ /** * @dev Send `_value` tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances); } /** * @dev Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount The amount of tokens it will receive */ function _mintToken(address target, uint256 mintedAmount) internal { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } } /** * @title AOToken */ contract AOToken is AOTokenInterface { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; // AO Dev Team addresses to receive Primordial/Network Tokens address public aoDevTeam1 = 0x5C63644D01Ba385eBAc5bcf2DDc1e6dBC1182b52; address public aoDevTeam2 = 0x156C79bf4347D1891da834Ea30662A14177CbF28; AOSetting internal _aoSetting; /***** PRIMORDIAL TOKEN VARIABLES *****/ uint256 public primordialTotalSupply; uint256 public primordialTotalBought; uint256 public primordialSellPrice; uint256 public primordialBuyPrice; // Total available primordial token for sale 1,125,899,906,842,620 AO+ uint256 constant public TOTAL_PRIMORDIAL_FOR_SALE = 1125899906842620; mapping (address => uint256) public primordialBalanceOf; mapping (address => mapping (address => uint256)) public primordialAllowance; // Mapping from owner's lot weighted multiplier to the amount of staked tokens mapping (address => mapping (uint256 => uint256)) public primordialStakedBalance; event PrimordialTransfer(address indexed from, address indexed to, uint256 value); event PrimordialApproval(address indexed _owner, address indexed _spender, uint256 _value); event PrimordialBurn(address indexed from, uint256 value); event PrimordialStake(address indexed from, uint256 value, uint256 weightedMultiplier); event PrimordialUnstake(address indexed from, uint256 value, uint256 weightedMultiplier); uint256 public totalLots; uint256 public totalBurnLots; uint256 public totalConvertLots; bool public networkExchangeEnded; /** * Stores Lot creation data (during network exchange) */ struct Lot { bytes32 lotId; uint256 multiplier; // This value is in 10^6, so 1000000 = 1 address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account burns primordial token */ struct BurnLot { bytes32 burnLotId; address lotOwner; uint256 tokenAmount; } /** * Struct to store info when account converts network token to primordial token */ struct ConvertLot { bytes32 convertLotId; address lotOwner; uint256 tokenAmount; } // Mapping from Lot ID to Lot object mapping (bytes32 => Lot) internal lots; // Mapping from Burn Lot ID to BurnLot object mapping (bytes32 => BurnLot) internal burnLots; // Mapping from Convert Lot ID to ConvertLot object mapping (bytes32 => ConvertLot) internal convertLots; // Mapping from owner to list of owned lot IDs mapping (address => bytes32[]) internal ownedLots; // Mapping from owner to list of owned burn lot IDs mapping (address => bytes32[]) internal ownedBurnLots; // Mapping from owner to list of owned convert lot IDs mapping (address => bytes32[]) internal ownedConvertLots; // Mapping from owner to his/her current weighted multiplier mapping (address => uint256) internal ownerWeightedMultiplier; // Mapping from owner to his/her max multiplier (multiplier of account's first Lot) mapping (address => uint256) internal ownerMaxMultiplier; // Event to be broadcasted to public when a lot is created // multiplier value is in 10^6 to account for 6 decimal points event LotCreation(address indexed lotOwner, bytes32 indexed lotId, uint256 multiplier, uint256 primordialTokenAmount, uint256 networkTokenBonusAmount); // Event to be broadcasted to public when burn lot is created (when account burns primordial tokens) event BurnLotCreation(address indexed lotOwner, bytes32 indexed burnLotId, uint256 burnTokenAmount, uint256 multiplierAfterBurn); // Event to be broadcasted to public when convert lot is created (when account convert network tokens to primordial tokens) event ConvertLotCreation(address indexed lotOwner, bytes32 indexed convertLotId, uint256 convertTokenAmount, uint256 multiplierAfterBurn); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _settingTAOId, address _aoSettingAddress) AOTokenInterface(initialSupply, tokenName, tokenSymbol) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; _aoSetting = AOSetting(_aoSettingAddress); powerOfTen = 0; decimals = 0; setPrimordialPrices(0, 10000); // Set Primordial buy price to 10000 Wei/token } /** * @dev Checks if buyer can buy primordial token */ modifier canBuyPrimordial(uint256 _sentAmount) { require (networkExchangeEnded == false && primordialTotalBought < TOTAL_PRIMORDIAL_FOR_SALE && primordialBuyPrice > 0 && _sentAmount > 0); _; } /***** The AO ONLY METHODS *****/ /** * @dev Set AO Dev team addresses to receive Primordial/Network tokens during network exchange * @param _aoDevTeam1 The first AO dev team address * @param _aoDevTeam2 The second AO dev team address */ function setAODevTeamAddresses(address _aoDevTeam1, address _aoDevTeam2) public onlyTheAO { aoDevTeam1 = _aoDevTeam1; aoDevTeam2 = _aoDevTeam2; } /***** PRIMORDIAL TOKEN The AO ONLY METHODS *****/ /** * @dev Allow users to buy Primordial tokens for `newBuyPrice` eth and sell Primordial tokens for `newSellPrice` eth * @param newPrimordialSellPrice Price users can sell to the contract * @param newPrimordialBuyPrice Price users can buy from the contract */ function setPrimordialPrices(uint256 newPrimordialSellPrice, uint256 newPrimordialBuyPrice) public onlyTheAO { primordialSellPrice = newPrimordialSellPrice; primordialBuyPrice = newPrimordialBuyPrice; } /***** PRIMORDIAL TOKEN WHITELISTED ADDRESS ONLY METHODS *****/ /** * @dev Stake `_value` Primordial tokens at `_weightedMultiplier ` multiplier on behalf of `_from` * @param _from The address of the target * @param _value The amount of Primordial tokens to stake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function stakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted balance is enough require (primordialBalanceOf[_from] >= _value); // Make sure the weighted multiplier is the same as account's current weighted multiplier require (_weightedMultiplier == ownerWeightedMultiplier[_from]); // Subtract from the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Add to the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].add(_value); emit PrimordialStake(_from, _value, _weightedMultiplier); return true; } /** * @dev Unstake `_value` Primordial tokens at `_weightedMultiplier` on behalf of `_from` * @param _from The address of the target * @param _value The amount to unstake * @param _weightedMultiplier The weighted multiplier of the Primordial tokens * @return true on success */ function unstakePrimordialTokenFrom(address _from, uint256 _value, uint256 _weightedMultiplier) public inWhitelist returns (bool) { // Check if the targeted staked balance is enough require (primordialStakedBalance[_from][_weightedMultiplier] >= _value); // Subtract from the targeted staked balance primordialStakedBalance[_from][_weightedMultiplier] = primordialStakedBalance[_from][_weightedMultiplier].sub(_value); // Add to the targeted balance primordialBalanceOf[_from] = primordialBalanceOf[_from].add(_value); emit PrimordialUnstake(_from, _value, _weightedMultiplier); return true; } /** * @dev Send `_value` primordial tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function whitelistTransferPrimordialTokenFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /***** PUBLIC METHODS *****/ /***** Primordial TOKEN PUBLIC METHODS *****/ /** * @dev Buy Primordial tokens from contract by sending ether */ function buyPrimordialToken() public payable canBuyPrimordial(msg.value) { (uint256 tokenAmount, uint256 remainderBudget, bool shouldEndNetworkExchange) = _calculateTokenAmountAndRemainderBudget(msg.value); require (tokenAmount > 0); // Ends network exchange if necessary if (shouldEndNetworkExchange) { networkExchangeEnded = true; } // Send the primordial token to buyer and reward AO devs _sendPrimordialTokenAndRewardDev(tokenAmount, msg.sender); // Send remainder budget back to buyer if exist if (remainderBudget > 0) { msg.sender.transfer(remainderBudget); } } /** * @dev Send `_value` Primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialToken(address _to, uint256 _value) public returns (bool success) { bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[msg.sender]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[msg.sender], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(msg.sender, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Send `_value` Primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount to send * @return true on success */ function transferPrimordialTokenFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_value <= primordialAllowance[_from][msg.sender]); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); bytes32 _createdLotId = _createWeightedMultiplierLot(_to, _value, ownerWeightedMultiplier[_from]); Lot memory _lot = lots[_createdLotId]; // Make sure the new lot is created successfully require (_lot.lotOwner == _to); // Update the weighted multiplier of the recipient ownerWeightedMultiplier[_to] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_to], primordialBalanceOf[_to], ownerWeightedMultiplier[_from], _value); // Transfer the Primordial tokens require (_transferPrimordialToken(_from, _to, _value)); emit LotCreation(_lot.lotOwner, _lot.lotId, _lot.multiplier, _lot.tokenAmount, 0); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount they can spend * @return true on success */ function approvePrimordialToken(address _spender, uint256 _value) public returns (bool success) { primordialAllowance[msg.sender][_spender] = _value; emit PrimordialApproval(msg.sender, _spender, _value); return true; } /** * @dev Allows `_spender` to spend no more than `_value` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approvePrimordialTokenAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approvePrimordialToken(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * @dev Remove `_value` Primordial tokens from the system irreversibly * and re-weight the account's multiplier after burn * @param _value The amount to burn * @return true on success */ function burnPrimordialToken(uint256 _value) public returns (bool success) { require (primordialBalanceOf[msg.sender] >= _value); require (calculateMaximumBurnAmount(msg.sender) >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterBurn(msg.sender, _value); primordialBalanceOf[msg.sender] = primordialBalanceOf[msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(msg.sender, _value); emit PrimordialBurn(msg.sender, _value); return true; } /** * @dev Remove `_value` Primordial tokens from the system irreversibly on behalf of `_from` * and re-weight `_from`'s multiplier after burn * @param _from The address of sender * @param _value The amount to burn * @return true on success */ function burnPrimordialTokenFrom(address _from, uint256 _value) public returns (bool success) { require (primordialBalanceOf[_from] >= _value); require (primordialAllowance[_from][msg.sender] >= _value); require (calculateMaximumBurnAmount(_from) >= _value); // Update `_from`'s multiplier ownerWeightedMultiplier[_from] = calculateMultiplierAfterBurn(_from, _value); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); primordialAllowance[_from][msg.sender] = primordialAllowance[_from][msg.sender].sub(_value); primordialTotalSupply = primordialTotalSupply.sub(_value); // Store burn lot info _createBurnLot(_from, _value); emit PrimordialBurn(_from, _value); return true; } /** * @dev Return all lot IDs owned by an address * @param _lotOwner The address of the lot owner * @return array of lot IDs */ function lotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedLots[_lotOwner]; } /** * @dev Return the total lots owned by an address * @param _lotOwner The address of the lot owner * @return total lots owner by the address */ function totalLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedLots[_lotOwner].length; } /** * @dev Return the lot information at a given index of the lots list of the requested owner * @param _lotOwner The address owning the lots list to be accessed * @param _index uint256 representing the index to be accessed of the requested lots list * @return id of the lot * @return The address of the lot owner * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotOfOwnerByIndex(address _lotOwner, uint256 _index) public view returns (bytes32, address, uint256, uint256) { require (_index < ownedLots[_lotOwner].length); Lot memory _lot = lots[ownedLots[_lotOwner][_index]]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return the lot information at a given ID * @param _lotId The lot ID in question * @return id of the lot * @return The lot owner address * @return multiplier of the lot in (10 ** 6) * @return Primordial token amount in the lot */ function lotById(bytes32 _lotId) public view returns (bytes32, address, uint256, uint256) { Lot memory _lot = lots[_lotId]; return (_lot.lotId, _lot.lotOwner, _lot.multiplier, _lot.tokenAmount); } /** * @dev Return all Burn Lot IDs owned by an address * @param _lotOwner The address of the burn lot owner * @return array of Burn Lot IDs */ function burnLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedBurnLots[_lotOwner]; } /** * @dev Return the total burn lots owned by an address * @param _lotOwner The address of the burn lot owner * @return total burn lots owner by the address */ function totalBurnLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedBurnLots[_lotOwner].length; } /** * @dev Return the burn lot information at a given ID * @param _burnLotId The burn lot ID in question * @return id of the lot * @return The address of the burn lot owner * @return Primordial token amount in the burn lot */ function burnLotById(bytes32 _burnLotId) public view returns (bytes32, address, uint256) { BurnLot memory _burnLot = burnLots[_burnLotId]; return (_burnLot.burnLotId, _burnLot.lotOwner, _burnLot.tokenAmount); } /** * @dev Return all Convert Lot IDs owned by an address * @param _lotOwner The address of the convert lot owner * @return array of Convert Lot IDs */ function convertLotIdsByAddress(address _lotOwner) public view returns (bytes32[]) { return ownedConvertLots[_lotOwner]; } /** * @dev Return the total convert lots owned by an address * @param _lotOwner The address of the convert lot owner * @return total convert lots owner by the address */ function totalConvertLotsByAddress(address _lotOwner) public view returns (uint256) { return ownedConvertLots[_lotOwner].length; } /** * @dev Return the convert lot information at a given ID * @param _convertLotId The convert lot ID in question * @return id of the lot * @return The address of the convert lot owner * @return Primordial token amount in the convert lot */ function convertLotById(bytes32 _convertLotId) public view returns (bytes32, address, uint256) { ConvertLot memory _convertLot = convertLots[_convertLotId]; return (_convertLot.convertLotId, _convertLot.lotOwner, _convertLot.tokenAmount); } /** * @dev Return the average weighted multiplier of all lots owned by an address * @param _lotOwner The address of the lot owner * @return the weighted multiplier of the address (in 10 ** 6) */ function weightedMultiplierByAddress(address _lotOwner) public view returns (uint256) { return ownerWeightedMultiplier[_lotOwner]; } /** * @dev Return the max multiplier of an address * @param _target The address to query * @return the max multiplier of the address (in 10 ** 6) */ function maxMultiplierByAddress(address _target) public view returns (uint256) { return (ownedLots[_target].length > 0) ? ownerMaxMultiplier[_target] : 0; } /** * @dev Calculate the primordial token multiplier, bonus network token percentage, and the * bonus network token amount on a given lot when someone purchases primordial token * during network exchange * @param _purchaseAmount The amount of primordial token intended to be purchased * @return The multiplier in (10 ** 6) * @return The bonus percentage * @return The amount of network token as bonus */ function calculateMultiplierAndBonus(uint256 _purchaseAmount) public view returns (uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier, uint256 endingPrimordialMultiplier, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); return ( AOLibrary.calculatePrimordialMultiplier(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingPrimordialMultiplier, endingPrimordialMultiplier), AOLibrary.calculateNetworkTokenBonusPercentage(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier), AOLibrary.calculateNetworkTokenBonusAmount(_purchaseAmount, TOTAL_PRIMORDIAL_FOR_SALE, primordialTotalBought, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier) ); } /** * @dev Calculate the maximum amount of Primordial an account can burn * @param _account The address of the account * @return The maximum primordial token amount to burn */ function calculateMaximumBurnAmount(address _account) public view returns (uint256) { return AOLibrary.calculateMaximumBurnAmount(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], ownerMaxMultiplier[_account]); } /** * @dev Calculate account's new multiplier after burn `_amountToBurn` primordial tokens * @param _account The address of the account * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterBurn(address _account, uint256 _amountToBurn) public view returns (uint256) { require (calculateMaximumBurnAmount(_account) >= _amountToBurn); return AOLibrary.calculateMultiplierAfterBurn(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToBurn); } /** * @dev Calculate account's new multiplier after converting `amountToConvert` network token to primordial token * @param _account The address of the account * @param _amountToConvert The amount of network token to convert * @return The new multiplier in (10 ** 6) */ function calculateMultiplierAfterConversion(address _account, uint256 _amountToConvert) public view returns (uint256) { return AOLibrary.calculateMultiplierAfterConversion(primordialBalanceOf[_account], ownerWeightedMultiplier[_account], _amountToConvert); } /** * @dev Convert `_value` of network tokens to primordial tokens * and re-weight the account's multiplier after conversion * @param _value The amount to convert * @return true on success */ function convertToPrimordial(uint256 _value) public returns (bool success) { require (balanceOf[msg.sender] >= _value); // Update the account's multiplier ownerWeightedMultiplier[msg.sender] = calculateMultiplierAfterConversion(msg.sender, _value); // Burn network token burn(_value); // mint primordial token _mintPrimordialToken(msg.sender, _value); // Store convert lot info totalConvertLots++; // Generate convert lot Id bytes32 convertLotId = keccak256(abi.encodePacked(this, msg.sender, totalConvertLots)); // Make sure no one owns this lot yet require (convertLots[convertLotId].lotOwner == address(0)); ConvertLot storage convertLot = convertLots[convertLotId]; convertLot.convertLotId = convertLotId; convertLot.lotOwner = msg.sender; convertLot.tokenAmount = _value; ownedConvertLots[msg.sender].push(convertLotId); emit ConvertLotCreation(convertLot.lotOwner, convertLot.convertLotId, convertLot.tokenAmount, ownerWeightedMultiplier[convertLot.lotOwner]); return true; } /***** NETWORK TOKEN & PRIMORDIAL TOKEN METHODS *****/ /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from your account * @param _to The address of the recipient * @param _value The amount of network tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokens(address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transfer(_to, _value)); require (transferPrimordialToken(_to, _primordialValue)); return true; } /** * @dev Send `_value` network tokens and `_primordialValue` primordial tokens to `_to` from `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network tokens tokens to send * @param _primordialValue The amount of Primordial tokens to send * @return true on success */ function transferTokensFrom(address _from, address _to, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.transferFrom(_from, _to, _value)); require (transferPrimordialTokenFrom(_from, _to, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of network tokens they can spend * @return true on success */ function approveTokens(address _spender, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.approve(_spender, _value)); require (approvePrimordialToken(_spender, _primordialValue)); return true; } /** * @dev Allows `_spender` to spend no more than `_value` network tokens and `_primordialValue` Primordial tokens in your behalf, and then ping the contract about it * @param _spender The address authorized to spend * @param _value The max amount of network tokens they can spend * @param _primordialValue The max amount of Primordial Tokens they can spend * @param _extraData some extra information to send to the approved contract * @return true on success */ function approveTokensAndCall(address _spender, uint256 _value, uint256 _primordialValue, bytes _extraData) public returns (bool success) { require (super.approveAndCall(_spender, _value, _extraData)); require (approvePrimordialTokenAndCall(_spender, _primordialValue, _extraData)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokens(uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burn(_value)); require (burnPrimordialToken(_primordialValue)); return true; } /** * @dev Remove `_value` network tokens and `_primordialValue` Primordial tokens from the system irreversibly on behalf of `_from` * @param _from The address of sender * @param _value The amount of network tokens to burn * @param _primordialValue The amount of Primordial tokens to burn * @return true on success */ function burnTokensFrom(address _from, uint256 _value, uint256 _primordialValue) public returns (bool success) { require (super.burnFrom(_from, _value)); require (burnPrimordialTokenFrom(_from, _primordialValue)); return true; } /***** INTERNAL METHODS *****/ /***** PRIMORDIAL TOKEN INTERNAL METHODS *****/ /** * @dev Calculate the amount of token the buyer will receive and remaining budget if exist * when he/she buys primordial token * @param _budget The amount of ETH sent by buyer * @return uint256 of the tokenAmount the buyer will receiver * @return uint256 of the remaining budget, if exist * @return bool whether or not the network exchange should end */ function _calculateTokenAmountAndRemainderBudget(uint256 _budget) internal view returns (uint256, uint256, bool) { // Calculate the amount of tokens uint256 tokenAmount = _budget.div(primordialBuyPrice); // If we need to return ETH to the buyer, in the case // where the buyer sends more ETH than available primordial token to be purchased uint256 remainderEth = 0; // Make sure primordialTotalBought is not overflowing bool shouldEndNetworkExchange = false; if (primordialTotalBought.add(tokenAmount) >= TOTAL_PRIMORDIAL_FOR_SALE) { tokenAmount = TOTAL_PRIMORDIAL_FOR_SALE.sub(primordialTotalBought); shouldEndNetworkExchange = true; remainderEth = msg.value.sub(tokenAmount.mul(primordialBuyPrice)); } return (tokenAmount, remainderEth, shouldEndNetworkExchange); } /** * @dev Actually sending the primordial token to buyer and reward AO devs accordingly * @param tokenAmount The amount of primordial token to be sent to buyer * @param to The recipient of the token */ function _sendPrimordialTokenAndRewardDev(uint256 tokenAmount, address to) internal { (uint256 startingPrimordialMultiplier,, uint256 startingNetworkTokenBonusMultiplier, uint256 endingNetworkTokenBonusMultiplier) = _getSettingVariables(); // Update primordialTotalBought (uint256 multiplier, uint256 networkTokenBonusPercentage, uint256 networkTokenBonusAmount) = calculateMultiplierAndBonus(tokenAmount); primordialTotalBought = primordialTotalBought.add(tokenAmount); _createPrimordialLot(to, tokenAmount, multiplier, networkTokenBonusAmount); // Calculate The AO and AO Dev Team's portion of Primordial and Network Token Bonus uint256 inverseMultiplier = startingPrimordialMultiplier.sub(multiplier); // Inverse of the buyer's multiplier uint256 theAONetworkTokenBonusAmount = (startingNetworkTokenBonusMultiplier.sub(networkTokenBonusPercentage).add(endingNetworkTokenBonusMultiplier)).mul(tokenAmount).div(AOLibrary.PERCENTAGE_DIVISOR()); if (aoDevTeam1 != address(0)) { _createPrimordialLot(aoDevTeam1, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } if (aoDevTeam2 != address(0)) { _createPrimordialLot(aoDevTeam2, tokenAmount.div(2), inverseMultiplier, theAONetworkTokenBonusAmount.div(2)); } _mintToken(theAO, theAONetworkTokenBonusAmount); } /** * @dev Create a lot with `primordialTokenAmount` of primordial tokens with `_multiplier` for an `account` * during network exchange, and reward `_networkTokenBonusAmount` if exist * @param _account Address of the lot owner * @param _primordialTokenAmount The amount of primordial tokens to be stored in the lot * @param _multiplier The multiplier for this lot in (10 ** 6) * @param _networkTokenBonusAmount The network token bonus amount */ function _createPrimordialLot(address _account, uint256 _primordialTokenAmount, uint256 _multiplier, uint256 _networkTokenBonusAmount) internal { totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _multiplier; lot.lotOwner = _account; lot.tokenAmount = _primordialTokenAmount; ownedLots[_account].push(lotId); ownerWeightedMultiplier[_account] = AOLibrary.calculateWeightedMultiplier(ownerWeightedMultiplier[_account], primordialBalanceOf[_account], lot.multiplier, lot.tokenAmount); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } _mintPrimordialToken(_account, lot.tokenAmount); _mintToken(_account, _networkTokenBonusAmount); emit LotCreation(lot.lotOwner, lot.lotId, lot.multiplier, lot.tokenAmount, _networkTokenBonusAmount); } /** * @dev Create `mintedAmount` Primordial tokens and send it to `target` * @param target Address to receive the Primordial tokens * @param mintedAmount The amount of Primordial tokens it will receive */ function _mintPrimordialToken(address target, uint256 mintedAmount) internal { primordialBalanceOf[target] = primordialBalanceOf[target].add(mintedAmount); primordialTotalSupply = primordialTotalSupply.add(mintedAmount); emit PrimordialTransfer(0, this, mintedAmount); emit PrimordialTransfer(this, target, mintedAmount); } /** * @dev Create a lot with `tokenAmount` of tokens at `weightedMultiplier` for an `account` * @param _account Address of lot owner * @param _tokenAmount The amount of tokens * @param _weightedMultiplier The multiplier of the lot (in 10^6) * @return bytes32 of new created lot ID */ function _createWeightedMultiplierLot(address _account, uint256 _tokenAmount, uint256 _weightedMultiplier) internal returns (bytes32) { require (_account != address(0)); require (_tokenAmount > 0); totalLots++; // Generate lotId bytes32 lotId = keccak256(abi.encodePacked(this, _account, totalLots)); // Make sure no one owns this lot yet require (lots[lotId].lotOwner == address(0)); Lot storage lot = lots[lotId]; lot.lotId = lotId; lot.multiplier = _weightedMultiplier; lot.lotOwner = _account; lot.tokenAmount = _tokenAmount; ownedLots[_account].push(lotId); // If this is the first lot, set this as the max multiplier of the account if (ownedLots[_account].length == 1) { ownerMaxMultiplier[_account] = lot.multiplier; } return lotId; } /** * @dev Send `_value` Primordial tokens from `_from` to `_to` * @param _from The address of sender * @param _to The address of the recipient * @param _value The amount to send */ function _transferPrimordialToken(address _from, address _to, uint256 _value) internal returns (bool) { require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require (primordialBalanceOf[_from] >= _value); // Check if the sender has enough require (primordialBalanceOf[_to].add(_value) >= primordialBalanceOf[_to]); // Check for overflows require (!frozenAccount[_from]); // Check if sender is frozen require (!frozenAccount[_to]); // Check if recipient is frozen uint256 previousBalances = primordialBalanceOf[_from].add(primordialBalanceOf[_to]); primordialBalanceOf[_from] = primordialBalanceOf[_from].sub(_value); // Subtract from the sender primordialBalanceOf[_to] = primordialBalanceOf[_to].add(_value); // Add the same to the recipient emit PrimordialTransfer(_from, _to, _value); assert(primordialBalanceOf[_from].add(primordialBalanceOf[_to]) == previousBalances); return true; } /** * @dev Store burn lot information * @param _account The address of the account * @param _tokenAmount The amount of primordial tokens to burn */ function _createBurnLot(address _account, uint256 _tokenAmount) internal { totalBurnLots++; // Generate burn lot Id bytes32 burnLotId = keccak256(abi.encodePacked(this, _account, totalBurnLots)); // Make sure no one owns this lot yet require (burnLots[burnLotId].lotOwner == address(0)); BurnLot storage burnLot = burnLots[burnLotId]; burnLot.burnLotId = burnLotId; burnLot.lotOwner = _account; burnLot.tokenAmount = _tokenAmount; ownedBurnLots[_account].push(burnLotId); emit BurnLotCreation(burnLot.lotOwner, burnLot.burnLotId, burnLot.tokenAmount, ownerWeightedMultiplier[burnLot.lotOwner]); } /** * @dev Get setting variables * @return startingPrimordialMultiplier The starting multiplier used to calculate primordial token * @return endingPrimordialMultiplier The ending multiplier used to calculate primordial token * @return startingNetworkTokenBonusMultiplier The starting multiplier used to calculate network token bonus * @return endingNetworkTokenBonusMultiplier The ending multiplier used to calculate network token bonus */ function _getSettingVariables() internal view returns (uint256, uint256, uint256, uint256) { (uint256 startingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingPrimordialMultiplier'); (uint256 endingPrimordialMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingPrimordialMultiplier'); (uint256 startingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'startingNetworkTokenBonusMultiplier'); (uint256 endingNetworkTokenBonusMultiplier,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'endingNetworkTokenBonusMultiplier'); return (startingPrimordialMultiplier, endingPrimordialMultiplier, startingNetworkTokenBonusMultiplier, endingNetworkTokenBonusMultiplier); } } /** * @title AOTreasury * * The purpose of this contract is to list all of the valid denominations of AO Token and do the conversion between denominations */ contract AOTreasury is TheAO { using SafeMath for uint256; bool public paused; bool public killed; struct Denomination { bytes8 name; address denominationAddress; } // Mapping from denomination index to Denomination object // The list is in order from lowest denomination to highest denomination // i.e, denominations[1] is the base denomination mapping (uint256 => Denomination) internal denominations; // Mapping from denomination ID to index of denominations mapping (bytes8 => uint256) internal denominationIndex; uint256 public totalDenominations; // Event to be broadcasted to public when a token exchange happens event Exchange(address indexed account, uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function */ constructor() public {} /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /** * @dev Checks if denomination is valid */ modifier isValidDenomination(bytes8 denominationName) { require (denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO adds denomination and the contract address associated with it * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationAddress != address(0)); require (denominationIndex[denominationName] == 0); totalDenominations++; // Make sure the new denomination is higher than the previous if (totalDenominations > 1) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations - 1].denominationAddress); AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); require (_newDenominationToken.powerOfTen() > _lastDenominationToken.powerOfTen()); } denominations[totalDenominations].name = denominationName; denominations[totalDenominations].denominationAddress = denominationAddress; denominationIndex[denominationName] = totalDenominations; return true; } /** * @dev The AO updates denomination address or activates/deactivates the denomination * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc. * @param denominationAddress The address of the denomination token * @return true on success */ function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominationAddress != address(0)); uint256 _denominationNameIndex = denominationIndex[denominationName]; AOTokenInterface _newDenominationToken = AOTokenInterface(denominationAddress); if (_denominationNameIndex > 1) { AOTokenInterface _prevDenominationToken = AOTokenInterface(denominations[_denominationNameIndex - 1].denominationAddress); require (_newDenominationToken.powerOfTen() > _prevDenominationToken.powerOfTen()); } if (_denominationNameIndex < totalDenominations) { AOTokenInterface _lastDenominationToken = AOTokenInterface(denominations[totalDenominations].denominationAddress); require (_newDenominationToken.powerOfTen() < _lastDenominationToken.powerOfTen()); } denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress; return true; } /***** PUBLIC METHODS *****/ /** * @dev Get denomination info based on name * @param denominationName The name to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByName(bytes8 denominationName) public view returns (bytes8, address, string, string, uint8, uint256) { require (denominationName.length != 0); require (denominationIndex[denominationName] > 0); require (denominations[denominationIndex[denominationName]].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[denominationIndex[denominationName]].denominationAddress); return ( denominations[denominationIndex[denominationName]].name, denominations[denominationIndex[denominationName]].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get denomination info by index * @param index The index to be queried * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string, string, uint8, uint256) { require (index > 0 && index <= totalDenominations); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /** * @dev Get base denomination info * @return the denomination short name * @return the denomination address * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function getBaseDenomination() public view returns (bytes8, address, string, string, uint8, uint256) { require (totalDenominations > 1); return getDenominationByIndex(1); } /** * @dev convert token from `denominationName` denomination to base denomination, * in this case it's similar to web3.toWei() functionality * * Example: * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount * * @param integerAmount uint256 of the integer amount to be converted * @param fractionAmount uint256 of the frational amount to be converted * @param denominationName bytes8 name of the token denomination * @return uint256 converted amount in base denomination from target denomination */ function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) public view returns (uint256) { if (denominationName.length > 0 && denominationIndex[denominationName] > 0 && denominations[denominationIndex[denominationName]].denominationAddress != address(0) && (integerAmount > 0 || fractionAmount > 0)) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint8 fractionNumDigits = _numDigits(fractionAmount); require (fractionNumDigits <= _denominationToken.decimals()); uint256 baseInteger = integerAmount.mul(10 ** _denominationToken.powerOfTen()); if (_denominationToken.decimals() == 0) { fractionAmount = 0; } return baseInteger.add(fractionAmount); } else { return 0; } } /** * @dev convert token from base denomination to `denominationName` denomination, * in this case it's similar to web3.fromWei() functionality * @param integerAmount uint256 of the base amount to be converted * @param denominationName bytes8 name of the target token denomination * @return uint256 of the converted integer amount in target denomination * @return uint256 of the converted fraction amount in target denomination */ function fromBase(uint256 integerAmount, bytes8 denominationName) public isValidDenomination(denominationName) view returns (uint256, uint256) { Denomination memory _denomination = denominations[denominationIndex[denominationName]]; AOTokenInterface _denominationToken = AOTokenInterface(_denomination.denominationAddress); uint256 denominationInteger = integerAmount.div(10 ** _denominationToken.powerOfTen()); uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationToken.powerOfTen())); return (denominationInteger, denominationFraction); } /** * @dev exchange `amount` token from `fromDenominationName` denomination to token in `toDenominationName` denomination * @param amount The amount of token to exchange * @param fromDenominationName The origin denomination * @param toDenominationName The target denomination */ function exchange(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isContractActive isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) { require (amount > 0); Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]]; Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]]; AOTokenInterface _fromDenominationToken = AOTokenInterface(_fromDenomination.denominationAddress); AOTokenInterface _toDenominationToken = AOTokenInterface(_toDenomination.denominationAddress); require (_fromDenominationToken.whitelistBurnFrom(msg.sender, amount)); require (_toDenominationToken.mintToken(msg.sender, amount)); emit Exchange(msg.sender, amount, fromDenominationName, toDenominationName); } /** * @dev Return the highest possible denomination given a base amount * @param amount The amount to be converted * @return the denomination short name * @return the denomination address * @return the integer amount at the denomination level * @return the fraction amount at the denomination level * @return the denomination public name * @return the denomination symbol * @return the denomination num of decimals * @return the denomination multiplier (power of ten) */ function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string, string, uint8, uint256) { uint256 integerAmount; uint256 fractionAmount; uint256 index; for (uint256 i=totalDenominations; i>0; i--) { Denomination memory _denomination = denominations[i]; (integerAmount, fractionAmount) = fromBase(amount, _denomination.name); if (integerAmount > 0) { index = i; break; } } require (index > 0 && index <= totalDenominations); require (integerAmount > 0 || fractionAmount > 0); require (denominations[index].denominationAddress != address(0)); AOTokenInterface _ao = AOTokenInterface(denominations[index].denominationAddress); return ( denominations[index].name, denominations[index].denominationAddress, integerAmount, fractionAmount, _ao.name(), _ao.symbol(), _ao.decimals(), _ao.powerOfTen() ); } /***** INTERNAL METHOD *****/ /** * @dev count num of digits * @param number uint256 of the nuumber to be checked * @return uint8 num of digits */ function _numDigits(uint256 number) internal pure returns (uint8) { uint8 digits = 0; while(number != 0) { number = number.div(10); digits++; } return digits; } } contract Pathos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } contract Ethos is TAOCurrency { /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol) TAOCurrency(initialSupply, tokenName, tokenSymbol) public {} } /** * @title TAOController */ contract TAOController { NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public { _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of TAO ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } } // Store the name lookup for a Name/TAO /** * @title TAOFamily */ contract TAOFamily is TAOController { using SafeMath for uint256; address public taoFactoryAddress; TAOFactory internal _taoFactory; struct Child { address taoId; bool approved; // If false, then waiting for parent TAO approval bool connected; // If false, then parent TAO want to remove this child TAO } struct Family { address taoId; address parentId; // The parent of this TAO ID (could be a Name or TAO) uint256 childMinLogos; mapping (uint256 => Child) children; mapping (address => uint256) childInternalIdLookup; uint256 totalChildren; uint256 childInternalId; } mapping (address => Family) internal families; // Event to be broadcasted to public when Advocate updates min required Logos to create a child TAO event UpdateChildMinLogos(address indexed taoId, uint256 childMinLogos, uint256 nonce); // Event to be broadcasted to public when a TAO adds a child TAO event AddChild(address indexed taoId, address childId, bool approved, bool connected, uint256 nonce); // Event to be broadcasted to public when a TAO approves a child TAO event ApproveChild(address indexed taoId, address childId, uint256 nonce); // Event to be broadcasted to public when a TAO removes a child TAO event RemoveChild(address indexed taoId, address childId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _taoFactoryAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == taoFactoryAddress); _; } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a TAO ID exist in the list of families * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return families[_id].taoId != address(0); } /** * @dev Store the Family info for a TAO * @param _id The ID of the TAO * @param _parentId The parent ID of this TAO * @param _childMinLogos The min required Logos to create a TAO * @return true on success */ function add(address _id, address _parentId, uint256 _childMinLogos) public isTAO(_id) isNameOrTAO(_parentId) onlyFactory returns (bool) { require (!isExist(_id)); Family storage _family = families[_id]; _family.taoId = _id; _family.parentId = _parentId; _family.childMinLogos = _childMinLogos; return true; } /** * @dev Get Family info given a TAO ID * @param _id The ID of the TAO * @return the parent ID of this TAO (could be a Name/TAO) * @return the min required Logos to create a child TAO * @return the total child TAOs count */ function getFamilyById(address _id) public view returns (address, uint256, uint256) { require (isExist(_id)); Family memory _family = families[_id]; return ( _family.parentId, _family.childMinLogos, _family.totalChildren ); } /** * @dev Set min required Logos to create a child from this TAO * @param _childMinLogos The min Logos to set * @return the nonce for this transaction */ function updateChildMinLogos(address _id, uint256 _childMinLogos) public isTAO(_id) senderIsName() onlyAdvocate(_id) { require (isExist(_id)); Family storage _family = families[_id]; _family.childMinLogos = _childMinLogos; uint256 _nonce = _taoFactory.incrementNonce(_id); require (_nonce > 0); emit UpdateChildMinLogos(_id, _family.childMinLogos, _nonce); } /** * @dev Check if `_childId` is a child TAO of `_taoId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to check * @return true if yes. Otherwise return false. */ function isChild(address _taoId, address _childId) public view returns (bool) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family memory _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; return ( _childInternalId > 0 && _family.children[_childInternalId].approved && _family.children[_childInternalId].connected && _childFamily.parentId == _taoId ); } /** * @dev Add child TAO * @param _taoId The TAO ID to be added to * @param _childId The ID to be added to as child TAO */ function addChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) onlyFactory returns (bool) { require (!isChild(_taoId, _childId)); Family storage _family = families[_taoId]; require (_family.childInternalIdLookup[_childId] == 0); _family.childInternalId++; _family.childInternalIdLookup[_childId] = _family.childInternalId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); Child storage _child = _family.children[_family.childInternalId]; _child.taoId = _childId; // If _taoId's Advocate == _childId's Advocate, then the child is automatically approved and connected // Otherwise, child TAO needs parent TAO approval address _taoAdvocate = _nameTAOPosition.getAdvocate(_taoId); address _childAdvocate = _nameTAOPosition.getAdvocate(_childId); if (_taoAdvocate == _childAdvocate) { _family.totalChildren++; _child.approved = true; _child.connected = true; Family storage _childFamily = families[_childId]; _childFamily.parentId = _taoId; } emit AddChild(_taoId, _childId, _child.approved, _child.connected, _nonce); return true; } /** * @dev Advocate of `_taoId` approves child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be approved */ function approveChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isExist(_taoId) && isExist(_childId)); Family storage _family = families[_taoId]; Family storage _childFamily = families[_childId]; uint256 _childInternalId = _family.childInternalIdLookup[_childId]; require (_childInternalId > 0 && !_family.children[_childInternalId].approved && !_family.children[_childInternalId].connected ); _family.totalChildren++; Child storage _child = _family.children[_childInternalId]; _child.approved = true; _child.connected = true; _childFamily.parentId = _taoId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit ApproveChild(_taoId, _childId, _nonce); } /** * @dev Advocate of `_taoId` removes child `_childId` * @param _taoId The TAO ID to be checked * @param _childId The child TAO ID to be removed */ function removeChild(address _taoId, address _childId) public isTAO(_taoId) isTAO(_childId) senderIsName() onlyAdvocate(_taoId) { require (isChild(_taoId, _childId)); Family storage _family = families[_taoId]; _family.totalChildren--; Child storage _child = _family.children[_family.childInternalIdLookup[_childId]]; _child.connected = false; _family.childInternalIdLookup[_childId] = 0; Family storage _childFamily = families[_childId]; _childFamily.parentId = address(0); uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit RemoveChild(_taoId, _childId, _nonce); } /** * @dev Get list of child TAO IDs * @param _taoId The TAO ID to be checked * @param _from The starting index (start from 1) * @param _to The ending index, (max is childInternalId) * @return list of child TAO IDs */ function getChildIds(address _taoId, uint256 _from, uint256 _to) public view returns (address[]) { require (isExist(_taoId)); Family storage _family = families[_taoId]; require (_from >= 1 && _to >= _from && _family.childInternalId >= _to); address[] memory _childIds = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _childIds[i.sub(_from)] = _family.children[i].approved && _family.children[i].connected ? _family.children[i].taoId : address(0); } return _childIds; } } // Store TAO's child information /** * @title TAOFactory * * The purpose of this contract is to allow node to create TAO */ contract TAOFactory is TheAO, TAOController { using SafeMath for uint256; address[] internal taos; address public taoFamilyAddress; address public nameTAOVaultAddress; address public settingTAOId; NameTAOLookup internal _nameTAOLookup; TAOFamily internal _taoFamily; AOSetting internal _aoSetting; Logos internal _logos; // Mapping from TAO ID to its nonce mapping (address => uint256) public nonces; // Event to be broadcasted to public when Advocate creates a TAO event CreateTAO(address indexed ethAddress, address advocateId, address taoId, uint256 index, address parent, uint8 parentTypeId); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOLookupAddress, address _nameTAOPositionAddress, address _aoSettingAddress, address _logosAddress, address _nameTAOVaultAddress) TAOController(_nameFactoryAddress, _nameTAOPositionAddress) public { nameTAOPositionAddress = _nameTAOPositionAddress; nameTAOVaultAddress = _nameTAOVaultAddress; _nameTAOLookup = NameTAOLookup(_nameTAOLookupAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSetting = AOSetting(_aoSettingAddress); _logos = Logos(_logosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if calling address can update TAO's nonce */ modifier canUpdateNonce { require (msg.sender == nameTAOPositionAddress || msg.sender == taoFamilyAddress); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the TAOFamily Address * @param _taoFamilyAddress The address of TAOFamily */ function setTAOFamilyAddress(address _taoFamilyAddress) public onlyTheAO { require (_taoFamilyAddress != address(0)); taoFamilyAddress = _taoFamilyAddress; _taoFamily = TAOFamily(taoFamilyAddress); } /** * @dev The AO set settingTAOId (The TAO ID that holds the setting values) * @param _settingTAOId The address of settingTAOId */ function setSettingTAOId(address _settingTAOId) public onlyTheAO isTAO(_settingTAOId) { settingTAOId = _settingTAOId; } /***** PUBLIC METHODS *****/ /** * @dev Increment the nonce of a TAO * @param _taoId The ID of the TAO * @return current nonce */ function incrementNonce(address _taoId) public canUpdateNonce returns (uint256) { // Check if _taoId exist require (nonces[_taoId] > 0); nonces[_taoId]++; return nonces[_taoId]; } /** * @dev Name creates a TAO * @param _name The name of the TAO * @param _datHash The datHash of this TAO * @param _database The database for this TAO * @param _keyValue The key/value pair to be checked on the database * @param _contentId The contentId related to this TAO * @param _parentId The parent of this TAO (has to be a Name or TAO) * @param _childMinLogos The min required Logos to create a child from this TAO */ function createTAO( string _name, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _parentId, uint256 _childMinLogos ) public senderIsName() isNameOrTAO(_parentId) { require (bytes(_name).length > 0); require (!_nameTAOLookup.isExist(_name)); address _nameId = _nameFactory.ethAddressToNameId(msg.sender); uint256 _parentCreateChildTAOMinLogos; uint256 _createChildTAOMinLogos = _getSettingVariables(); if (AOLibrary.isTAO(_parentId)) { (, _parentCreateChildTAOMinLogos,) = _taoFamily.getFamilyById(_parentId); } if (_parentCreateChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _parentCreateChildTAOMinLogos); } else if (_createChildTAOMinLogos > 0) { require (_logos.sumBalanceOf(_nameId) >= _createChildTAOMinLogos); } // Create the TAO address taoId = new TAO(_name, _nameId, _datHash, _database, _keyValue, _contentId, nameTAOVaultAddress); // Increment the nonce nonces[taoId]++; // Store the name lookup information require (_nameTAOLookup.add(_name, taoId, TAO(_parentId).name(), 0)); // Store the Advocate/Listener/Speaker information require (_nameTAOPosition.add(taoId, _nameId, _nameId, _nameId)); require (_taoFamily.add(taoId, _parentId, _childMinLogos)); taos.push(taoId); emit CreateTAO(msg.sender, _nameId, taoId, taos.length.sub(1), _parentId, TAO(_parentId).typeId()); if (AOLibrary.isTAO(_parentId)) { require (_taoFamily.addChild(_parentId, taoId)); } } /** * @dev Get TAO information * @param _taoId The ID of the TAO to be queried * @return The name of the TAO * @return The origin Name ID that created the TAO * @return The name of Name that created the TAO * @return The datHash of the TAO * @return The database of the TAO * @return The keyValue of the TAO * @return The contentId of the TAO * @return The typeId of the TAO */ function getTAO(address _taoId) public view returns (string, address, string, string, string, string, bytes32, uint8) { TAO _tao = TAO(_taoId); return ( _tao.name(), _tao.originId(), Name(_tao.originId()).name(), _tao.datHash(), _tao.database(), _tao.keyValue(), _tao.contentId(), _tao.typeId() ); } /** * @dev Get total TAOs count * @return total TAOs count */ function getTotalTAOsCount() public view returns (uint256) { return taos.length; } /** * @dev Get list of TAO IDs * @param _from The starting index * @param _to The ending index * @return list of TAO IDs */ function getTAOIds(uint256 _from, uint256 _to) public view returns (address[]) { require (_from >= 0 && _to >= _from && taos.length > _to); address[] memory _taos = new address[](_to.sub(_from).add(1)); for (uint256 i = _from; i <= _to; i++) { _taos[i.sub(_from)] = taos[i]; } return _taos; } /** * @dev Check whether or not the signature is valid * @param _data The signed string data * @param _nonce The signed uint256 nonce (should be TAO's current nonce + 1) * @param _validateAddress The ETH address to be validated (optional) * @param _name The Name of the TAO * @param _signatureV The V part of the signature * @param _signatureR The R part of the signature * @param _signatureS The S part of the signature * @return true if valid. false otherwise * @return The name of the Name that created the signature * @return The Position of the Name that created the signature. * 0 == unknown. 1 == Advocate. 2 == Listener. 3 == Speaker */ function validateTAOSignature( string _data, uint256 _nonce, address _validateAddress, string _name, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS ) public isTAO(_getTAOIdByName(_name)) view returns (bool, string, uint256) { address _signatureAddress = AOLibrary.getValidateSignatureAddress(address(this), _data, _nonce, _signatureV, _signatureR, _signatureS); if (_isTAOSignatureAddressValid(_validateAddress, _signatureAddress, _getTAOIdByName(_name), _nonce)) { return (true, Name(_nameFactory.ethAddressToNameId(_signatureAddress)).name(), _nameTAOPosition.determinePosition(_signatureAddress, _getTAOIdByName(_name))); } else { return (false, "", 0); } } /***** INTERNAL METHOD *****/ /** * @dev Check whether or not the address recovered from the signature is valid * @param _validateAddress The ETH address to be validated (optional) * @param _signatureAddress The address recovered from the signature * @param _taoId The ID of the TAO * @param _nonce The signed uint256 nonce * @return true if valid. false otherwise */ function _isTAOSignatureAddressValid( address _validateAddress, address _signatureAddress, address _taoId, uint256 _nonce ) internal view returns (bool) { if (_validateAddress != address(0)) { return (_nonce == nonces[_taoId].add(1) && _signatureAddress == _validateAddress && _nameTAOPosition.senderIsPosition(_validateAddress, _taoId) ); } else { return ( _nonce == nonces[_taoId].add(1) && _nameTAOPosition.senderIsPosition(_signatureAddress, _taoId) ); } } /** * @dev Internal function to get the TAO Id by name * @param _name The name of the TAO * @return the TAO ID */ function _getTAOIdByName(string _name) internal view returns (address) { return _nameTAOLookup.getAddressByName(_name); } /** * @dev Get setting variables * @return createChildTAOMinLogos The minimum required Logos to create a TAO */ function _getSettingVariables() internal view returns (uint256) { (uint256 createChildTAOMinLogos,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'createChildTAOMinLogos'); return createChildTAOMinLogos; } } /** * @title NameTAOPosition */ contract NameTAOPosition is TheAO { address public nameFactoryAddress; address public taoFactoryAddress; NameFactory internal _nameFactory; TAOFactory internal _taoFactory; struct Position { address advocateId; address listenerId; address speakerId; bool created; } mapping (address => Position) internal positions; // Event to be broadcasted to public when current Advocate of TAO sets New Advocate event SetAdvocate(address indexed taoId, address oldAdvocateId, address newAdvocateId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Listener event SetListener(address indexed taoId, address oldListenerId, address newListenerId, uint256 nonce); // Event to be broadcasted to public when current Advocate of Name/TAO sets New Speaker event SetSpeaker(address indexed taoId, address oldSpeakerId, address newSpeakerId, uint256 nonce); /** * @dev Constructor function */ constructor(address _nameFactoryAddress) public { nameFactoryAddress = _nameFactoryAddress; _nameFactory = NameFactory(_nameFactoryAddress); nameTAOPositionAddress = address(this); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Check if calling address is Factory */ modifier onlyFactory { require (msg.sender == nameFactoryAddress || msg.sender == taoFactoryAddress); _; } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if `_id` is a Name or a TAO */ modifier isNameOrTAO(address _id) { require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id)); _; } /** * @dev Check is msg.sender address is a Name */ modifier senderIsName() { require (_nameFactory.ethAddressToNameId(msg.sender) != address(0)); _; } /** * @dev Check if msg.sender is the current advocate of a Name/TAO ID */ modifier onlyAdvocate(address _id) { require (senderIsAdvocate(msg.sender, _id)); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO set the taoFactoryAddress Address * @param _taoFactoryAddress The address of TAOFactory */ function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO { require (_taoFactoryAddress != address(0)); taoFactoryAddress = _taoFactoryAddress; _taoFactory = TAOFactory(_taoFactoryAddress); } /***** PUBLIC METHODS *****/ /** * @dev Check whether or not a Name/TAO ID exist in the list * @param _id The ID to be checked * @return true if yes, false otherwise */ function isExist(address _id) public view returns (bool) { return positions[_id].created; } /** * @dev Check whether or not eth address is advocate of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsAdvocate(address _sender, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameFactory.ethAddressToNameId(_sender)); } /** * @dev Check whether or not eth address is either Advocate/Listener/Speaker of _id * @param _sender The eth address to check * @param _id The ID to be checked * @return true if yes, false otherwise */ function senderIsPosition(address _sender, address _id) public view returns (bool) { address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == address(0)) { return false; } else { return (positions[_id].created && (positions[_id].advocateId == _nameId || positions[_id].listenerId == _nameId || positions[_id].speakerId == _nameId ) ); } } /** * @dev Check whether or not _nameId is advocate of _id * @param _nameId The name ID to be checked * @param _id The ID to be checked * @return true if yes, false otherwise */ function nameIsAdvocate(address _nameId, address _id) public view returns (bool) { return (positions[_id].created && positions[_id].advocateId == _nameId); } /** * @dev Determine whether or not `_sender` is Advocate/Listener/Speaker of the Name/TAO * @param _sender The ETH address that to check * @param _id The ID of the Name/TAO * @return 1 if Advocate. 2 if Listener. 3 if Speaker */ function determinePosition(address _sender, address _id) public view returns (uint256) { require (senderIsPosition(_sender, _id)); Position memory _position = positions[_id]; address _nameId = _nameFactory.ethAddressToNameId(_sender); if (_nameId == _position.advocateId) { return 1; } else if (_nameId == _position.listenerId) { return 2; } else { return 3; } } /** * @dev Add Position for a Name/TAO * @param _id The ID of the Name/TAO * @param _advocateId The Advocate ID of the Name/TAO * @param _listenerId The Listener ID of the Name/TAO * @param _speakerId The Speaker ID of the Name/TAO * @return true on success */ function add(address _id, address _advocateId, address _listenerId, address _speakerId) public isNameOrTAO(_id) isName(_advocateId) isNameOrTAO(_listenerId) isNameOrTAO(_speakerId) onlyFactory returns (bool) { require (!isExist(_id)); Position storage _position = positions[_id]; _position.advocateId = _advocateId; _position.listenerId = _listenerId; _position.speakerId = _speakerId; _position.created = true; return true; } /** * @dev Get Name/TAO's Position info * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO * @return the Listener ID of Name/TAO * @return the Speaker ID of Name/TAO */ function getPositionById(address _id) public view returns (address, address, address) { require (isExist(_id)); Position memory _position = positions[_id]; return ( _position.advocateId, _position.listenerId, _position.speakerId ); } /** * @dev Get Name/TAO's Advocate * @param _id The ID of the Name/TAO * @return the Advocate ID of Name/TAO */ function getAdvocate(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.advocateId; } /** * @dev Get Name/TAO's Listener * @param _id The ID of the Name/TAO * @return the Listener ID of Name/TAO */ function getListener(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.listenerId; } /** * @dev Get Name/TAO's Speaker * @param _id The ID of the Name/TAO * @return the Speaker ID of Name/TAO */ function getSpeaker(address _id) public view returns (address) { require (isExist(_id)); Position memory _position = positions[_id]; return _position.speakerId; } /** * @dev Set Advocate for a TAO * @param _taoId The ID of the TAO * @param _newAdvocateId The new advocate ID to be set */ function setAdvocate(address _taoId, address _newAdvocateId) public isTAO(_taoId) isName(_newAdvocateId) senderIsName() onlyAdvocate(_taoId) { Position storage _position = positions[_taoId]; address _currentAdvocateId = _position.advocateId; _position.advocateId = _newAdvocateId; uint256 _nonce = _taoFactory.incrementNonce(_taoId); require (_nonce > 0); emit SetAdvocate(_taoId, _currentAdvocateId, _position.advocateId, _nonce); } /** * @dev Set Listener for a Name/TAO * @param _id The ID of the Name/TAO * @param _newListenerId The new listener ID to be set */ function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Listener can only be a Name // If _id is a TAO, then new Listener can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); } /** * @dev Set Speaker for a Name/TAO * @param _id The ID of the Name/TAO * @param _newSpeakerId The new speaker ID to be set */ function setSpeaker(address _id, address _newSpeakerId) public isNameOrTAO(_id) isNameOrTAO(_newSpeakerId) senderIsName() onlyAdvocate(_id) { // If _id is a Name, then new Speaker can only be a Name // If _id is a TAO, then new Speaker can be a TAO/Name bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newSpeakerId)); } Position storage _position = positions[_id]; address _currentSpeakerId = _position.speakerId; _position.speakerId = _newSpeakerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); } else { _nonce = _taoFactory.incrementNonce(_id); } emit SetSpeaker(_id, _currentSpeakerId, _position.speakerId, _nonce); } } /** * @title AOSetting * * This contract stores all AO setting variables */ contract AOSetting { address public aoSettingAttributeAddress; address public aoUintSettingAddress; address public aoBoolSettingAddress; address public aoAddressSettingAddress; address public aoBytesSettingAddress; address public aoStringSettingAddress; NameFactory internal _nameFactory; NameTAOPosition internal _nameTAOPosition; AOSettingAttribute internal _aoSettingAttribute; AOUintSetting internal _aoUintSetting; AOBoolSetting internal _aoBoolSetting; AOAddressSetting internal _aoAddressSetting; AOBytesSetting internal _aoBytesSetting; AOStringSetting internal _aoStringSetting; uint256 public totalSetting; /** * Mapping from associatedTAOId's setting name to Setting ID. * * Instead of concatenating the associatedTAOID and setting name to create a unique ID for lookup, * use nested mapping to achieve the same result. * * The setting's name needs to be converted to bytes32 since solidity does not support mapping by string. */ mapping (address => mapping (bytes32 => uint256)) internal nameSettingLookup; // Mapping from updateHashKey to it's settingId mapping (bytes32 => uint256) public updateHashLookup; // Event to be broadcasted to public when a setting is created and waiting for approval event SettingCreation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, string settingName, uint8 settingType, bytes32 associatedTAOSettingId, bytes32 creatorTAOSettingId); // Event to be broadcasted to public when setting creation is approved/rejected by the advocate of associatedTAOId event ApproveSettingCreation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting creation is finalized by the advocate of creatorTAOId event FinalizeSettingCreation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); // Event to be broadcasted to public when a proposed update for a setting is created event SettingUpdate(uint256 indexed settingId, address indexed updateAdvocateNameId, address proposalTAOId); // Event to be broadcasted to public when setting update is approved/rejected by the advocate of proposalTAOId event ApproveSettingUpdate(uint256 indexed settingId, address proposalTAOId, address proposalTAOAdvocate, bool approved); // Event to be broadcasted to public when setting update is finalized by the advocate of associatedTAOId event FinalizeSettingUpdate(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate); // Event to be broadcasted to public when a setting deprecation is created and waiting for approval event SettingDeprecation(uint256 indexed settingId, address indexed creatorNameId, address creatorTAOId, address associatedTAOId, uint256 newSettingId, address newSettingContractAddress, bytes32 associatedTAOSettingDeprecationId, bytes32 creatorTAOSettingDeprecationId); // Event to be broadcasted to public when setting deprecation is approved/rejected by the advocate of associatedTAOId event ApproveSettingDeprecation(uint256 indexed settingId, address associatedTAOId, address associatedTAOAdvocate, bool approved); // Event to be broadcasted to public when setting deprecation is finalized by the advocate of creatorTAOId event FinalizeSettingDeprecation(uint256 indexed settingId, address creatorTAOId, address creatorTAOAdvocate); /** * @dev Constructor function */ constructor(address _nameFactoryAddress, address _nameTAOPositionAddress, address _aoSettingAttributeAddress, address _aoUintSettingAddress, address _aoBoolSettingAddress, address _aoAddressSettingAddress, address _aoBytesSettingAddress, address _aoStringSettingAddress) public { aoSettingAttributeAddress = _aoSettingAttributeAddress; aoUintSettingAddress = _aoUintSettingAddress; aoBoolSettingAddress = _aoBoolSettingAddress; aoAddressSettingAddress = _aoAddressSettingAddress; aoBytesSettingAddress = _aoBytesSettingAddress; aoStringSettingAddress = _aoStringSettingAddress; _nameFactory = NameFactory(_nameFactoryAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); _aoSettingAttribute = AOSettingAttribute(_aoSettingAttributeAddress); _aoUintSetting = AOUintSetting(_aoUintSettingAddress); _aoBoolSetting = AOBoolSetting(_aoBoolSettingAddress); _aoAddressSetting = AOAddressSetting(_aoAddressSettingAddress); _aoBytesSetting = AOBytesSetting(_aoBytesSettingAddress); _aoStringSetting = AOStringSetting(_aoStringSettingAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_settingName` of `_associatedTAOId` is taken */ modifier settingNameNotTaken(string _settingName, address _associatedTAOId) { require (settingNameExist(_settingName, _associatedTAOId) == false); _; } /** * @dev Check if msg.sender is the current advocate of Name ID */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** Public Methods *****/ /** * @dev Check whether or not a setting name of an associatedTAOId exist * @param _settingName The human-readable name of the setting * @param _associatedTAOId The taoId that the setting affects * @return true if yes. false otherwise */ function settingNameExist(string _settingName, address _associatedTAOId) public view returns (bool) { return (nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] > 0); } /** * @dev Advocate of _creatorTAOId adds a uint setting * @param _settingName The human-readable name of the setting * @param _value The uint256 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addUintSetting(string _settingName, uint256 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoUintSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 1, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bool setting * @param _settingName The human-readable name of the setting * @param _value The bool value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBoolSetting(string _settingName, bool _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBoolSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 2, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds an address setting * @param _settingName The human-readable name of the setting * @param _value The address value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addAddressSetting(string _settingName, address _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoAddressSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 3, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a bytes32 setting * @param _settingName The human-readable name of the setting * @param _value The bytes32 value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addBytesSetting(string _settingName, bytes32 _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoBytesSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 4, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of _creatorTAOId adds a string setting * @param _settingName The human-readable name of the setting * @param _value The string value of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function addStringSetting(string _settingName, string _value, address _creatorTAOId, address _associatedTAOId, string _extraData) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) settingNameNotTaken(_settingName, _associatedTAOId) onlyAdvocate(_creatorTAOId) { // Update global variables totalSetting++; // Store the value as pending value _aoStringSetting.setPendingValue(totalSetting, _value); // Store setting creation data _storeSettingCreation(_nameFactory.ethAddressToNameId(msg.sender), 5, _settingName, _creatorTAOId, _associatedTAOId, _extraData); } /** * @dev Advocate of Setting's _associatedTAOId approves setting creation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingCreation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveAdd(_settingId, _associatedTAOAdvocate, _approved)); (,,,address _associatedTAOId, string memory _settingName,,,,,) = _aoSettingAttribute.getSettingData(_settingId); if (!_approved) { // Clear the settingName from nameSettingLookup so it can be added again in the future delete nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } emit ApproveSettingCreation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _creatorTAOId finalizes the setting creation once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingCreation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeAdd(_settingId, _creatorTAOAdvocate)); (,,address _creatorTAOId,,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingCreation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Advocate of Setting's _associatedTAOId submits a uint256 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new uint256 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateUintSetting(uint256 _settingId, uint256 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 1, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoUintSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoUintSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bool setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bool value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBoolSetting(uint256 _settingId, bool _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 2, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBoolSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBoolSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits an address setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new address value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateAddressSetting(uint256 _settingId, address _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 3, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoAddressSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoAddressSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a bytes32 setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new bytes32 value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateBytesSetting(uint256 _settingId, bytes32 _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 4, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoBytesSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoBytesSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's _associatedTAOId submits a string setting update after an update has been proposed * @param _settingId The ID of the setting to be updated * @param _newValue The new string value for this setting * @param _proposalTAOId The child of the associatedTAOId with the update Logos * @param _updateSignature A signature of the proposalTAOId and update value by associatedTAOId's advocate's name address * @param _extraData Catch-all string value to be stored if exist */ function updateStringSetting(uint256 _settingId, string _newValue, address _proposalTAOId, string _updateSignature, string _extraData) public isTAO(_proposalTAOId) { // Store the setting state data require (_aoSettingAttribute.update(_settingId, 5, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId, _updateSignature, _extraData)); // Store the value as pending value _aoStringSetting.setPendingValue(_settingId, _newValue); // Store the update hash key lookup updateHashLookup[keccak256(abi.encodePacked(this, _proposalTAOId, _aoStringSetting.settingValue(_settingId), _newValue, _extraData, _settingId))] = _settingId; emit SettingUpdate(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _proposalTAOId); } /** * @dev Advocate of Setting's proposalTAOId approves the setting update * @param _settingId The ID of the setting to be approved * @param _approved Whether to approve or reject */ function approveSettingUpdate(uint256 _settingId, bool _approved) public { address _proposalTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); (,,, address _proposalTAOId,,,) = _aoSettingAttribute.getSettingState(_settingId); require (_aoSettingAttribute.approveUpdate(_settingId, _proposalTAOAdvocate, _approved)); emit ApproveSettingUpdate(_settingId, _proposalTAOId, _proposalTAOAdvocate, _approved); } /** * @dev Advocate of Setting's _associatedTAOId finalizes the setting update once the setting is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingUpdate(uint256 _settingId) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeUpdate(_settingId, _associatedTAOAdvocate)); (,,, address _associatedTAOId,, uint8 _settingType,,,,) = _aoSettingAttribute.getSettingData(_settingId); _movePendingToSetting(_settingId, _settingType); emit FinalizeSettingUpdate(_settingId, _associatedTAOId, _associatedTAOAdvocate); } /** * @dev Advocate of _creatorTAOId adds a setting deprecation * @param _settingId The ID of the setting to be deprecated * @param _newSettingId The new setting ID to route * @param _newSettingContractAddress The new setting contract address to route * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects */ function addSettingDeprecation(uint256 _settingId, uint256 _newSettingId, address _newSettingContractAddress, address _creatorTAOId, address _associatedTAOId) public isTAO(_creatorTAOId) isTAO(_associatedTAOId) onlyAdvocate(_creatorTAOId) { (bytes32 _associatedTAOSettingDeprecationId, bytes32 _creatorTAOSettingDeprecationId) = _aoSettingAttribute.addDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress); emit SettingDeprecation(_settingId, _nameFactory.ethAddressToNameId(msg.sender), _creatorTAOId, _associatedTAOId, _newSettingId, _newSettingContractAddress, _associatedTAOSettingDeprecationId, _creatorTAOSettingDeprecationId); } /** * @dev Advocate of SettingDeprecation's _associatedTAOId approves setting deprecation * @param _settingId The ID of the setting to approve * @param _approved Whether to approve or reject */ function approveSettingDeprecation(uint256 _settingId, bool _approved) public { address _associatedTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.approveDeprecation(_settingId, _associatedTAOAdvocate, _approved)); (,,, address _associatedTAOId,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit ApproveSettingDeprecation(_settingId, _associatedTAOId, _associatedTAOAdvocate, _approved); } /** * @dev Advocate of SettingDeprecation's _creatorTAOId finalizes the setting deprecation once the setting deprecation is approved * @param _settingId The ID of the setting to be finalized */ function finalizeSettingDeprecation(uint256 _settingId) public { address _creatorTAOAdvocate = _nameFactory.ethAddressToNameId(msg.sender); require (_aoSettingAttribute.finalizeDeprecation(_settingId, _creatorTAOAdvocate)); (,, address _creatorTAOId,,,,,,,,,) = _aoSettingAttribute.getSettingDeprecation(_settingId); emit FinalizeSettingDeprecation(_settingId, _creatorTAOId, _creatorTAOAdvocate); } /** * @dev Get setting Id given an associatedTAOId and settingName * @param _associatedTAOId The ID of the AssociatedTAO * @param _settingName The name of the setting * @return the ID of the setting */ function getSettingIdByTAOName(address _associatedTAOId, string _settingName) public view returns (uint256) { return nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))]; } /** * @dev Get setting values by setting ID. * Will throw error if the setting is not exist or rejected. * @param _settingId The ID of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesById(uint256 _settingId) public view returns (uint256, bool, address, bytes32, string) { require (_aoSettingAttribute.settingExist(_settingId)); _settingId = _aoSettingAttribute.getLatestSettingId(_settingId); return ( _aoUintSetting.settingValue(_settingId), _aoBoolSetting.settingValue(_settingId), _aoAddressSetting.settingValue(_settingId), _aoBytesSetting.settingValue(_settingId), _aoStringSetting.settingValue(_settingId) ); } /** * @dev Get setting values by taoId and settingName. * Will throw error if the setting is not exist or rejected. * @param _taoId The ID of the TAO * @param _settingName The name of the setting * @return the uint256 value of this setting ID * @return the bool value of this setting ID * @return the address value of this setting ID * @return the bytes32 value of this setting ID * @return the string value of this setting ID */ function getSettingValuesByTAOName(address _taoId, string _settingName) public view returns (uint256, bool, address, bytes32, string) { return getSettingValuesById(getSettingIdByTAOName(_taoId, _settingName)); } /***** Internal Method *****/ /** * @dev Store setting creation data * @param _creatorNameId The nameId that created the setting * @param _settingType The type of this setting. 1 => uint256, 2 => bool, 3 => address, 4 => bytes32, 5 => string * @param _settingName The human-readable name of the setting * @param _creatorTAOId The taoId that created the setting * @param _associatedTAOId The taoId that the setting affects * @param _extraData Catch-all string value to be stored if exist */ function _storeSettingCreation(address _creatorNameId, uint8 _settingType, string _settingName, address _creatorTAOId, address _associatedTAOId, string _extraData) internal { // Make sure _settingType is in supported list require (_settingType >= 1 && _settingType <= 5); // Store nameSettingLookup nameSettingLookup[_associatedTAOId][keccak256(abi.encodePacked(this, _settingName))] = totalSetting; // Store setting data/state (bytes32 _associatedTAOSettingId, bytes32 _creatorTAOSettingId) = _aoSettingAttribute.add(totalSetting, _creatorNameId, _settingType, _settingName, _creatorTAOId, _associatedTAOId, _extraData); emit SettingCreation(totalSetting, _creatorNameId, _creatorTAOId, _associatedTAOId, _settingName, _settingType, _associatedTAOSettingId, _creatorTAOSettingId); } /** * @dev Move value of _settingId from pending variable to setting variable * @param _settingId The ID of the setting * @param _settingType The type of the setting */ function _movePendingToSetting(uint256 _settingId, uint8 _settingType) internal { // If settingType == uint256 if (_settingType == 1) { _aoUintSetting.movePendingToSetting(_settingId); } else if (_settingType == 2) { // Else if settingType == bool _aoBoolSetting.movePendingToSetting(_settingId); } else if (_settingType == 3) { // Else if settingType == address _aoAddressSetting.movePendingToSetting(_settingId); } else if (_settingType == 4) { // Else if settingType == bytes32 _aoBytesSetting.movePendingToSetting(_settingId); } else { // Else if settingType == string _aoStringSetting.movePendingToSetting(_settingId); } } } /** * @title AOEarning * * This contract stores the earning from staking/hosting content on AO */ contract AOEarning is TheAO { using SafeMath for uint256; address public settingTAOId; address public aoSettingAddress; address public baseDenominationAddress; address public treasuryAddress; address public nameFactoryAddress; address public pathosAddress; address public ethosAddress; bool public paused; bool public killed; AOToken internal _baseAO; AOTreasury internal _treasury; NameFactory internal _nameFactory; Pathos internal _pathos; Ethos internal _ethos; AOSetting internal _aoSetting; // Total earning from staking content from all nodes uint256 public totalStakeContentEarning; // Total earning from hosting content from all nodes uint256 public totalHostContentEarning; // Total The AO earning uint256 public totalTheAOEarning; // Mapping from address to his/her earning from content that he/she staked mapping (address => uint256) public stakeContentEarning; // Mapping from address to his/her earning from content that he/she hosted mapping (address => uint256) public hostContentEarning; // Mapping from address to his/her network price earning // i.e, when staked amount = filesize mapping (address => uint256) public networkPriceEarning; // Mapping from address to his/her content price earning // i.e, when staked amount > filesize mapping (address => uint256) public contentPriceEarning; // Mapping from address to his/her inflation bonus mapping (address => uint256) public inflationBonusAccrued; struct Earning { bytes32 purchaseId; uint256 paymentEarning; uint256 inflationBonus; uint256 pathosAmount; uint256 ethosAmount; } // Mapping from address to earning from staking content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public stakeEarnings; // Mapping from address to earning from hosting content of a purchase ID mapping (address => mapping(bytes32 => Earning)) public hostEarnings; // Mapping from purchase ID to earning for The AO mapping (bytes32 => Earning) public theAOEarnings; // Mapping from stake ID to it's total earning from staking mapping (bytes32 => uint256) public totalStakedContentStakeEarning; // Mapping from stake ID to it's total earning from hosting mapping (bytes32 => uint256) public totalStakedContentHostEarning; // Mapping from stake ID to it's total earning earned by The AO mapping (bytes32 => uint256) public totalStakedContentTheAOEarning; // Mapping from content host ID to it's total earning mapping (bytes32 => uint256) public totalHostContentEarningById; // Event to be broadcasted to public when content creator/host earns the payment split in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event PaymentEarningEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalPaymentAmount, uint256 recipientProfitPercentage, uint256 recipientPaymentEarning, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earns inflation bonus in escrow when request node buys the content // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event InflationBonusEscrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 totalInflationBonusAmount, uint256 recipientProfitPercentage, uint256 recipientInflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator/host/The AO earning is released from escrow // recipientType: // 0 => Content Creator (Stake Owner) // 1 => Node Host // 2 => The AO event EarningUnescrowed(address indexed recipient, bytes32 indexed purchaseId, uint256 paymentEarning, uint256 inflationBonus, uint8 recipientType); // Event to be broadcasted to public when content creator's Name earns Pathos when a node buys a content event PathosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when host's Name earns Ethos when a node buys a content event EthosEarned(address indexed nameId, bytes32 indexed purchaseId, uint256 amount); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _nameFactoryAddress The address of NameFactory * @param _pathosAddress The address of Pathos * @param _ethosAddress The address of Ethos */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _nameFactoryAddress, address _pathosAddress, address _ethosAddress) public { settingTAOId = _settingTAOId; aoSettingAddress = _aoSettingAddress; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; pathosAddress = _pathosAddress; ethosAddress = _ethosAddress; _aoSetting = AOSetting(_aoSettingAddress); _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _nameFactory = NameFactory(_nameFactoryAddress); _pathos = Pathos(_pathosAddress); _ethos = Ethos(_ethosAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Calculate the content creator/host/The AO earning when request node buys the content. * Also at this stage, all of the earnings are stored in escrow * @param _buyer The request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function calculateEarning( address _buyer, bytes32 _purchaseId, uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) public isContractActive inWhitelist returns (bool) { // Split the payment earning between content creator and host and store them in escrow _escrowPaymentEarning(_buyer, _purchaseId, _networkAmountStaked.add(_primordialAmountStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); // Calculate the inflation bonus earning for content creator/node/The AO in escrow _escrowInflationBonus(_purchaseId, _calculateInflationBonus(_networkAmountStaked, _primordialAmountStaked, _primordialWeightedMultiplierStaked), _profitPercentage, _stakeOwner, _host, _isAOContentUsageType); return true; } /** * @dev Release the payment earning and inflation bonus that is in escrow for specific purchase ID * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID to check * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _stakeOwner The address of the stake owner * @param _host The address of the node that host the file * @return true on success */ function releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _stakeOwner, address _host) public isContractActive inWhitelist returns (bool) { // Release the earning in escrow for stake owner _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _stakeOwner, 0); // Release the earning in escrow for host _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, _host, 1); // Release the earning in escrow for The AO _releaseEarning(_stakeId, _contentHostId, _purchaseId, _buyerPaidMoreThanFileSize, theAO, 2); return true; } /***** INTERNAL METHODS *****/ /** * @dev Calculate the payment split for content creator/host and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType) internal { (uint256 _stakeOwnerEarning, uint256 _pathosAmount) = _escrowStakeOwnerPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _stakeOwner, _isAOContentUsageType); (uint256 _ethosAmount) = _escrowHostPaymentEarning(_buyer, _purchaseId, _totalStaked, _profitPercentage, _host, _isAOContentUsageType, _stakeOwnerEarning); _escrowTheAOPaymentEarning(_purchaseId, _totalStaked, _pathosAmount, _ethosAmount); } /** * @dev Calculate the inflation bonus amount * @param _networkAmountStaked The amount of network tokens at stake * @param _primordialAmountStaked The amount of primordial tokens at stake * @param _primordialWeightedMultiplierStaked The weighted multiplier of primordial tokens at stake * @return the bonus network amount */ function _calculateInflationBonus(uint256 _networkAmountStaked, uint256 _primordialAmountStaked, uint256 _primordialWeightedMultiplierStaked) internal view returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); uint256 _networkBonus = _networkAmountStaked.mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); uint256 _primordialBonus = _primordialAmountStaked.mul(_primordialWeightedMultiplierStaked).div(AOLibrary.MULTIPLIER_DIVISOR()).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()); return _networkBonus.add(_primordialBonus); } /** * @dev Mint the inflation bonus for content creator/host/The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _inflationBonusAmount The amount of inflation bonus earning * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _host The address of the host * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type */ function _escrowInflationBonus( bytes32 _purchaseId, uint256 _inflationBonusAmount, uint256 _profitPercentage, address _stakeOwner, address _host, bool _isAOContentUsageType ) internal { (, uint256 theAOCut,) = _getSettingVariables(); if (_inflationBonusAmount > 0) { // Store how much the content creator earns in escrow uint256 _stakeOwnerInflationBonus = _isAOContentUsageType ? (_inflationBonusAmount.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.inflationBonus = _stakeOwnerInflationBonus; require (_baseAO.mintTokenEscrow(_stakeOwner, _stakeEarning.inflationBonus)); emit InflationBonusEscrowed(_stakeOwner, _purchaseId, _inflationBonusAmount, _profitPercentage, _stakeEarning.inflationBonus, 0); // Store how much the host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.inflationBonus = _inflationBonusAmount.sub(_stakeOwnerInflationBonus); require (_baseAO.mintTokenEscrow(_host, _hostEarning.inflationBonus)); emit InflationBonusEscrowed(_host, _purchaseId, _inflationBonusAmount, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.inflationBonus, 1); // Store how much the The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.inflationBonus = (_inflationBonusAmount.mul(theAOCut)).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.inflationBonus)); emit InflationBonusEscrowed(theAO, _purchaseId, _inflationBonusAmount, theAOCut, _theAOEarning.inflationBonus, 2); } else { emit InflationBonusEscrowed(_stakeOwner, _purchaseId, 0, _profitPercentage, 0, 0); emit InflationBonusEscrowed(_host, _purchaseId, 0, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), 0, 1); emit InflationBonusEscrowed(theAO, _purchaseId, 0, theAOCut, 0, 2); } } /** * @dev Release the escrowed earning for a specific purchase ID for an account * @param _stakeId The ID of the staked content * @param _contentHostId The ID of the hosted content * @param _purchaseId The purchase receipt ID * @param _buyerPaidMoreThanFileSize Whether or not the request node paid more than filesize when buying the content * @param _account The address of account that made the earning (content creator/host) * @param _recipientType The type of the earning recipient (0 => content creator. 1 => host. 2 => theAO) */ function _releaseEarning(bytes32 _stakeId, bytes32 _contentHostId, bytes32 _purchaseId, bool _buyerPaidMoreThanFileSize, address _account, uint8 _recipientType) internal { // Make sure the recipient type is valid require (_recipientType >= 0 && _recipientType <= 2); uint256 _paymentEarning; uint256 _inflationBonus; uint256 _totalEarning; uint256 _pathosAmount; uint256 _ethosAmount; if (_recipientType == 0) { Earning storage _earning = stakeEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _pathosAmount = _earning.pathosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalStakeContentEarning = totalStakeContentEarning.add(_totalEarning); stakeContentEarning[_account] = stakeContentEarning[_account].add(_totalEarning); totalStakedContentStakeEarning[_stakeId] = totalStakedContentStakeEarning[_stakeId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the content creator/stake owner with some Pathos require (_pathos.mintToken(_nameFactory.ethAddressToNameId(_account), _pathosAmount)); emit PathosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _pathosAmount); } else if (_recipientType == 1) { _earning = hostEarnings[_account][_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _ethosAmount = _earning.ethosAmount; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalHostContentEarning = totalHostContentEarning.add(_totalEarning); hostContentEarning[_account] = hostContentEarning[_account].add(_totalEarning); totalStakedContentHostEarning[_stakeId] = totalStakedContentHostEarning[_stakeId].add(_totalEarning); totalHostContentEarningById[_contentHostId] = totalHostContentEarningById[_contentHostId].add(_totalEarning); if (_buyerPaidMoreThanFileSize) { contentPriceEarning[_account] = contentPriceEarning[_account].add(_totalEarning); } else { networkPriceEarning[_account] = networkPriceEarning[_account].add(_totalEarning); } inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); // Reward the host node with some Ethos require (_ethos.mintToken(_nameFactory.ethAddressToNameId(_account), _ethosAmount)); emit EthosEarned(_nameFactory.ethAddressToNameId(_account), _purchaseId, _ethosAmount); } else { _earning = theAOEarnings[_purchaseId]; _paymentEarning = _earning.paymentEarning; _inflationBonus = _earning.inflationBonus; _earning.paymentEarning = 0; _earning.inflationBonus = 0; _earning.pathosAmount = 0; _earning.ethosAmount = 0; _totalEarning = _paymentEarning.add(_inflationBonus); // Update the global var settings totalTheAOEarning = totalTheAOEarning.add(_totalEarning); inflationBonusAccrued[_account] = inflationBonusAccrued[_account].add(_inflationBonus); totalStakedContentTheAOEarning[_stakeId] = totalStakedContentTheAOEarning[_stakeId].add(_totalEarning); } require (_baseAO.unescrowFrom(_account, _totalEarning)); emit EarningUnescrowed(_account, _purchaseId, _paymentEarning, _inflationBonus, _recipientType); } /** * @dev Get setting variables * @return inflationRate The rate to use when calculating inflation bonus * @return theAOCut The rate to use when calculating the AO earning * @return theAOEthosEarnedRate The rate to use when calculating the Ethos to AO rate for the AO */ function _getSettingVariables() internal view returns (uint256, uint256, uint256) { (uint256 inflationRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'inflationRate'); (uint256 theAOCut,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOCut'); (uint256 theAOEthosEarnedRate,,,,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'theAOEthosEarnedRate'); return (inflationRate, theAOCut, theAOEthosEarnedRate); } /** * @dev Calculate the payment split for content creator and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _stakeOwner The address of the stake owner * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @return The stake owner's earning amount * @return The pathos earned from this transaction */ function _escrowStakeOwnerPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _stakeOwner, bool _isAOContentUsageType) internal returns (uint256, uint256) { (uint256 inflationRate,,) = _getSettingVariables(); Earning storage _stakeEarning = stakeEarnings[_stakeOwner][_purchaseId]; _stakeEarning.purchaseId = _purchaseId; // Store how much the content creator (stake owner) earns in escrow // If content is AO Content Usage Type, stake owner earns 0% // and all profit goes to the serving host node _stakeEarning.paymentEarning = _isAOContentUsageType ? (_totalStaked.mul(_profitPercentage)).div(AOLibrary.PERCENTAGE_DIVISOR()) : 0; // Pathos = Price X Node Share X Inflation Rate _stakeEarning.pathosAmount = _totalStaked.mul(AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage)).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); require (_baseAO.escrowFrom(_buyer, _stakeOwner, _stakeEarning.paymentEarning)); emit PaymentEarningEscrowed(_stakeOwner, _purchaseId, _totalStaked, _profitPercentage, _stakeEarning.paymentEarning, 0); return (_stakeEarning.paymentEarning, _stakeEarning.pathosAmount); } /** * @dev Calculate the payment split for host node and store them in escrow * @param _buyer the request node address that buys the content * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _profitPercentage The content creator's profit percentage * @param _host The address of the host node * @param _isAOContentUsageType whether or not the content is of AO Content Usage Type * @param _stakeOwnerEarning The stake owner's earning amount * @return The ethos earned from this transaction */ function _escrowHostPaymentEarning(address _buyer, bytes32 _purchaseId, uint256 _totalStaked, uint256 _profitPercentage, address _host, bool _isAOContentUsageType, uint256 _stakeOwnerEarning) internal returns (uint256) { (uint256 inflationRate,,) = _getSettingVariables(); // Store how much the node host earns in escrow Earning storage _hostEarning = hostEarnings[_host][_purchaseId]; _hostEarning.purchaseId = _purchaseId; _hostEarning.paymentEarning = _totalStaked.sub(_stakeOwnerEarning); // Ethos = Price X Creator Share X Inflation Rate _hostEarning.ethosAmount = _totalStaked.mul(_profitPercentage).mul(inflationRate).div(AOLibrary.PERCENTAGE_DIVISOR()).div(AOLibrary.PERCENTAGE_DIVISOR()); if (_isAOContentUsageType) { require (_baseAO.escrowFrom(_buyer, _host, _hostEarning.paymentEarning)); } else { // If not AO Content usage type, we want to mint to the host require (_baseAO.mintTokenEscrow(_host, _hostEarning.paymentEarning)); } emit PaymentEarningEscrowed(_host, _purchaseId, _totalStaked, AOLibrary.PERCENTAGE_DIVISOR().sub(_profitPercentage), _hostEarning.paymentEarning, 1); return _hostEarning.ethosAmount; } /** * @dev Calculate the earning for The AO and store them in escrow * @param _purchaseId The ID of the purchase receipt object * @param _totalStaked The total staked amount of the content * @param _pathosAmount The amount of pathos earned by stake owner * @param _ethosAmount The amount of ethos earned by host node */ function _escrowTheAOPaymentEarning(bytes32 _purchaseId, uint256 _totalStaked, uint256 _pathosAmount, uint256 _ethosAmount) internal { (,,uint256 theAOEthosEarnedRate) = _getSettingVariables(); // Store how much The AO earns in escrow Earning storage _theAOEarning = theAOEarnings[_purchaseId]; _theAOEarning.purchaseId = _purchaseId; // Pathos + X% of Ethos _theAOEarning.paymentEarning = _pathosAmount.add(_ethosAmount.mul(theAOEthosEarnedRate).div(AOLibrary.PERCENTAGE_DIVISOR())); require (_baseAO.mintTokenEscrow(theAO, _theAOEarning.paymentEarning)); emit PaymentEarningEscrowed(theAO, _purchaseId, _totalStaked, 0, _theAOEarning.paymentEarning, 2); } } /** * @title AOContent * * The purpose of this contract is to allow content creator to stake network ERC20 AO tokens and/or primordial AO Tokens * on his/her content */ contract AOContent is TheAO { using SafeMath for uint256; uint256 public totalContents; uint256 public totalContentHosts; uint256 public totalStakedContents; uint256 public totalPurchaseReceipts; address public settingTAOId; address public baseDenominationAddress; address public treasuryAddress; AOToken internal _baseAO; AOTreasury internal _treasury; AOEarning internal _earning; AOSetting internal _aoSetting; NameTAOPosition internal _nameTAOPosition; bool public paused; bool public killed; struct Content { bytes32 contentId; address creator; /** * baseChallenge is the content's PUBLIC KEY * When a request node wants to be a host, it is required to send a signed base challenge (its content's PUBLIC KEY) * so that the contract can verify the authenticity of the content by comparing what the contract has and what the request node * submit */ string baseChallenge; uint256 fileSize; bytes32 contentUsageType; // i.e AO Content, Creative Commons, or T(AO) Content address taoId; bytes32 taoContentState; // i.e Submitted, Pending Review, Accepted to TAO uint8 updateTAOContentStateV; bytes32 updateTAOContentStateR; bytes32 updateTAOContentStateS; string extraData; } struct StakedContent { bytes32 stakeId; bytes32 contentId; address stakeOwner; uint256 networkAmount; // total network token staked in base denomination uint256 primordialAmount; // the amount of primordial AO Token to stake (always in base denomination) uint256 primordialWeightedMultiplier; uint256 profitPercentage; // support up to 4 decimals, 100% = 1000000 bool active; // true if currently staked, false when unstaked uint256 createdOnTimestamp; } struct ContentHost { bytes32 contentHostId; bytes32 stakeId; address host; /** * encChallenge is the content's PUBLIC KEY unique to the host */ string encChallenge; string contentDatKey; string metadataDatKey; } struct PurchaseReceipt { bytes32 purchaseId; bytes32 contentHostId; address buyer; uint256 price; uint256 amountPaidByBuyer; // total network token paid in base denomination uint256 amountPaidByAO; // total amount paid by AO string publicKey; // The public key provided by request node address publicAddress; // The public address provided by request node uint256 createdOnTimestamp; } // Mapping from Content index to the Content object mapping (uint256 => Content) internal contents; // Mapping from content ID to index of the contents list mapping (bytes32 => uint256) internal contentIndex; // Mapping from StakedContent index to the StakedContent object mapping (uint256 => StakedContent) internal stakedContents; // Mapping from stake ID to index of the stakedContents list mapping (bytes32 => uint256) internal stakedContentIndex; // Mapping from ContentHost index to the ContentHost object mapping (uint256 => ContentHost) internal contentHosts; // Mapping from content host ID to index of the contentHosts list mapping (bytes32 => uint256) internal contentHostIndex; // Mapping from PurchaseReceipt index to the PurchaseReceipt object mapping (uint256 => PurchaseReceipt) internal purchaseReceipts; // Mapping from purchase ID to index of the purchaseReceipts list mapping (bytes32 => uint256) internal purchaseReceiptIndex; // Mapping from buyer's content host ID to the buy ID // To check whether or not buyer has bought/paid for a content mapping (address => mapping (bytes32 => bytes32)) public buyerPurchaseReceipts; // Event to be broadcasted to public when `content` is stored event StoreContent(address indexed creator, bytes32 indexed contentId, uint256 fileSize, bytes32 contentUsageType); // Event to be broadcasted to public when `stakeOwner` stakes a new content event StakeContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 baseNetworkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier, uint256 profitPercentage, uint256 createdOnTimestamp); // Event to be broadcasted to public when a node hosts a content event HostContent(address indexed host, bytes32 indexed contentHostId, bytes32 stakeId, string contentDatKey, string metadataDatKey); // Event to be broadcasted to public when `stakeOwner` updates the staked content's profit percentage event SetProfitPercentage(address indexed stakeOwner, bytes32 indexed stakeId, uint256 newProfitPercentage); // Event to be broadcasted to public when `stakeOwner` unstakes some network/primordial token from an existing content event UnstakePartialContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 remainingNetworkAmount, uint256 remainingPrimordialAmount, uint256 primordialWeightedMultiplier); // Event to be broadcasted to public when `stakeOwner` unstakes all token amount on an existing content event UnstakeContent(address indexed stakeOwner, bytes32 indexed stakeId); // Event to be broadcasted to public when `stakeOwner` re-stakes an existing content event StakeExistingContent(address indexed stakeOwner, bytes32 indexed stakeId, bytes32 indexed contentId, uint256 currentNetworkAmount, uint256 currentPrimordialAmount, uint256 currentPrimordialWeightedMultiplier); // Event to be broadcasted to public when a request node buys a content event BuyContent(address indexed buyer, bytes32 indexed purchaseId, bytes32 indexed contentHostId, uint256 price, uint256 amountPaidByAO, uint256 amountPaidByBuyer, string publicKey, address publicAddress, uint256 createdOnTimestamp); // Event to be broadcasted to public when Advocate/Listener/Speaker wants to update the TAO Content's State event UpdateTAOContentState(bytes32 indexed contentId, address indexed taoId, address signer, bytes32 taoContentState); // Event to be broadcasted to public when emergency mode is triggered event EscapeHatch(); /** * @dev Constructor function * @param _settingTAOId The TAO ID that controls the setting * @param _aoSettingAddress The address of AOSetting * @param _baseDenominationAddress The address of AO base token * @param _treasuryAddress The address of AOTreasury * @param _earningAddress The address of AOEarning * @param _nameTAOPositionAddress The address of NameTAOPosition */ constructor(address _settingTAOId, address _aoSettingAddress, address _baseDenominationAddress, address _treasuryAddress, address _earningAddress, address _nameTAOPositionAddress) public { settingTAOId = _settingTAOId; baseDenominationAddress = _baseDenominationAddress; treasuryAddress = _treasuryAddress; nameTAOPositionAddress = _nameTAOPositionAddress; _baseAO = AOToken(_baseDenominationAddress); _treasury = AOTreasury(_treasuryAddress); _earning = AOEarning(_earningAddress); _aoSetting = AOSetting(_aoSettingAddress); _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /** * @dev Checks if contract is currently active */ modifier isContractActive { require (paused == false && killed == false); _; } /***** The AO ONLY METHODS *****/ /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev The AO pauses/unpauses contract * @param _paused Either to pause contract or not */ function setPaused(bool _paused) public onlyTheAO { paused = _paused; } /** * @dev The AO triggers emergency mode. * */ function escapeHatch() public onlyTheAO { require (killed == false); killed = true; emit EscapeHatch(); } /** * @dev The AO updates base denomination address * @param _newBaseDenominationAddress The new address */ function setBaseDenominationAddress(address _newBaseDenominationAddress) public onlyTheAO { require (AOToken(_newBaseDenominationAddress).powerOfTen() == 0); baseDenominationAddress = _newBaseDenominationAddress; _baseAO = AOToken(baseDenominationAddress); } /***** PUBLIC METHODS *****/ /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for an AO Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge */ function stakeAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, _profitPercentage)); (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_aoContent, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _profitPercentage ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a Creative Commons Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file */ function stakeCreativeCommonsContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require (_treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize); (,bytes32 _contentUsageType_creativeCommons,,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_creativeCommons, address(0) ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Stake `_networkIntegerAmount` + `_networkFractionAmount` of network token in `_denomination` and/or `_primordialAmount` primordial Tokens for a T(AO) Content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) */ function stakeTAOContent( uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, address _taoId) public isContractActive { require (AOLibrary.canStake(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _baseChallenge, _encChallenge, _contentDatKey, _metadataDatKey, _fileSize, 0)); require ( _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) == _fileSize && _nameTAOPosition.senderIsPosition(msg.sender, _taoId) ); (,,bytes32 _contentUsageType_taoContent,,,) = _getSettingVariables(); /** * 1. Store this content * 2. Stake the network/primordial token on content * 3. Add the node info that hosts this content (in this case the creator himself) */ _hostContent( msg.sender, _stakeContent( msg.sender, _storeContent( msg.sender, _baseChallenge, _fileSize, _contentUsageType_taoContent, _taoId ), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, 0 ), _encChallenge, _contentDatKey, _metadataDatKey ); } /** * @dev Set profit percentage on existing staked content * Will throw error if this is a Creative Commons/T(AO) Content * @param _stakeId The ID of the staked content * @param _profitPercentage The new value to be set */ function setProfitPercentage(bytes32 _stakeId, uint256 _profitPercentage) public isContractActive { require (_profitPercentage <= AOLibrary.PERCENTAGE_DIVISOR()); // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure we are updating profit percentage for AO Content only // Creative Commons/T(AO) Content has 0 profit percentage require (_isAOContentUsageType(_stakedContent.contentId)); _stakedContent.profitPercentage = _profitPercentage; emit SetProfitPercentage(msg.sender, _stakeId, _profitPercentage); } /** * @dev Set extra data on existing content * @param _contentId The ID of the content * @param _extraData some extra information to send to the contract for a content */ function setContentExtraData(bytes32 _contentId, string _extraData) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); Content storage _content = contents[contentIndex[_contentId]]; // Make sure the content creator is the same as the sender require (_content.creator == msg.sender); _content.extraData = _extraData; } /** * @dev Return content info at a given ID * @param _contentId The ID of the content * @return address of the creator * @return file size of the content * @return the content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @return The TAO ID for this content (if this is a T(AO) Content) * @return The TAO Content state, i.e Submitted, Pending Review, or Accepted to TAO * @return The V part of signature that is used to update the TAO Content State * @return The R part of signature that is used to update the TAO Content State * @return The S part of signature that is used to update the TAO Content State * @return the extra information sent to the contract when creating a content */ function contentById(bytes32 _contentId) public view returns (address, uint256, bytes32, address, bytes32, uint8, bytes32, bytes32, string) { // Make sure the content exist require (contentIndex[_contentId] > 0); Content memory _content = contents[contentIndex[_contentId]]; return ( _content.creator, _content.fileSize, _content.contentUsageType, _content.taoId, _content.taoContentState, _content.updateTAOContentStateV, _content.updateTAOContentStateR, _content.updateTAOContentStateS, _content.extraData ); } /** * @dev Return content host info at a given ID * @param _contentHostId The ID of the hosted content * @return The ID of the staked content * @return address of the host * @return the dat key of the content * @return the dat key of the content's metadata */ function contentHostById(bytes32 _contentHostId) public view returns (bytes32, address, string, string) { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; return ( _contentHost.stakeId, _contentHost.host, _contentHost.contentDatKey, _contentHost.metadataDatKey ); } /** * @dev Return staked content information at a given ID * @param _stakeId The ID of the staked content * @return The ID of the content being staked * @return address of the staked content's owner * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the profit percentage of the content * @return status of the staked content * @return the timestamp when the staked content was created */ function stakedContentById(bytes32 _stakeId) public view returns (bytes32, address, uint256, uint256, uint256, uint256, bool, uint256) { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; return ( _stakedContent.contentId, _stakedContent.stakeOwner, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.active, _stakedContent.createdOnTimestamp ); } /** * @dev Unstake existing staked content and refund partial staked amount to the stake owner * Use unstakeContent() to unstake all staked token amount. unstakePartialContent() can unstake only up to * the mininum required to pay the fileSize * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to unstake * @param _networkFractionAmount The fraction amount of network token to unstake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to unstake */ function unstakePartialContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the staked content has enough balance to unstake require (AOLibrary.canUnstakePartial(treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _stakedContent.networkAmount, _stakedContent.primordialAmount, _fileSize)); if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _unstakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.sub(_unstakeNetworkAmount); require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.sub(_primordialAmount); require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit UnstakePartialContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Unstake existing staked content and refund the total staked amount to the stake owner * @param _stakeId The ID of the staked content */ function unstakeContent(bytes32 _stakeId) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); // Make sure the staked content is currently active (staked) with some amounts require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); _stakedContent.active = false; if (_stakedContent.networkAmount > 0) { uint256 _unstakeNetworkAmount = _stakedContent.networkAmount; _stakedContent.networkAmount = 0; require (_baseAO.unstakeFrom(msg.sender, _unstakeNetworkAmount)); } if (_stakedContent.primordialAmount > 0) { uint256 _primordialAmount = _stakedContent.primordialAmount; uint256 _primordialWeightedMultiplier = _stakedContent.primordialWeightedMultiplier; _stakedContent.primordialAmount = 0; _stakedContent.primordialWeightedMultiplier = 0; require (_baseAO.unstakePrimordialTokenFrom(msg.sender, _primordialAmount, _primordialWeightedMultiplier)); } emit UnstakeContent(_stakedContent.stakeOwner, _stakeId); } /** * @dev Stake existing content with more tokens (this is to increase the price) * * @param _stakeId The ID of the staked content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake. (The primordial weighted multiplier has to match the current staked weighted multiplier) */ function stakeExistingContent(bytes32 _stakeId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount) public isContractActive { // Make sure the staked content exist require (stakedContentIndex[_stakeId] > 0); StakedContent storage _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; uint256 _fileSize = contents[contentIndex[_stakedContent.contentId]].fileSize; // Make sure the staked content owner is the same as the sender require (_stakedContent.stakeOwner == msg.sender); require (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0); require (AOLibrary.canStakeExisting(treasuryAddress, _isAOContentUsageType(_stakedContent.contentId), _fileSize, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount)); // Make sure we can stake primordial token // If we are currently staking an active staked content, then the stake owner's weighted multiplier has to match `stakedContent.primordialWeightedMultiplier` // i.e, can't use a combination of different weighted multiplier. Stake owner has to call unstakeContent() to unstake all tokens first if (_primordialAmount > 0 && _stakedContent.active && _stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0) { require (_baseAO.weightedMultiplierByAddress(msg.sender) == _stakedContent.primordialWeightedMultiplier); } _stakedContent.active = true; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { uint256 _stakeNetworkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); _stakedContent.networkAmount = _stakedContent.networkAmount.add(_stakeNetworkAmount); require (_baseAO.stakeFrom(_stakedContent.stakeOwner, _stakeNetworkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _stakedContent.primordialAmount.add(_primordialAmount); // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeExistingContent(msg.sender, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier); } /** * @dev Determine the content price hosted by a host * @param _contentHostId The content host ID to be checked * @return the price of the content */ function contentHostPrice(bytes32 _contentHostId) public isContractActive view returns (uint256) { // Make sure content host exist require (contentHostIndex[_contentHostId] > 0); bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_stakeId]]; // Make sure content is currently staked require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); return _stakedContent.networkAmount.add(_stakedContent.primordialAmount); } /** * @dev Determine the how much the content is paid by AO given a contentHostId * @param _contentHostId The content host ID to be checked * @return the amount paid by AO */ function contentHostPaidByAO(bytes32 _contentHostId) public isContractActive view returns (uint256) { bytes32 _stakeId = contentHosts[contentHostIndex[_contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; if (_isAOContentUsageType(_contentId)) { return 0; } else { return contentHostPrice(_contentHostId); } } /** * @dev Bring content in to the requesting node by sending network tokens to the contract to pay for the content * @param _contentHostId The ID of hosted content * @param _networkIntegerAmount The integer amount of network token to pay * @param _networkFractionAmount The fraction amount of network token to pay * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _publicKey The public key of the request node * @param _publicAddress The public address of the request node */ function buyContent(bytes32 _contentHostId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, string _publicKey, address _publicAddress) public isContractActive { // Make sure the content host exist require (contentHostIndex[_contentHostId] > 0); // Make sure public key is not empty require (bytes(_publicKey).length > 0); // Make sure public address is valid require (_publicAddress != address(0)); ContentHost memory _contentHost = contentHosts[contentHostIndex[_contentHostId]]; StakedContent memory _stakedContent = stakedContents[stakedContentIndex[_contentHost.stakeId]]; // Make sure the content currently has stake require (_stakedContent.active == true && (_stakedContent.networkAmount > 0 || (_stakedContent.primordialAmount > 0 && _stakedContent.primordialWeightedMultiplier > 0))); // Make sure the buyer has not bought this content previously require (buyerPurchaseReceipts[msg.sender][_contentHostId][0] == 0); // Make sure the token amount can pay for the content price if (_isAOContentUsageType(_stakedContent.contentId)) { require (AOLibrary.canBuy(treasuryAddress, _stakedContent.networkAmount.add(_stakedContent.primordialAmount), _networkIntegerAmount, _networkFractionAmount, _denomination)); } // Increment totalPurchaseReceipts; totalPurchaseReceipts++; // Generate purchaseId bytes32 _purchaseId = keccak256(abi.encodePacked(this, msg.sender, _contentHostId)); PurchaseReceipt storage _purchaseReceipt = purchaseReceipts[totalPurchaseReceipts]; // Make sure the node doesn't buy the same content twice require (_purchaseReceipt.buyer == address(0)); _purchaseReceipt.purchaseId = _purchaseId; _purchaseReceipt.contentHostId = _contentHostId; _purchaseReceipt.buyer = msg.sender; // Update the receipt with the correct network amount _purchaseReceipt.price = _stakedContent.networkAmount.add(_stakedContent.primordialAmount); _purchaseReceipt.amountPaidByAO = contentHostPaidByAO(_contentHostId); _purchaseReceipt.amountPaidByBuyer = _purchaseReceipt.price.sub(_purchaseReceipt.amountPaidByAO); _purchaseReceipt.publicKey = _publicKey; _purchaseReceipt.publicAddress = _publicAddress; _purchaseReceipt.createdOnTimestamp = now; purchaseReceiptIndex[_purchaseId] = totalPurchaseReceipts; buyerPurchaseReceipts[msg.sender][_contentHostId] = _purchaseId; // Calculate content creator/host/The AO earning from this purchase and store them in escrow require (_earning.calculateEarning( msg.sender, _purchaseId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.stakeOwner, _contentHost.host, _isAOContentUsageType(_stakedContent.contentId) )); emit BuyContent(_purchaseReceipt.buyer, _purchaseReceipt.purchaseId, _purchaseReceipt.contentHostId, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp); } /** * @dev Return purchase receipt info at a given ID * @param _purchaseId The ID of the purchased content * @return The ID of the content host * @return address of the buyer * @return price of the content * @return amount paid by AO * @return amount paid by Buyer * @return request node's public key * @return request node's public address * @return created on timestamp */ function purchaseReceiptById(bytes32 _purchaseId) public view returns (bytes32, address, uint256, uint256, uint256, string, address, uint256) { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; return ( _purchaseReceipt.contentHostId, _purchaseReceipt.buyer, _purchaseReceipt.price, _purchaseReceipt.amountPaidByAO, _purchaseReceipt.amountPaidByBuyer, _purchaseReceipt.publicKey, _purchaseReceipt.publicAddress, _purchaseReceipt.createdOnTimestamp ); } /** * @dev Request node wants to become a distribution node after buying the content * Also, if this transaction succeeds, contract will release all of the earnings that are * currently in escrow for content creator/host/The AO */ function becomeHost( bytes32 _purchaseId, uint8 _baseChallengeV, bytes32 _baseChallengeR, bytes32 _baseChallengeS, string _encChallenge, string _contentDatKey, string _metadataDatKey ) public isContractActive { // Make sure the purchase receipt exist require (purchaseReceiptIndex[_purchaseId] > 0); PurchaseReceipt memory _purchaseReceipt = purchaseReceipts[purchaseReceiptIndex[_purchaseId]]; bytes32 _stakeId = contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].stakeId; bytes32 _contentId = stakedContents[stakedContentIndex[_stakeId]].contentId; // Make sure the purchase receipt owner is the same as the sender require (_purchaseReceipt.buyer == msg.sender); // Verify that the file is not tampered by validating the base challenge signature // The signed base challenge key should match the one from content creator Content memory _content = contents[contentIndex[_contentId]]; require (AOLibrary.getBecomeHostSignatureAddress(address(this), _content.baseChallenge, _baseChallengeV, _baseChallengeR, _baseChallengeS) == _purchaseReceipt.publicAddress); _hostContent(msg.sender, _stakeId, _encChallenge, _contentDatKey, _metadataDatKey); // Release earning from escrow require (_earning.releaseEarning( _stakeId, _purchaseReceipt.contentHostId, _purchaseId, (_purchaseReceipt.amountPaidByBuyer > _content.fileSize), stakedContents[stakedContentIndex[_stakeId]].stakeOwner, contentHosts[contentHostIndex[_purchaseReceipt.contentHostId]].host) ); } /** * @dev Update the TAO Content State of a T(AO) Content * @param _contentId The ID of the Content * @param _taoId The ID of the TAO that initiates the update * @param _taoContentState The TAO Content state value, i.e Submitted, Pending Review, or Accepted to TAO * @param _updateTAOContentStateV The V part of the signature for this update * @param _updateTAOContentStateR The R part of the signature for this update * @param _updateTAOContentStateS The S part of the signature for this update */ function updateTAOContentState( bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _updateTAOContentStateV, bytes32 _updateTAOContentStateR, bytes32 _updateTAOContentStateS ) public isContractActive { // Make sure the content exist require (contentIndex[_contentId] > 0); require (AOLibrary.isTAO(_taoId)); (,, bytes32 _contentUsageType_taoContent, bytes32 taoContentState_submitted, bytes32 taoContentState_pendingReview, bytes32 taoContentState_acceptedToTAO) = _getSettingVariables(); require (_taoContentState == taoContentState_submitted || _taoContentState == taoContentState_pendingReview || _taoContentState == taoContentState_acceptedToTAO); address _signatureAddress = AOLibrary.getUpdateTAOContentStateSignatureAddress(address(this), _contentId, _taoId, _taoContentState, _updateTAOContentStateV, _updateTAOContentStateR, _updateTAOContentStateS); Content storage _content = contents[contentIndex[_contentId]]; // Make sure that the signature address is one of content's TAO ID's Advocate/Listener/Speaker require (_signatureAddress == msg.sender && _nameTAOPosition.senderIsPosition(_signatureAddress, _content.taoId)); require (_content.contentUsageType == _contentUsageType_taoContent); _content.taoContentState = _taoContentState; _content.updateTAOContentStateV = _updateTAOContentStateV; _content.updateTAOContentStateR = _updateTAOContentStateR; _content.updateTAOContentStateS = _updateTAOContentStateS; emit UpdateTAOContentState(_contentId, _taoId, _signatureAddress, _taoContentState); } /***** INTERNAL METHODS *****/ /** * @dev Store the content information (content creation during staking) * @param _creator the address of the content creator * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _fileSize The size of the file * @param _contentUsageType The content usage type, i.e AO Content, Creative Commons, or T(AO) Content * @param _taoId The TAO (TAO) ID for this content (if this is a T(AO) Content) * @return the ID of the content */ function _storeContent(address _creator, string _baseChallenge, uint256 _fileSize, bytes32 _contentUsageType, address _taoId) internal returns (bytes32) { // Increment totalContents totalContents++; // Generate contentId bytes32 _contentId = keccak256(abi.encodePacked(this, _creator, totalContents)); Content storage _content = contents[totalContents]; // Make sure the node does't store the same content twice require (_content.creator == address(0)); (,,bytes32 contentUsageType_taoContent, bytes32 taoContentState_submitted,,) = _getSettingVariables(); _content.contentId = _contentId; _content.creator = _creator; _content.baseChallenge = _baseChallenge; _content.fileSize = _fileSize; _content.contentUsageType = _contentUsageType; // If this is a TAO Content if (_contentUsageType == contentUsageType_taoContent) { _content.taoContentState = taoContentState_submitted; _content.taoId = _taoId; } contentIndex[_contentId] = totalContents; emit StoreContent(_content.creator, _content.contentId, _content.fileSize, _content.contentUsageType); return _content.contentId; } /** * @dev Add the distribution node info that hosts the content * @param _host the address of the host * @param _stakeId The ID of the staked content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata */ function _hostContent(address _host, bytes32 _stakeId, string _encChallenge, string _contentDatKey, string _metadataDatKey) internal { require (bytes(_encChallenge).length > 0); require (bytes(_contentDatKey).length > 0); require (bytes(_metadataDatKey).length > 0); require (stakedContentIndex[_stakeId] > 0); // Increment totalContentHosts totalContentHosts++; // Generate contentId bytes32 _contentHostId = keccak256(abi.encodePacked(this, _host, _stakeId)); ContentHost storage _contentHost = contentHosts[totalContentHosts]; // Make sure the node doesn't host the same content twice require (_contentHost.host == address(0)); _contentHost.contentHostId = _contentHostId; _contentHost.stakeId = _stakeId; _contentHost.host = _host; _contentHost.encChallenge = _encChallenge; _contentHost.contentDatKey = _contentDatKey; _contentHost.metadataDatKey = _metadataDatKey; contentHostIndex[_contentHostId] = totalContentHosts; emit HostContent(_contentHost.host, _contentHost.contentHostId, _contentHost.stakeId, _contentHost.contentDatKey, _contentHost.metadataDatKey); } /** * @dev actual staking the content * @param _stakeOwner the address that stake the content * @param _contentId The ID of the content * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return the newly created staked content ID */ function _stakeContent(address _stakeOwner, bytes32 _contentId, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _profitPercentage) internal returns (bytes32) { // Increment totalStakedContents totalStakedContents++; // Generate stakeId bytes32 _stakeId = keccak256(abi.encodePacked(this, _stakeOwner, _contentId)); StakedContent storage _stakedContent = stakedContents[totalStakedContents]; // Make sure the node doesn't stake the same content twice require (_stakedContent.stakeOwner == address(0)); _stakedContent.stakeId = _stakeId; _stakedContent.contentId = _contentId; _stakedContent.stakeOwner = _stakeOwner; _stakedContent.profitPercentage = _profitPercentage; _stakedContent.active = true; _stakedContent.createdOnTimestamp = now; stakedContentIndex[_stakeId] = totalStakedContents; if (_denomination[0] != 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0)) { _stakedContent.networkAmount = _treasury.toBase(_networkIntegerAmount, _networkFractionAmount, _denomination); require (_baseAO.stakeFrom(_stakeOwner, _stakedContent.networkAmount)); } if (_primordialAmount > 0) { _stakedContent.primordialAmount = _primordialAmount; // Primordial Token is the base AO Token _stakedContent.primordialWeightedMultiplier = _baseAO.weightedMultiplierByAddress(_stakedContent.stakeOwner); require (_baseAO.stakePrimordialTokenFrom(_stakedContent.stakeOwner, _primordialAmount, _stakedContent.primordialWeightedMultiplier)); } emit StakeContent(_stakedContent.stakeOwner, _stakedContent.stakeId, _stakedContent.contentId, _stakedContent.networkAmount, _stakedContent.primordialAmount, _stakedContent.primordialWeightedMultiplier, _stakedContent.profitPercentage, _stakedContent.createdOnTimestamp); return _stakedContent.stakeId; } /** * @dev Get setting variables * @return contentUsageType_aoContent Content Usage Type = AO Content * @return contentUsageType_creativeCommons Content Usage Type = Creative Commons * @return contentUsageType_taoContent Content Usage Type = T(AO) Content * @return taoContentState_submitted TAO Content State = Submitted * @return taoContentState_pendingReview TAO Content State = Pending Review * @return taoContentState_acceptedToTAO TAO Content State = Accepted to TAO */ function _getSettingVariables() internal view returns (bytes32, bytes32, bytes32, bytes32, bytes32, bytes32) { (,,,bytes32 contentUsageType_aoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_aoContent'); (,,,bytes32 contentUsageType_creativeCommons,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_creativeCommons'); (,,,bytes32 contentUsageType_taoContent,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'contentUsageType_taoContent'); (,,,bytes32 taoContentState_submitted,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_submitted'); (,,,bytes32 taoContentState_pendingReview,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_pendingReview'); (,,,bytes32 taoContentState_acceptedToTAO,) = _aoSetting.getSettingValuesByTAOName(settingTAOId, 'taoContentState_acceptedToTAO'); return ( contentUsageType_aoContent, contentUsageType_creativeCommons, contentUsageType_taoContent, taoContentState_submitted, taoContentState_pendingReview, taoContentState_acceptedToTAO ); } /** * @dev Check whether or not the content is of AO Content Usage Type * @param _contentId The ID of the content * @return true if yes. false otherwise */ function _isAOContentUsageType(bytes32 _contentId) internal view returns (bool) { (bytes32 _contentUsageType_aoContent,,,,,) = _getSettingVariables(); return contents[contentIndex[_contentId]].contentUsageType == _contentUsageType_aoContent; } } /** * @title Name */ contract Name is TAO { /** * @dev Constructor function */ constructor (string _name, address _originId, string _datHash, string _database, string _keyValue, bytes32 _contentId, address _vaultAddress) TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public { // Creating Name typeId = 1; } } contract Logos is TAOCurrency { NameTAOPosition internal _nameTAOPosition; // Mapping of a Name ID to the amount of Logos positioned by others to itself // address is the address of nameId, not the eth public address mapping (address => uint256) public positionFromOthers; // Mapping of Name ID to other Name ID and the amount of Logos positioned by itself mapping (address => mapping(address => uint256)) public positionToOthers; // Mapping of a Name ID to the total amount of Logos positioned by itself to others mapping (address => uint256) public totalPositionToOthers; // Mapping of Name ID to it's advocated TAO ID and the amount of Logos earned mapping (address => mapping(address => uint256)) public advocatedTAOLogos; // Mapping of a Name ID to the total amount of Logos earned from advocated TAO mapping (address => uint256) public totalAdvocatedTAOLogos; // Event broadcasted to public when `from` address position `value` Logos to `to` event PositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `from` address unposition `value` Logos from `to` event UnpositionFrom(address indexed from, address indexed to, uint256 value); // Event broadcasted to public when `nameId` receives `amount` of Logos from advocating `taoId` event AddAdvocatedTAOLogos(address indexed nameId, address indexed taoId, uint256 amount); // Event broadcasted to public when Logos from advocating `taoId` is transferred from `fromNameId` to `toNameId` event TransferAdvocatedTAOLogos(address indexed fromNameId, address indexed toNameId, address indexed taoId, uint256 amount); /** * @dev Constructor function */ constructor(uint256 initialSupply, string tokenName, string tokenSymbol, address _nameTAOPositionAddress) TAOCurrency(initialSupply, tokenName, tokenSymbol) public { nameTAOPositionAddress = _nameTAOPositionAddress; _nameTAOPosition = NameTAOPosition(_nameTAOPositionAddress); } /** * @dev Check if `_taoId` is a TAO */ modifier isTAO(address _taoId) { require (AOLibrary.isTAO(_taoId)); _; } /** * @dev Check if `_nameId` is a Name */ modifier isName(address _nameId) { require (AOLibrary.isName(_nameId)); _; } /** * @dev Check if msg.sender is the current advocate of _id */ modifier onlyAdvocate(address _id) { require (_nameTAOPosition.senderIsAdvocate(msg.sender, _id)); _; } /***** PUBLIC METHODS *****/ /** * @dev Get the total sum of Logos for an address * @param _target The address to check * @return The total sum of Logos (own + positioned + advocated TAOs) */ function sumBalanceOf(address _target) public isNameOrTAO(_target) view returns (uint256) { return balanceOf[_target].add(positionFromOthers[_target]).add(totalAdvocatedTAOLogos[_target]); } /** * @dev `_from` Name position `_value` Logos onto `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to position * @return true on success */ function positionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't position Logos to itself require (balanceOf[_from].sub(totalPositionToOthers[_from]) >= _value); // should have enough balance to position require (positionFromOthers[_to].add(_value) >= positionFromOthers[_to]); // check for overflows uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].add(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].add(_value); positionFromOthers[_to] = positionFromOthers[_to].add(_value); emit PositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].sub(_value) == previousPositionToOthers); assert(positionFromOthers[_to].sub(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) <= previousAvailPositionBalance); return true; } /** * @dev `_from` Name unposition `_value` Logos from `_to` Name * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to unposition * @return true on success */ function unpositionFrom(address _from, address _to, uint256 _value) public isName(_from) isName(_to) onlyAdvocate(_from) returns (bool) { require (_from != _to); // Can't unposition Logos to itself require (positionToOthers[_from][_to] >= _value); uint256 previousPositionToOthers = totalPositionToOthers[_from]; uint256 previousPositionFromOthers = positionFromOthers[_to]; uint256 previousAvailPositionBalance = balanceOf[_from].sub(totalPositionToOthers[_from]); positionToOthers[_from][_to] = positionToOthers[_from][_to].sub(_value); totalPositionToOthers[_from] = totalPositionToOthers[_from].sub(_value); positionFromOthers[_to] = positionFromOthers[_to].sub(_value); emit UnpositionFrom(_from, _to, _value); assert(totalPositionToOthers[_from].add(_value) == previousPositionToOthers); assert(positionFromOthers[_to].add(_value) == previousPositionFromOthers); assert(balanceOf[_from].sub(totalPositionToOthers[_from]) >= previousAvailPositionBalance); return true; } /** * @dev Add `_amount` logos earned from advocating a TAO `_taoId` to its Advocate * @param _taoId The ID of the advocated TAO * @param _amount the amount to reward * @return true on success */ function addAdvocatedTAOLogos(address _taoId, uint256 _amount) public inWhitelist isTAO(_taoId) returns (bool) { require (_amount > 0); address _nameId = _nameTAOPosition.getAdvocate(_taoId); advocatedTAOLogos[_nameId][_taoId] = advocatedTAOLogos[_nameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_nameId] = totalAdvocatedTAOLogos[_nameId].add(_amount); emit AddAdvocatedTAOLogos(_nameId, _taoId, _amount); return true; } /** * @dev Transfer logos earned from advocating a TAO `_taoId` from `_fromNameId` to `_toNameId` * @param _fromNameId The ID of the Name that sends the Logos * @param _toNameId The ID of the Name that receives the Logos * @param _taoId The ID of the advocated TAO * @return true on success */ function transferAdvocatedTAOLogos(address _fromNameId, address _toNameId, address _taoId) public inWhitelist isName(_fromNameId) isName(_toNameId) isTAO(_taoId) returns (bool) { require (_nameTAOPosition.nameIsAdvocate(_toNameId, _taoId)); require (advocatedTAOLogos[_fromNameId][_taoId] > 0); require (totalAdvocatedTAOLogos[_fromNameId] >= advocatedTAOLogos[_fromNameId][_taoId]); uint256 _amount = advocatedTAOLogos[_fromNameId][_taoId]; advocatedTAOLogos[_fromNameId][_taoId] = advocatedTAOLogos[_fromNameId][_taoId].sub(_amount); totalAdvocatedTAOLogos[_fromNameId] = totalAdvocatedTAOLogos[_fromNameId].sub(_amount); advocatedTAOLogos[_toNameId][_taoId] = advocatedTAOLogos[_toNameId][_taoId].add(_amount); totalAdvocatedTAOLogos[_toNameId] = totalAdvocatedTAOLogos[_toNameId].add(_amount); emit TransferAdvocatedTAOLogos(_fromNameId, _toNameId, _taoId, _amount); return true; } } /** * @title AOLibrary */ library AOLibrary { using SafeMath for uint256; uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6; // 1000000 = 1 uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6; // 100% = 1000000 /** * @dev Check whether or not the given TAO ID is a TAO * @param _taoId The ID of the TAO * @return true if yes. false otherwise */ function isTAO(address _taoId) public view returns (bool) { return (_taoId != address(0) && bytes(TAO(_taoId).name()).length > 0 && TAO(_taoId).originId() != address(0) && TAO(_taoId).typeId() == 0); } /** * @dev Check whether or not the given Name ID is a Name * @param _nameId The ID of the Name * @return true if yes. false otherwise */ function isName(address _nameId) public view returns (bool) { return (_nameId != address(0) && bytes(TAO(_nameId).name()).length > 0 && Name(_nameId).originId() != address(0) && Name(_nameId).typeId() == 1); } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate * @param _sender The address to check * @param _theAO The AO address * @param _nameTAOPositionAddress The address of NameTAOPosition * @return true if yes, false otherwise */ function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { return (_sender == _theAO || ( (isTAO(_theAO) || isName(_theAO)) && _nameTAOPositionAddress != address(0) && NameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO) ) ); } /** * @dev Return the divisor used to correctly calculate percentage. * Percentage stored throughout AO contracts covers 4 decimals, * so 1% is 10000, 1.25% is 12500, etc */ function PERCENTAGE_DIVISOR() public pure returns (uint256) { return _PERCENTAGE_DIVISOR; } /** * @dev Return the divisor used to correctly calculate multiplier. * Multiplier stored throughout AO contracts covers 6 decimals, * so 1 is 1000000, 0.023 is 23000, etc */ function MULTIPLIER_DIVISOR() public pure returns (uint256) { return _MULTIPLIER_DIVISOR; } /** * @dev Check whether or not content creator can stake a content based on the provided params * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _baseChallenge The base challenge string (PUBLIC KEY) of the content * @param _encChallenge The encrypted challenge string (PUBLIC KEY) of the content unique to the host * @param _contentDatKey The dat key of the content * @param _metadataDatKey The dat key of the content's metadata * @param _fileSize The size of the file * @param _profitPercentage The percentage of profit the stake owner's media will charge * @return true if yes. false otherwise */ function canStake(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, string _baseChallenge, string _encChallenge, string _contentDatKey, string _metadataDatKey, uint256 _fileSize, uint256 _profitPercentage) public view returns (bool) { return ( bytes(_baseChallenge).length > 0 && bytes(_encChallenge).length > 0 && bytes(_contentDatKey).length > 0 && bytes(_metadataDatKey).length > 0 && _fileSize > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0 || _primordialAmount > 0) && _stakeAmountValid(_treasuryAddress, _networkIntegerAmount, _networkFractionAmount, _denomination, _primordialAmount, _fileSize) == true && _profitPercentage <= _PERCENTAGE_DIVISOR ); } /** * @dev Check whether or the requested unstake amount is valid * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @param _stakedNetworkAmount The current staked network token amount * @param _stakedPrimordialAmount The current staked primordial token amount * @param _stakedFileSize The file size of the staked content * @return true if can unstake, false otherwise */ function canUnstakePartial( address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _stakedNetworkAmount, uint256 _stakedPrimordialAmount, uint256 _stakedFileSize) public view returns (bool) { if ( (_denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && _stakedNetworkAmount < AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) ) || _stakedPrimordialAmount < _primordialAmount || ( _denomination.length > 0 && (_networkIntegerAmount > 0 || _networkFractionAmount > 0) && (_stakedNetworkAmount.sub(AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination)).add(_stakedPrimordialAmount.sub(_primordialAmount)) < _stakedFileSize) ) || ( _denomination.length == 0 && _networkIntegerAmount == 0 && _networkFractionAmount == 0 && _primordialAmount > 0 && _stakedPrimordialAmount.sub(_primordialAmount) < _stakedFileSize) ) { return false; } else { return true; } } /** * @dev Check whether the network token and/or primordial token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _isAOContentUsageType whether or not the content is of AO Content usage type * @param _fileSize The size of the file * @param _stakedAmount The total staked amount * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @param _primordialAmount The amount of primordial token * @return true when the amount is sufficient, false otherwise */ function canStakeExisting( address _treasuryAddress, bool _isAOContentUsageType, uint256 _fileSize, uint256 _stakedAmount, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount ) public view returns (bool) { if (_isAOContentUsageType) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) >= _fileSize; } else { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount).add(_stakedAmount) == _fileSize; } } /** * @dev Check whether the network token is adequate to pay for existing staked content * @param _treasuryAddress AO treasury contract address * @param _price The price of the content * @param _networkIntegerAmount The integer amount of the network token * @param _networkFractionAmount The fraction amount of the network token * @param _denomination The denomination of the the network token * @return true when the amount is sufficient, false otherwise */ function canBuy(address _treasuryAddress, uint256 _price, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination) public view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination) >= _price; } /** * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier` * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _currentPrimordialBalance Account's current primordial token balance * @param _additionalWeightedMultiplier The weighted multiplier to be added * @param _additionalPrimordialAmount The primordial token amount to be added * @return the new primordial weighted multiplier */ function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { if (_currentWeightedMultiplier > 0) { uint256 _totalWeightedTokens = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount)); uint256 _totalTokens = _currentPrimordialBalance.add(_additionalPrimordialAmount); return _totalWeightedTokens.div(_totalTokens); } else { return _additionalWeightedMultiplier; } } /** * @dev Return the address that signed the message when a node wants to become a host * @param _callingContractAddress the address of the calling contract * @param _message the message that was signed * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getBecomeHostSignatureAddress(address _callingContractAddress, string _message, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _message)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the address that signed the TAO content state update * @param _callingContractAddress the address of the calling contract * @param _contentId the ID of the content * @param _taoId the ID of the TAO * @param _taoContentState the TAO Content State value, i.e Submitted, Pending Review, or Accepted to TAO * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getUpdateTAOContentStateSignatureAddress(address _callingContractAddress, bytes32 _contentId, address _taoId, bytes32 _taoContentState, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _contentId, _taoId, _taoContentState)); return ecrecover(_hash, _v, _r, _s); } /** * @dev Return the staking and earning information of a stake ID * @param _contentAddress The address of AOContent * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getContentMetrics(address _contentAddress, address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier) = getStakingMetrics(_contentAddress, _stakeId); (uint256 totalStakeEarning, uint256 totalHostEarning, uint256 totalTheAOEarning) = getEarningMetrics(_earningAddress, _stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier, totalStakeEarning, totalHostEarning, totalTheAOEarning ); } /** * @dev Return the staking information of a stake ID * @param _contentAddress The address of AOContent * @param _stakeId The ID of the staked content * @return the network base token amount staked for this content * @return the primordial token amount staked for this content * @return the primordial weighted multiplier of the staked content */ function getStakingMetrics(address _contentAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { (,, uint256 networkAmount, uint256 primordialAmount, uint256 primordialWeightedMultiplier,,,) = AOContent(_contentAddress).stakedContentById(_stakeId); return ( networkAmount, primordialAmount, primordialWeightedMultiplier ); } /** * @dev Return the earning information of a stake ID * @param _earningAddress The address of AOEarning * @param _stakeId The ID of the staked content * @return the total earning from staking this content * @return the total earning from hosting this content * @return the total The AO earning of this content */ function getEarningMetrics(address _earningAddress, bytes32 _stakeId) public view returns (uint256, uint256, uint256) { return ( AOEarning(_earningAddress).totalStakedContentStakeEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentHostEarning(_stakeId), AOEarning(_earningAddress).totalStakedContentTheAOEarning(_stakeId) ); } /** * @dev Calculate the primordial token multiplier on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Multiplier = S * Ending Multiplier = E * To Purchase = P * Multiplier for next Lot of Amount = (1 - ((M + P/2) / T)) x (S-E) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting multiplier in (10 ** 6) * @param _endingMultiplier The ending multiplier in (10 ** 6) * @return The multiplier in (10 ** 6) */ function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * Multiplier = (1 - (temp / T)) x (S-E) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply multiplier with _MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR to account for 6 decimals * so, Multiplier = (_MULTIPLIER_DIVISOR/_MULTIPLIER_DIVISOR) * (1 - (temp / T)) * (S-E) * Multiplier = ((_MULTIPLIER_DIVISOR * (1 - (temp / T))) * (S-E)) / _MULTIPLIER_DIVISOR * Multiplier = ((_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E)) / _MULTIPLIER_DIVISOR * Take out the division by _MULTIPLIER_DIVISOR for now and include in later calculation * Multiplier = (_MULTIPLIER_DIVISOR - ((_MULTIPLIER_DIVISOR * temp) / T)) * (S-E) */ uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)); /** * Since _startingMultiplier and _endingMultiplier are in 6 decimals * Need to divide multiplier by _MULTIPLIER_DIVISOR */ return multiplier.div(_MULTIPLIER_DIVISOR); } else { return 0; } } /** * @dev Calculate the bonus percentage of network token on a given lot * Total Primordial Mintable = T * Total Primordial Minted = M * Starting Network Token Bonus Multiplier = Bs * Ending Network Token Bonus Multiplier = Be * To Purchase = P * AO Bonus % = B% = (1 - ((M + P/2) / T)) x (Bs-Be) * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) { /** * Let temp = M + (P/2) * B% = (1 - (temp / T)) x (Bs-Be) */ uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2)); /** * Multiply B% with _PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR to account for 6 decimals * so, B% = (_PERCENTAGE_DIVISOR/_PERCENTAGE_DIVISOR) * (1 - (temp / T)) * (Bs-Be) * B% = ((_PERCENTAGE_DIVISOR * (1 - (temp / T))) * (Bs-Be)) / _PERCENTAGE_DIVISOR * B% = ((_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be)) / _PERCENTAGE_DIVISOR * Take out the division by _PERCENTAGE_DIVISOR for now and include in later calculation * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) * But since Bs and Be are in 6 decimals, need to divide by _PERCENTAGE_DIVISOR * B% = (_PERCENTAGE_DIVISOR - ((_PERCENTAGE_DIVISOR * temp) / T)) * (Bs-Be) / _PERCENTAGE_DIVISOR */ uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR); return bonusPercentage; } else { return 0; } } /** * @dev Calculate the bonus amount of network token on a given lot * AO Bonus Amount = B% x P * * @param _purchaseAmount The amount of primordial token intended to be purchased * @param _totalPrimordialMintable Total Primordial token intable * @param _totalPrimordialMinted Total Primordial token minted so far * @param _startingMultiplier The starting Network token bonus multiplier * @param _endingMultiplier The ending Network token bonus multiplier * @return The bonus percentage */ function calculateNetworkTokenBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { uint256 bonusPercentage = calculateNetworkTokenBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier); /** * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR * when calculating the network token bonus amount */ uint256 networkTokenBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR); return networkTokenBonus; } /** * @dev Calculate the maximum amount of Primordial an account can burn * _primordialBalance = P * _currentWeightedMultiplier = M * _maximumMultiplier = S * _amountToBurn = B * B = ((S x P) - (P x M)) / S * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _maximumMultiplier The maximum multiplier of this account * @return The maximum burn amount */ function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier); } /** * @dev Calculate the new multiplier after burning primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToBurn = B * _newMultiplier = E * E = (P x M) / (P - B) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToBurn The amount of primordial token to burn * @return The new multiplier */ function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn)); } /** * @dev Calculate the new multiplier after converting network token to primordial token * _primordialBalance = P * _currentWeightedMultiplier = M * _amountToConvert = C * _newMultiplier = E * E = (P x M) / (P + C) * * @param _primordialBalance Account's primordial token balance * @param _currentWeightedMultiplier Account's current weighted multiplier * @param _amountToConvert The amount of network token to convert * @return The new multiplier */ function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert)); } /** * @dev Get TAO Currency Balances given a nameId * @param _nameId The ID of the Name * @param _logosAddress The address of Logos * @param _ethosAddress The address of Ethos * @param _pathosAddress The address of Pathos * @return sum Logos balance of the Name ID * @return Ethos balance of the Name ID * @return Pathos balance of the Name ID */ function getTAOCurrencyBalances( address _nameId, address _logosAddress, address _ethosAddress, address _pathosAddress ) public view returns (uint256, uint256, uint256) { return ( Logos(_logosAddress).sumBalanceOf(_nameId), TAOCurrency(_ethosAddress).balanceOf(_nameId), TAOCurrency(_pathosAddress).balanceOf(_nameId) ); } /** * @dev Return the address that signed the data and nonce when validating signature * @param _callingContractAddress the address of the calling contract * @param _data the data that was signed * @param _nonce The signed uint256 nonce * @param _v part of the signature * @param _r part of the signature * @param _s part of the signature * @return the address that signed the message */ function getValidateSignatureAddress(address _callingContractAddress, string _data, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) public pure returns (address) { bytes32 _hash = keccak256(abi.encodePacked(_callingContractAddress, _data, _nonce)); return ecrecover(_hash, _v, _r, _s); } /***** Internal Methods *****/ /** * @dev Check whether the network token and/or primordial token is adequate to pay for the filesize * @param _treasuryAddress AO treasury contract address * @param _networkIntegerAmount The integer amount of network token to stake * @param _networkFractionAmount The fraction amount of network token to stake * @param _denomination The denomination of the network token, i.e ao, kilo, mega, etc. * @param _primordialAmount The amount of primordial Token to stake * @param _fileSize The size of the file * @return true when the amount is sufficient, false otherwise */ function _stakeAmountValid(address _treasuryAddress, uint256 _networkIntegerAmount, uint256 _networkFractionAmount, bytes8 _denomination, uint256 _primordialAmount, uint256 _fileSize) internal view returns (bool) { return AOTreasury(_treasuryAddress).toBase(_networkIntegerAmount, _networkFractionAmount, _denomination).add(_primordialAmount) >= _fileSize; } } contract Epiphany is TheAO { string public what; string public when; string public why; string public who; address public where; string public aSign; string public logos; constructor() public { what = 'The AO'; when = 'January 6th, 2019 a.d, year 1 a.c. Epiphany. An appearance or manifestation especially of a divine being. An illuminating discovery, realization, or disclosure.'; why = 'To Hear, See, and Speak the Human inside Humanity.'; who = 'You. Set the world, Free. – Truth'; aSign = '08e2c4e1ccf3bccfb3b8eef14679b28442649a2a733960661210a0b00d9c93bf'; logos = '0920c6ab1848df83a332a21e8c9ec1a393e694c396b872aee053722d023e2a32'; } /** * @dev Checks if the calling contract address is The AO * OR * If The AO is set to a Name/TAO, then check if calling address is the Advocate */ modifier onlyTheAO { require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress)); _; } /***** The AO ONLY METHODS *****/ /** * @dev The AO set the NameTAOPosition Address * @param _nameTAOPositionAddress The address of NameTAOPosition */ function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO { require (_nameTAOPositionAddress != address(0)); nameTAOPositionAddress = _nameTAOPositionAddress; } /** * @dev Transfer ownership of The AO to new address * @param _theAO The new address to be transferred */ function transferOwnership(address _theAO) public onlyTheAO { require (_theAO != address(0)); theAO = _theAO; } /** * @dev Whitelist `_account` address to transact on behalf of others * @param _account The address to whitelist * @param _whitelist Either to whitelist or not */ function setWhitelist(address _account, bool _whitelist) public onlyTheAO { require (_account != address(0)); whitelist[_account] = _whitelist; } /** * @dev Set `where` value * @param _where The new value to be set */ function setWhere(address _where) public onlyTheAO { where = _where; } }
Set Listener for a Name/TAO _id The ID of the Name/TAO _newListenerId The new listener ID to be set/ If _id is a Name, then new Listener can only be a Name If _id is a TAO, then new Listener can be a TAO/Name
function setListener(address _id, address _newListenerId) public isNameOrTAO(_id) isNameOrTAO(_newListenerId) senderIsName() onlyAdvocate(_id) { bool _isName = false; if (AOLibrary.isName(_id)) { _isName = true; require (AOLibrary.isName(_newListenerId)); } Position storage _position = positions[_id]; address _currentListenerId = _position.listenerId; _position.listenerId = _newListenerId; if (_isName) { uint256 _nonce = _nameFactory.incrementNonce(_id); _nonce = _taoFactory.incrementNonce(_id); } emit SetListener(_id, _currentListenerId, _position.listenerId, _nonce); }
10,007,462
pragma solidity ^0.5.0; import "../../ethsnarks/contracts/Verifier.sol"; import "../../ethsnarks/contracts/SnarkUtils.sol"; contract HashPreimageExample { // Store the verification key uint256[14] private m_vk; uint256[] private m_gammaABC; // Construct instance of contract with a verification key constructor( uint256[14] memory in_vk, uint256[] memory in_gammaABC ) public { m_vk = in_vk; m_gammaABC = in_gammaABC; } function TestVerify ( uint256[14] memory in_vk, uint256[] memory vk_gammaABC, uint256[8] memory in_proof, uint256[] memory proof_inputs ) public view returns (bool) { return Verifier.Verify(in_vk, vk_gammaABC, in_proof, proof_inputs); } // Provide proof of knowledge of a hash preimage function Verify( uint256[] memory in_data, uint256[8] memory proof ) public view returns (bool) { // Public inputs for the zkSNARK circuit are hashed into a single input // A 256bit word is packed into two 253bit field elements uint256[] memory snark_input = new uint256[](2); SnarkUtils.PackWords(in_data, snark_input); // Validate the proof return Verifier.Verify( m_vk, m_gammaABC, proof, snark_input ); } }
Provide proof of knowledge of a hash preimage Public inputs for the zkSNARK circuit are hashed into a single input A 256bit word is packed into two 253bit field elements Validate the proof
function Verify( uint256[] memory in_data, uint256[8] memory proof ) public view returns (bool) { uint256[] memory snark_input = new uint256[](2); SnarkUtils.PackWords(in_data, snark_input); return Verifier.Verify( m_vk, m_gammaABC, proof, snark_input ); }
13,005,865
pragma solidity ^0.4.21; import "./open-zeppelin/math/SafeMath.sol"; import "./FundToken.sol"; import "./FundWallet.sol"; import "./FundToken.sol"; import "./Fund.sol"; // @title FundOperator // @dev This class is a suggestion for an implementation of a multi-sig operator of the Fund class // Every function of the Fund class can be called from here, therefore this class should be used as the owner of the Fund // The multi-sig verification implemented here puts a special focus by implementing two different sets of keys // used to access the operator. The hotAccounts represent the fund managers while the trustPartyAccounts represent // external trust accounts such as service providers, exchanged or known personalities. // The idea is that the normal management of the fund is possible by the fund managers, but if the fund managers // want to send fund to an unknown/untrusted wallet the transaction has to be confirmed by trust parties as well // This functionality offers a strong argument for trust and security because the fund managers cannot take of with the money // However this functionality can be disabled by setting the trust threshold to zero. // The multi-signature verification method is different from common patterns used by e.g. the Gnosis multi-sig wallet // All the signing happens off-chain which reduces gas cost drastically because only one transaction is needed to // authorize an action. // The signatures used here follow the ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 // Every function in this class requires signatures in the form of v, r, s. These signatures have to match the // purpose of the action. These parameters are not described for every function. // The format in which the signatures have to be given are an array which contains all signatures as follows: // | hotSignatures | trustPartySignatures (if necessary) | coldSignature (if necessary | // To see how to sign a transaction in the correct way check out the test cases in ../test/FundOperator.test.js // @author ScJa contract FundOperator { using SafeMath for uint256; // Enum which is used to uniquely identify every Action the operator can authorize. This is used for signatures. enum Action {AddFund, AddToken, AddTrustedWallets, AddColdWallet, EtherTransfer, TokenTransfer, PriceUpdate, Pause} // The fund which is managed by the operator Fund public fund; // Used for multi-signature purposes to uniquely identify every transaction uint256 public nonce; // Amount of signatures required from hot accounts for every transaction uint256 public hotThreshold; // Amount of signatures required for special actions which are not part of every day management actions uint256 public trustPartyThreshold; // Saves all hot accounts which manage the fund mapping(address => bool) public isHotAccount; // Saves all trust party accounts mapping(address => bool) public isTrustPartyAccount; // Saves all cold wallets used by the fund and the cold key used to protect the wallet. // Format: (Wallet storing funds) => (cold account required for access) mapping(address => address) public coldStorage; // Used for storing funds which can be quickly accessed mapping(address => bool) public isHotWallet; // Set of wallets which includes all wallets owned by the fund but can also contain other trusted such as exchanges mapping(address => bool) public isTrustedWallet; // The following five arrays are not used internally but added for public access to all addresses used address[] public hotAccounts; address[] public coldAccounts; address[] public trustPartyAccounts; FundWallet[] public hotWallets; FundWallet[] public coldWallets; // @dev Logs which fund is added for the operator to manage. Can only be emitted once // @param fund Address to fund managed event FundAdded(address fund); // @dev Logs the addition of the token added to the fund which represents the shares of the fund // @param token Address to the token added to the fund event FundTokenAuthorized(address token); // @dev Logs all hot wallets added to the operator // @param wallet Address added as a hot wallet event HotWalletAdded(address indexed wallet); // @dev Logs cold wallets added to the operator // @param wallet Address to the cold wallet // @param key Address to the cold key which is needed to unlock the wallet. event ColdWalletAdded(address indexed wallet, address indexed key); // @dev Logs when a trusted wallet is added. Both the addition of hot wallets and cold wallets will also emit this event. // @param wallet Address to the trusted wallet event TrustedWalletAdded(address indexed wallet); // @dev Logs whenever a cold wallet is accessed in a transfer // @param wallet Address of the cold wallet accessed event ColdWalletAccessed(address indexed wallet); // @dev Logs whenever a transfer of Ether is authorized // @param from Wallet from which the Ether was sent // @param to Address to which the Ether was sent // @param value Amount of wei sent event EtherTransferAuthorized(address indexed from, address indexed to, uint256 value); // @dev Logs the authorization of a transfer of tokens // @param token The address to the ERC20 compatible token of which tokens are moved // @param from Address from which tokens were sent // @param to Address to which the tokens were sent // @param value Amount of tokens sent event TokenTransferAuthorized(address indexed token, address indexed from, address indexed to, uint256 value); // @dev Logs the authorization of a price update // @param numerator The new numerator for the price // @param denominator The new denominator for the price event PriceUpdateAuthorized(uint256 numerator, uint256 denominator); // @dev Logs the authorization of the pausing of the fund event PauseAuthorized(); // @dev Logs the authorization of the unpausing of the fund event UnpauseAuthorized(); // @dev Verifies the operator already has a fund added modifier hasFund() { require(address(fund) != 0); _; } // @dev Verifies an address is not the zero address // @param _address modifier notNull(address _address) { require(_address != 0); _; } // @dev Constructor which adds all hot accounts and trust party accounts to the fund. No more accounts of this // type can be added at a later point. To change them redeploy a new version of all components. // Does not allow for any duplicates. No trustparty accounts have to be added. // @param _hotTreshold Amount of signatures from hot accounts needed to confirm every action in this class // @param _trustPartyThreshold Amount of signatures needed from trust parties for extraordinary actions // @param _hotAccounts Array of addresses of hot accounts // @param _trustPartyAccounts Array of addresses of trust party accounts function FundOperator (uint256 _hotThreshold, uint256 _trustPartyThreshold, address[] _hotAccounts, address[] _trustPartyAccounts) public { require(_hotAccounts.length <= 10 && _hotAccounts.length != 0); require(_trustPartyAccounts.length <= 10); require(_hotThreshold <= _hotAccounts.length && _hotThreshold != 0); require(_trustPartyThreshold <= _trustPartyAccounts.length); for (uint256 i = 0; i < _hotAccounts.length; i++) { require(!isHotAccount[_hotAccounts[i]] && _hotAccounts[i] != 0); isHotAccount[_hotAccounts[i]] = true; } for (i = 0; i < _trustPartyAccounts.length; i++) { require(!isHotAccount[_trustPartyAccounts[i]]); require(!isTrustPartyAccount[_trustPartyAccounts[i]] && _trustPartyAccounts[i] != 0); isTrustPartyAccount[_trustPartyAccounts[i]] = true; } hotThreshold = _hotThreshold; trustPartyThreshold = _trustPartyThreshold; hotAccounts = _hotAccounts; trustPartyAccounts = _trustPartyAccounts; } // @dev Adds the fund to be managed to the operator // Requires trust party to sign // @param _fund Address to the fund to be added/managed function addFund(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, Fund _fund) external notNull(_fund) { require(address(fund) == 0); bytes32 preHash = keccak256(this, uint256(Action.AddFund), _fund, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); _verifyTrustPartyAction(_sigV, _sigR, _sigS, preHash); fund = _fund; isHotWallet[fund] = true; isTrustedWallet[fund] = true; emit FundAdded(fund); nonce = nonce.add(1); } // @dev Adds the token to the fund managed by the operator // Requires trust party to sign // @param _token Address of the token to be added function addToken(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, FundToken _token) external hasFund { bytes32 preHash = keccak256(this, uint256(Action.AddToken), _token, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); _verifyTrustPartyAction(_sigV, _sigR, _sigS, preHash); emit FundTokenAuthorized(_token); nonce = nonce.add(1); fund.addToken(_token); } // @dev Adds an array of trusted wallets or hot wallets. Hot wallets are hot and trusted // Requires trust party to sign // @param _wallets Array of wallets to add to the fund // @param _hot Says whether the wallets added should be both hot and trusted or only trusted function addTrustedWallets(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, FundWallet[] _wallets, bool _hot) external hasFund { bytes32 preHash = keccak256(this, uint256(Action.AddTrustedWallets), _wallets, _hot, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); _verifyTrustPartyAction(_sigV, _sigR, _sigS, preHash); for (uint256 i = 0; i < _wallets.length; i++) { require(!isTrustedWallet[_wallets[i]]); require(_wallets[i].owner() == address(fund)); isTrustedWallet[_wallets[i]] = true; emit TrustedWalletAdded(_wallets[i]); if (_hot) { isHotWallet[_wallets[i]] = true; hotWallets.push(_wallets[i]); emit HotWalletAdded(_wallets[i]); } } nonce = nonce.add(1); } // @dev Adds a single cold wallet with the corresponding cold key to the fund. // Requires trsut party to sign // @param _wallet Address to the cold wallet to add // @param _key Address to the cold account needed to access the cold wallet at a later point function addColdWallet(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, FundWallet _wallet, address _key) external notNull(_wallet) { require(!isTrustedWallet[_wallet]); require(_wallet.owner() == address(fund)); bytes32 preHash = keccak256(this, uint256(Action.AddColdWallet), _wallet, _key, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); _verifyTrustPartyAction(_sigV, _sigR, _sigS, preHash); isTrustedWallet[_wallet] = true; coldWallets.push(_wallet); coldStorage[_wallet] = _key; coldAccounts.push(_key); _verifyColdStorageAccess(_sigV[_sigV.length - 1], _sigR[_sigR.length - 1], _sigS[_sigS.length - 1], preHash, _wallet); emit ColdWalletAdded(_wallet, _key); emit TrustedWalletAdded(_wallet); nonce = nonce.add(1); } // @dev Function is used internally to verify access whenever a transfer from a cold wallet is initiated // See test cases for an example on how the signatures can be generated correctly in Javascript // @param _preHash Hash to check the signatures against // @param _wallet Cold wallet to be accessed function _verifyColdStorageAccess(uint8 _sigV, bytes32 _sigR, bytes32 _sigS, bytes32 _preHash, address _wallet) internal { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 txHash = keccak256(prefix, _preHash); address recovered = ecrecover(txHash, _sigV, _sigR, _sigS); require(coldStorage[_wallet] == recovered); emit ColdWalletAccessed(_wallet); } // @dev Internal function to verify every action taken in this class. Check the signatures given against the // preHash to check if the all the signatures are correct. The hot signatures have to be the first elements of the // signature arrays. // See test cases for an example on how the signatures can be generated correctly in Javascript // @param _preHash Hash to check the signatures against function _verifyHotAction(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, bytes32 _preHash) view internal { require(_sigV.length >= hotThreshold); require(_sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 txHash = keccak256(prefix, _preHash); // Loop is ensuring that there are no duplicates by checking the addresses are strictly increasing address lastAdd = 0; for (uint256 i = 0; i < hotThreshold; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd); require(isHotAccount[recovered]); lastAdd = recovered; } } // @dev Internal function to verify all actions which need special confirmation from the trust parties. // The trust party signatures have to be appended after the hot signatures. // See test cases for an example on how the signatures can be generated correctly in Javascript // @param _preHash Hash to check the signatures against function _verifyTrustPartyAction(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, bytes32 _preHash) view internal { require(_sigV.length >= hotThreshold.add(trustPartyThreshold)); require(_sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 txHash = keccak256(prefix, _preHash); // Loop is ensuring that there are no duplicates by checking the addresses are strictly increasing address lastAdd = 0; for (uint256 i = hotThreshold; i < hotThreshold + trustPartyThreshold; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd); require(isTrustPartyAccount[recovered]); lastAdd = recovered; } } // @dev Internal function called for both ether and token transfer in order to reduce duplicate code // Check whether the address to send from is a wallet of the fund. // Depending on if it is sending from a cold wallet or sending to an untrusted wallet different signatures are verified // @param _preHash Hash to check signatures against // @param _from Wallet to transfer funds from // @param _to Wallet to transfer funds to // @param _value Amount of either wei or tokens to send function _verifyTransfer(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, bytes32 _preHash, FundWallet _from, address _to, uint256 _value) internal { require(isHotWallet[_from] || coldStorage[_from] != 0); require(_value > 0); _verifyHotAction(_sigV, _sigR, _sigS, _preHash); if (coldStorage[_from] != 0) { // Double length check for safety require(_sigR.length == _sigS.length && _sigR.length == _sigV.length); uint256 coldKeyPos = _sigV.length - 1; _verifyColdStorageAccess(_sigV[coldKeyPos], _sigR[coldKeyPos], _sigS[coldKeyPos], _preHash, _from); } if (!isTrustedWallet[_to]) { _verifyTrustPartyAction(_sigV, _sigR, _sigS, _preHash); } nonce = nonce.add(1); } // @dev Authorizes an Ether transfer between two wallets // If sending to an untrusted wallet requires trust party to sign // @param _from Address from which the Ether is sent from // @param _to Address to which the Ether is sent // @param _value Amount of wei sent function requestEtherTransfer(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, FundWallet _from, address _to, uint256 _value) external hasFund { bytes32 preHash = keccak256(this, uint256(Action.EtherTransfer), _from, _to, _value, nonce); _verifyTransfer(_sigV, _sigR, _sigS, preHash, _from, _to, _value); // Triggers external call fund.moveEther(FundWallet(_from), _to, _value); emit EtherTransferAuthorized(_from, _to, _value); } // @dev Authorizes a token transfer between two wallets // If sending to an untrusted wallet requires trust party to sign // @param _token ERC20-compatible token of which tokens are moved // @param _from Address from which tokens are sent from // @param _to Address to which the tokens are sent to // @param _value Amount of tokens sent function requestTokenTransfer(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, ERC20 _token, FundWallet _from, address _to, uint256 _value) external hasFund { bytes32 preHash = keccak256(this, int256(Action.TokenTransfer), _token, _from, _to, _value, nonce); _verifyTransfer(_sigV, _sigR, _sigS, preHash, _from, _to, _value); // Triggers external call fund.moveTokens(_token, _from, _to, _value); emit TokenTransferAuthorized(address(_token), _from, _to, _value); } // @dev Authorizes the fund to update the price for a token/share // @param _numerator Numerator for the new price // @param _denominator Denominator for the new price function requestPriceUpdate(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, uint256 _numerator, uint256 _denominator) external hasFund { // Double check to fail fast require(_numerator != 0 && _denominator != 0); bytes32 preHash = keccak256(this, uint256(Action.PriceUpdate), _numerator, _denominator, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); nonce = nonce.add(1); fund.updatePrice(_numerator, _denominator); emit PriceUpdateAuthorized(_numerator, _denominator); } // @dev Authorizes the pausing or unpausing of the fund // @param _pause If true the fund will be paused, if false the fund will be unpaused. function requestPause(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, bool _pause) external hasFund { bytes32 preHash = keccak256(this, uint256(Action.Pause), _pause, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); nonce = nonce.add(1); if (_pause) { fund.pause(); emit PauseAuthorized(); } else { fund.unpause(); emit UnpauseAuthorized(); } } }
Adds the fund to be managed to the operator Requires trust party to sign _fund Address to the fund to be added/managed
function addFund(uint8[] _sigV, bytes32[] _sigR, bytes32[] _sigS, Fund _fund) external notNull(_fund) { require(address(fund) == 0); bytes32 preHash = keccak256(this, uint256(Action.AddFund), _fund, nonce); _verifyHotAction(_sigV, _sigR, _sigS, preHash); _verifyTrustPartyAction(_sigV, _sigR, _sigS, preHash); fund = _fund; isHotWallet[fund] = true; isTrustedWallet[fund] = true; emit FundAdded(fund); nonce = nonce.add(1); }
12,681,098
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.1; import "./interfaces/ITransactionManager.sol"; import "./lib/LibAsset.sol"; import "./lib/LibERC20.sol"; import "./interpreters/MultisendInterpreter.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract TransactionManager is ReentrancyGuard, ITransactionManager { /// @dev Mapping of router to balance specific to asset mapping(address => mapping(address => uint256)) public routerBalances; /// @dev Maping of user address to blocks where active transfers /// were created. mapping(address => uint256[]) public activeTransactionBlocks; /// @dev Mapping of hash of `TransactionData` to status of a transaction mapping(bytes32 => TransactionStatus) public transactionStatus; /// @dev The chain id of the contract, is passed in to avoid any evm issues uint256 public immutable chainId; /// @dev Address of the deployed multisending interpreter contract address public immutable iMultisend; uint256 public constant MIN_TIMEOUT = 24 hours; constructor(address _iMultisend, uint256 _chainId) { iMultisend = _iMultisend; chainId = _chainId; } /// @param amount The amount of liquidity to add for the router /// @param assetId The address (or `address(0)` if native asset) of the /// asset you're adding liquidity for function addLiquidity(uint256 amount, address assetId) external payable override nonReentrant { // Validate correct amounts are transferred if (LibAsset.isEther(assetId)) { require(msg.value == amount, "addLiquidity: VALUE_MISMATCH"); } else { require(msg.value == 0, "addLiquidity: ETH_WITH_ERC_TRANSFER"); require(LibERC20.transferFrom(assetId, msg.sender, address(this), amount), "addLiquidity: ERC20_TRANSFER_FAILED"); } // Update the router balances routerBalances[msg.sender][assetId] += amount; // Emit event emit LiquidityAdded(msg.sender, assetId, amount); } function removeLiquidity( uint256 amount, address assetId, address payable recipient ) external override nonReentrant { // Check that the amount can be deducted for the router // TODO is this check worth the extra gas? require(routerBalances[msg.sender][assetId] >= amount, "removeLiquidity: INSUFFICIENT_FUNDS"); // Update router balances routerBalances[msg.sender][assetId] -= amount; // Transfer from contract to router require(LibAsset.transferAsset(assetId, recipient, amount), "removeLiquidity: TRANSFER_FAILED"); // Emit event emit LiquidityRemoved(msg.sender, assetId, amount, recipient); } function prepare( InvariantTransactionData calldata _txData, uint256 amount, uint256 expiry, bytes calldata encodedBid, bytes calldata bidSignature ) external payable override nonReentrant returns (TransactionData memory) { // Make sure the expiry is greater than min require((expiry - block.timestamp) >= MIN_TIMEOUT, "prepare: TIMEOUT_TOO_LOW"); // Make sure the chains are different require(_txData.sendingChainId != _txData.receivingChainId, "prepare: SAME_CHAINIDS"); // Make sure the chains are relevant require(_txData.sendingChainId == chainId || _txData.receivingChainId == chainId, "prepare: INVALID_CHAINIDS"); // Sanity check: valid fallback require(_txData.receivingAddress != address(0), "prepare: INVALID_RECEIVING_ADDRESS"); // Make sure the hash is not a duplicate TransactionData memory txData = TransactionData({ user: _txData.user, router: _txData.router, sendingAssetId: _txData.sendingAssetId, receivingAssetId: _txData.receivingAssetId, receivingAddress: _txData.receivingAddress, callData: _txData.callData, transactionId: _txData.transactionId, amount: amount, expiry: expiry, blockNumber: block.number, sendingChainId: _txData.sendingChainId, receivingChainId: _txData.receivingChainId }); bytes32 digest = keccak256(abi.encode(txData)); require(transactionStatus[digest] == TransactionStatus.Empty, "prepare: DIGEST_EXISTS"); // Store the transaction variants transactionStatus[digest] = TransactionStatus.Pending; // Store active blocks activeTransactionBlocks[txData.user].push(block.number); // First determine if this is sender side or receiver side if (txData.sendingChainId == chainId) { // This is sender side prepare // Validate correct amounts and transfer if (LibAsset.isEther(txData.sendingAssetId)) { require(msg.value == txData.amount, "prepare: VALUE_MISMATCH"); } else { require(msg.value == 0, "prepare: ETH_WITH_ERC_TRANSFER"); require( LibERC20.transferFrom(txData.sendingAssetId, msg.sender, address(this), txData.amount), "prepare: ERC20_TRANSFER_FAILED" ); } } else { // This is receiver side prepare // Check that the caller is the router require(msg.sender == txData.router, "prepare: ROUTER_MISMATCH"); require(msg.value == 0, "prepare: ETH_WITH_ROUTER_PREPARE"); // Check that router has liquidity // TODO do we need explicit check vs implicit from safemath below? require( routerBalances[txData.router][txData.receivingAssetId] >= txData.amount, "prepare: INSUFFICIENT_LIQUIDITY" ); // NOTE: Timeout and amounts should have been decremented offchain // NOTE: after some consideration, it feels like it's better to leave amount/fee // validation *outside* the contracts as we likely want the logic to be flexible // Pull funds from router balance (use msg.sender here to mitigate 3rd party attack) // What would happen if some router tried to swoop in and steal another router's spot? // - 3rd party router could EITHER use original txData or replace txData.router with itself // - if original txData, 3rd party router would basically be paying for original router // - if relaced router address, user sig on digest would not unlock sender side routerBalances[txData.router][txData.receivingAssetId] -= txData.amount; } // Emit event emit TransactionPrepared(txData, msg.sender, encodedBid, bidSignature); return txData; } function fulfill( TransactionData calldata txData, uint256 relayerFee, bytes calldata signature // signature on fee + digest ) external override nonReentrant returns (TransactionData memory) { // Make sure params match against stored data // Also checks that there is an active transfer here // Also checks that sender or receiver chainID is this chainId (bc we // checked it previously) bytes32 digest = keccak256(abi.encode(txData)); require(transactionStatus[digest] == TransactionStatus.Pending, "fulfill: INVALID_TX_STATUS"); require(txData.expiry > block.timestamp, "fulfill: EXPIRED"); // Validate signature require(recoverFulfillSignature(txData, relayerFee, signature) == txData.user, "fulfill: INVALID_SIGNATURE"); // Sanity check: fee < amount // TODO: Do we need this check? Safemath would catch it below require(relayerFee < txData.amount, "fulfill: INVALID_RELAYER_FEE"); // Mark transaction as fulfilled transactionStatus[digest] = TransactionStatus.Completed; // Remove active blocks removeUserActiveBlocks(txData.user, txData.blockNumber); // TODO: user cant accidentally fulfill sender if (txData.sendingChainId == chainId) { // Complete tx to router // NOTE: there is no fee taken on the sending side for the relayer routerBalances[txData.router][txData.sendingAssetId] += txData.amount; } else { // Complete tx to user // Get the amount to send uint256 toSend = txData.amount - relayerFee; // Send the relayer the fee if (relayerFee > 0) { require( LibAsset.transferAsset(txData.receivingAssetId, payable(msg.sender), relayerFee), "fulfill: FEE_TRANSFER_FAILED" ); } if (keccak256(txData.callData) == keccak256(new bytes(0))) { // No external calls, send directly to receiving address require( LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend), "fulfill: TRANSFER_FAILED" ); } else { // Handle external calls with a fallback to the receiving // address // TODO: This would allow us to execute an arbitrary transfer to drain the contracts // We'll need to change this to use vector pattern with *explicit* amount. // If it is a token, approve the amount to the interpreter try MultisendInterpreter(iMultisend).execute{value: LibAsset.isEther(txData.receivingAssetId) ? toSend : 0}( txData.receivingAssetId, toSend, txData.callData ) {} catch { require( LibAsset.transferAsset(txData.receivingAssetId, payable(txData.receivingAddress), toSend), "fulfill: TRANSFER_FAILED" ); } } } // Emit event emit TransactionFulfilled(txData, relayerFee, signature, msg.sender); return txData; } // Tx can be "collaboratively" cancelled by the receiver at any time and by the sender after expiry function cancel(TransactionData calldata txData, bytes calldata signature) external override nonReentrant returns (TransactionData memory) { // Make sure params match against stored data // Also checks that there is an active transfer here // Also checks that sender or receiver chainID is this chainId (bc we checked it previously) bytes32 digest = keccak256(abi.encode(txData)); require(transactionStatus[digest] == TransactionStatus.Pending, "cancel: INVALID_TX_STATUS"); // Mark transaction as complete transactionStatus[digest] = TransactionStatus.Completed; if (txData.sendingChainId == chainId) { // Sender side --> funds go back to user if (txData.expiry >= block.timestamp) { // Timeout has not expired and tx may only be cancelled by router require(msg.sender == txData.router, "cancel: ROUTER_MUST_CANCEL"); } // Return to user require( LibAsset.transferAsset(txData.sendingAssetId, payable(txData.user), txData.amount), "cancel: TRANSFER_FAILED" ); } else { // Receiver side --> funds go back to router if (txData.expiry >= block.timestamp) { // Timeout has not expired and tx may only be cancelled by user // Validate signature require(recoverCancelSignature(txData, signature) == txData.user, "cancel: INVALID_SIGNATURE"); } // Return to router routerBalances[txData.router][txData.receivingAssetId] += txData.amount; } // Remove active blocks removeUserActiveBlocks(txData.user, txData.blockNumber); // Emit event emit TransactionCancelled(txData, msg.sender); // Return return txData; } // Private functions function removeUserActiveBlocks(address user, uint256 preparedBlock) internal { // Remove active blocks uint256 newLength = activeTransactionBlocks[user].length - 1; uint256[] memory updated = new uint256[](newLength); bool removed = false; uint256 updatedIdx = 0; for (uint256 i; i < newLength + 1; i++) { // Handle case where there could be more than one tx added in a block // And only one should be removed if (!removed && activeTransactionBlocks[user][i] == preparedBlock) { removed = true; continue; } updated[updatedIdx] = activeTransactionBlocks[user][i]; updatedIdx++; } activeTransactionBlocks[user] = updated; } function recoverFulfillSignature( TransactionData calldata txData, uint256 relayerFee, bytes calldata signature ) internal pure returns (address) { // Create the digest bytes32 invariantDigest = hashInvariantTransactionData(txData); // Create the signed payload SignedFulfillData memory payload = SignedFulfillData({invariantDigest: invariantDigest, relayerFee: relayerFee}); bytes32 signed = keccak256(abi.encode(payload)); // Recover return ECDSA.recover(ECDSA.toEthSignedMessageHash(signed), signature); } function recoverCancelSignature(TransactionData calldata txData, bytes calldata signature) internal pure returns (address) { // Create the digest bytes32 invariantDigest = hashInvariantTransactionData(txData); // Create the signed payload SignedCancelData memory payload = SignedCancelData({invariantDigest: invariantDigest, cancel: "cancel"}); // Recover bytes32 signed = keccak256(abi.encode(payload)); // Recover return ECDSA.recover(ECDSA.toEthSignedMessageHash(signed), signature); } function hashInvariantTransactionData(TransactionData calldata txData) internal pure returns (bytes32) { InvariantTransactionData memory invariant = InvariantTransactionData({ user: txData.user, router: txData.router, sendingAssetId: txData.sendingAssetId, receivingAssetId: txData.receivingAssetId, receivingAddress: txData.receivingAddress, sendingChainId: txData.sendingChainId, receivingChainId: txData.receivingChainId, callData: txData.callData, transactionId: txData.transactionId }); return keccak256(abi.encode(invariant)); } }
amount The amount of liquidity to add for the router assetId The address (or `address(0)` if native asset) of the asset you're adding liquidity for Validate correct amounts are transferred
function addLiquidity(uint256 amount, address assetId) external payable override nonReentrant { if (LibAsset.isEther(assetId)) { require(msg.value == amount, "addLiquidity: VALUE_MISMATCH"); require(msg.value == 0, "addLiquidity: ETH_WITH_ERC_TRANSFER"); require(LibERC20.transferFrom(assetId, msg.sender, address(this), amount), "addLiquidity: ERC20_TRANSFER_FAILED"); } }
13,017,910
/** * ██╗░░██╗░█████╗░██████╗░██╗░░░░░░██████╗░░█████╗░██╗░░░░░░█████╗░██╗░░██╗██╗░░░██╗ * ██║░░██║██╔══██╗██╔══██╗██║░░░░░██╔════╝░██╔══██╗██║░░░░░██╔══██╗╚██╗██╔╝╚██╗░██╔╝ * ███████║██║░░██║██║░░██║██║░░░░░██║░░██╗░███████║██║░░░░░███████║░╚███╔╝░░╚████╔╝░ * ██╔══██║██║░░██║██║░░██║██║░░░░░██║░░╚██╗██╔══██║██║░░░░░██╔══██║░██╔██╗░░░╚██╔╝░░ * ██║░░██║╚█████╔╝██████╔╝███████╗╚██████╔╝██║░░██║███████╗██║░░██║██╔╝╚██╗░░░██║░░░ * ╚═╝░░╚═╝░╚════╝░╚═════╝░╚══════╝░╚═════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝░░░╚═╝░░░ * * HodlGalaxy is a coming fairlaunch ESC Token, with the best suited Tokenomics for the current ESC era, rewarding 7% in $WETH. * HodlGalaxy's use-case is to become a 3rd party liquidity platform which allows holders of $HGALAXY to create their own liquidity/farming pools for their own token. * We also feature a professional Doxxed Team! HodlGalaxy is here to stay and we invite you to join us. * * During the FairLaunch of HodlGalaxy a max buy of 1.5 ETH will be set for the first 1 minute to stop long holders being able to dump large amounts of tokens. * The contract address will be released for everyone at the same time to stop bots from ruining the launch. * * Token Tax Breakdown: 7% $WETH Rewards, 4% Marketing Fee, 2% Liquidity. * * Website https://HodlGalaxy.com * Telegram https://t.me/HodlGalaxy */ // SPDX-License-Identifier: MIT // File: contracts/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: contracts/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: contracts/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: contracts/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) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; bool public inCooldown = false; uint256 public maxTxAmount = 1000000000000000 * 1000000000000000000; mapping (address => bool) private _isExcluded; mapping (address => uint256) private _tranzCount; /** * @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 { //, uint256 totalSupply _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"); if ((inCooldown == true) && !(_isExcluded[sender] || _isExcluded[recipient])) { require(_tranzCount[sender] == 0, "inCooldown: only one tranzaction allowed"); require(amount < maxTxAmount, "inCooldown: Transfer amount exceeds the maxTxAmount"); _tranzCount[sender]++; } _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 _add(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: add 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 { } function setInCooldown(bool _inCooldown) public onlyOwner { inCooldown = _inCooldown; } function setMaxTxAmount(uint256 _maxTxAmount) public onlyOwner { maxTxAmount = _maxTxAmount; } function isExcluded(address account) public view returns(bool) { return _isExcluded[account]; } function setIsExcluded(address account) public onlyOwner { _isExcluded[account] = true; } function tranzCount(address account) public view returns(uint256) { return _tranzCount[account]; } } // File: contracts/MyToken.sol pragma solidity >=0.6.12; contract HodlGalaxy is Context, ERC20 { using SafeMath for uint256; using Address for address; event Burn(address indexed _sender, uint256 amount); event Add(address indexed account, uint256 amount); uint tokenTotalSupply = 100000000; constructor() public ERC20("HodlGalaxy", "HGALAXY") { _add(msg.sender, tokenTotalSupply * (10 ** uint256(decimals()))); } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); emit Burn(_msgSender(), amount); } function add(address account, uint256 amount) public onlyOwner { _add(account, amount); emit Add(account, amount); } }
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; }
8,309
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
(Free functions cannot have visibility.) solhint-disable-next-line func-visibility
function setFreeMemoryPointer(MemoryPointer mPtr) pure { FreeMemoryPPtr.write(mPtr); }
3,218,162
./partial_match/56/0x56521583cBA15393102D0a33A09FfB0d9A0adB05/sources/STGBNBLPPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'STGBNBLPPool: Cannot stake 0'); super.stake(amount); emit Staked(msg.sender, amount); }
11,141,171
./partial_match/42220/0x1EC3366D384ee7996F2F70B67A65C5d54Ce96040/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/identity/Attestations.sol
Revokes an account for an identifier. identifier The identifier for which to revoke. index The index of the account in the accounts array./
function revoke(bytes32 identifier, uint256 index) external { uint256 numAccounts = identifiers[identifier].accounts.length; require(index < numAccounts, "Index is invalid"); require( msg.sender == identifiers[identifier].accounts[index], "Index does not match msg.sender" ); uint256 newNumAccounts = numAccounts.sub(1); if (index != newNumAccounts) { identifiers[identifier].accounts[index] = identifiers[identifier].accounts[newNumAccounts]; } identifiers[identifier].accounts[newNumAccounts] = address(0x0); identifiers[identifier].accounts.length = identifiers[identifier].accounts.length.sub(1); }
3,499,736
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "../interfaces/IOracleMaster.sol"; import "../interfaces/ILido.sol"; import "../interfaces/IAuthManager.sol"; import "../interfaces/IRelayEncoder.sol"; import "../interfaces/IXcmTransactor.sol"; import "../interfaces/IController.sol"; import "../interfaces/Types.sol"; import "./utils/LedgerUtils.sol"; import "./utils/ReportUtils.sol"; contract Ledger { using LedgerUtils for Types.OracleData; using SafeCast for uint256; event DownwardComplete(uint128 amount); event UpwardComplete(uint128 amount); event Rewards(uint128 amount, uint128 balance); event Slash(uint128 amount, uint128 balance); // Lido main contract address ILido public LIDO; // vKSM precompile IERC20 internal VKSM; // controller for sending xcm messages to relay chain IController internal CONTROLLER; // ledger stash account bytes32 public stashAccount; // ledger controller account bytes32 public controllerAccount; // Stash balance that includes locked (bounded in stake) and free to transfer balance uint128 public totalBalance; // Locked, or bonded in stake module, balance uint128 public lockedBalance; // last reported active ledger balance uint128 public activeBalance; // last reported ledger status Types.LedgerStatus public status; // Cached stash balance. Need to calculate rewards between successfull up/down transfers uint128 public cachedTotalBalance; // Pending transfers uint128 public transferUpwardBalance; uint128 public transferDownwardBalance; // Pending bonding uint128 public pendingBonds; // Minimal allowed balance to being a nominator uint128 public MIN_NOMINATOR_BALANCE; // Minimal allowable active balance uint128 public MINIMUM_BALANCE; // Ledger manager role bytes32 internal constant ROLE_LEDGER_MANAGER = keccak256("ROLE_LEDGER_MANAGER"); // Maximum allowable unlocking chunks amount uint256 public MAX_UNLOCKING_CHUNKS; // Allows function calls only from LIDO modifier onlyLido() { require(msg.sender == address(LIDO), "LEDGER: NOT_LIDO"); _; } // Allows function calls only from Oracle modifier onlyOracle() { address oracle = IOracleMaster(ILido(LIDO).ORACLE_MASTER()).getOracle(address(this)); require(msg.sender == oracle, "LEDGER: NOT_ORACLE"); _; } // Allows function calls only from member with specific role modifier auth(bytes32 role) { require(IAuthManager(ILido(LIDO).AUTH_MANAGER()).has(role, msg.sender), "LEDGER: UNAUTHOROZED"); _; } /** * @notice Initialize ledger contract. * @param _stashAccount - stash account id * @param _controllerAccount - controller account id * @param _vKSM - vKSM contract address * @param _controller - xcmTransactor(relaychain calls relayer) contract address * @param _minNominatorBalance - minimal allowed nominator balance * @param _lido - LIDO address * @param _minimumBalance - minimal allowed active balance for ledger * @param _maxUnlockingChunks - maximum amount of unlocking chunks */ function initialize( bytes32 _stashAccount, bytes32 _controllerAccount, address _vKSM, address _controller, uint128 _minNominatorBalance, address _lido, uint128 _minimumBalance, uint256 _maxUnlockingChunks ) external { require(_vKSM != address(0), "LEDGER: INCORRECT_VKSM"); require(address(VKSM) == address(0), "LEDGER: ALREADY_INITIALIZED"); // The owner of the funds stashAccount = _stashAccount; // The account which handles bounded part of stash funds (unbond, rebond, withdraw, nominate) controllerAccount = _controllerAccount; status = Types.LedgerStatus.None; LIDO = ILido(_lido); VKSM = IERC20(_vKSM); CONTROLLER = IController(_controller); MIN_NOMINATOR_BALANCE = _minNominatorBalance; MINIMUM_BALANCE = _minimumBalance; MAX_UNLOCKING_CHUNKS = _maxUnlockingChunks; _refreshAllowances(); } /** * @notice Set new minimal allowed nominator balance and minimal active balance, allowed to call only by lido contract * @dev That method designed to be called by lido contract when relay spec is changed * @param _minNominatorBalance - minimal allowed nominator balance * @param _minimumBalance - minimal allowed ledger active balance * @param _maxUnlockingChunks - maximum amount of unlocking chunks */ function setRelaySpecs(uint128 _minNominatorBalance, uint128 _minimumBalance, uint256 _maxUnlockingChunks) external onlyLido { MIN_NOMINATOR_BALANCE = _minNominatorBalance; MINIMUM_BALANCE = _minimumBalance; MAX_UNLOCKING_CHUNKS = _maxUnlockingChunks; } /** * @notice Refresh allowances for ledger */ function refreshAllowances() external auth(ROLE_LEDGER_MANAGER) { _refreshAllowances(); } /** * @notice Return target stake amount for this ledger * @return target stake amount */ function ledgerStake() public view returns (uint256) { return LIDO.ledgerStake(address(this)); } /** * @notice Return true if ledger doesn't have any funds */ function isEmpty() external view returns (bool) { return totalBalance == 0 && transferUpwardBalance == 0 && transferDownwardBalance == 0; } /** * @notice Nominate on behalf of this ledger, allowed to call only by lido contract * @dev Method spawns xcm call to relaychain. * @param _validators - array of choosen validator to be nominated */ function nominate(bytes32[] calldata _validators) external onlyLido { require(activeBalance >= MIN_NOMINATOR_BALANCE, "LEDGER: NOT_ENOUGH_STAKE"); CONTROLLER.nominate(_validators); } /** * @notice Provide portion of relaychain data about current ledger, allowed to call only by oracle contract * @dev Basically, ledger can obtain data from any source, but for now it allowed to recieve only from oracle. Method perform calculation of current state based on report data and saved state and expose required instructions(relaychain pallet calls) via xcm to adjust bonded amount to required target stake. * @param _eraId - reporting era id * @param _report - data that represent state of ledger on relaychain for `_eraId` */ function pushData(uint64 _eraId, Types.OracleData memory _report) external onlyOracle { require(stashAccount == _report.stashAccount, "LEDGER: STASH_ACCOUNT_MISMATCH"); status = _report.stakeStatus; activeBalance = _report.activeBalance; (uint128 unlockingBalance, uint128 withdrawableBalance) = _report.getTotalUnlocking(_eraId); if (!_processRelayTransfers(_report)) { return; } uint128 _cachedTotalBalance = cachedTotalBalance; uint256 totalSupply = LIDO.totalSupply(); if (totalSupply > 0) { uint256 relativeDifference = _report.stashBalance > cachedTotalBalance ? _report.stashBalance - cachedTotalBalance : cachedTotalBalance - _report.stashBalance; // NOTE: 1 / 10000 - one base point relativeDifference = relativeDifference * 10000 / totalSupply; require(relativeDifference < LIDO.MAX_ALLOWABLE_DIFFERENCE(), "LEDGER: DIFFERENCE_EXCEEDS_BALANCE"); } if (_cachedTotalBalance < _report.stashBalance) { // if cached balance > real => we have reward uint128 reward = _report.stashBalance - _cachedTotalBalance; LIDO.distributeRewards(reward, _report.stashBalance); emit Rewards(reward, _report.stashBalance); } else if (_cachedTotalBalance > _report.stashBalance) { uint128 slash = _cachedTotalBalance - _report.stashBalance; LIDO.distributeLosses(slash, _report.stashBalance); emit Slash(slash, _report.stashBalance); } uint128 _ledgerStake = ledgerStake().toUint128(); // Always transfer deficit to relay chain if (_report.stashBalance < _ledgerStake) { uint128 deficit = _ledgerStake - _report.stashBalance; require(VKSM.balanceOf(address(LIDO)) >= deficit, "LEDGER: TRANSFER_EXCEEDS_BALANCE"); LIDO.transferToLedger(deficit); CONTROLLER.transferToRelaychain(deficit); transferUpwardBalance += deficit; } uint128 relayFreeBalance = _report.getFreeBalance(); pendingBonds = 0; // Always set bonds to zero (if we have old free balance then it will bond again) if (activeBalance < _ledgerStake) { // NOTE: if ledger stake > active balance we are trying to bond all funds uint128 diff = _ledgerStake - activeBalance; uint128 diffToRebond = diff > unlockingBalance ? unlockingBalance : diff; if (diffToRebond > 0) { CONTROLLER.rebond(diffToRebond, MAX_UNLOCKING_CHUNKS); diff -= diffToRebond; } if (transferUpwardBalance > 0 && relayFreeBalance == transferUpwardBalance) { // In case if bond amount = transferUpwardBalance we can't distinguish 2 messages were success or 2 messages were failed relayFreeBalance -= 1; } if (diff > 0 && relayFreeBalance > 0) { uint128 diffToBond = diff > relayFreeBalance ? relayFreeBalance : diff; if (_report.stakeStatus == Types.LedgerStatus.Nominator || _report.stakeStatus == Types.LedgerStatus.Idle) { CONTROLLER.bondExtra(diffToBond); pendingBonds = diffToBond; } else if (_report.stakeStatus == Types.LedgerStatus.None && diffToBond >= MIN_NOMINATOR_BALANCE) { CONTROLLER.bond(controllerAccount, diffToBond); pendingBonds = diffToBond; } relayFreeBalance -= diffToBond; } } else { if (_ledgerStake < MIN_NOMINATOR_BALANCE && status != Types.LedgerStatus.Idle && activeBalance > 0) { CONTROLLER.chill(); } // NOTE: if ledger stake < active balance we unbond uint128 diff = activeBalance - _ledgerStake; if (diff > 0) { CONTROLLER.unbond(diff); } // NOTE: if ledger stake == active balance we only withdraw unlocked balance if (withdrawableBalance > 0) { uint32 slashSpans = 0; if (_report.unlocking.length == 0 && _report.activeBalance <= MINIMUM_BALANCE) { slashSpans = _report.slashingSpans; } CONTROLLER.withdrawUnbonded(slashSpans); } } // NOTE: always transfer all free baalance to parachain if (relayFreeBalance > 0) { CONTROLLER.transferToParachain(relayFreeBalance); transferDownwardBalance += relayFreeBalance; } cachedTotalBalance = _report.stashBalance; } /** * @notice Await for all transfers from/to relay chain * @param _report - data that represent state of ledger on relaychain */ function _processRelayTransfers(Types.OracleData memory _report) internal returns(bool) { // wait for the downward transfer to complete uint128 _transferDownwardBalance = transferDownwardBalance; if (_transferDownwardBalance > 0) { uint128 totalDownwardTransferred = uint128(VKSM.balanceOf(address(this))); if (totalDownwardTransferred >= _transferDownwardBalance ) { // send all funds to lido LIDO.transferFromLedger(_transferDownwardBalance, totalDownwardTransferred - _transferDownwardBalance); // Clear transfer flag cachedTotalBalance -= _transferDownwardBalance; transferDownwardBalance = 0; emit DownwardComplete(_transferDownwardBalance); _transferDownwardBalance = 0; } } // wait for the upward transfer to complete uint128 _transferUpwardBalance = transferUpwardBalance; if (_transferUpwardBalance > 0) { // NOTE: pending Bonds allows to control balance which was bonded in previous era, but not in lockedBalance yet // (see single_ledger_test:test_equal_deposit_bond) uint128 ledgerFreeBalance = (totalBalance - lockedBalance); int128 freeBalanceDiff = int128(_report.getFreeBalance()) - int128(ledgerFreeBalance); int128 expectedBalanceDiff = int128(transferUpwardBalance) - int128(pendingBonds); if (freeBalanceDiff >= expectedBalanceDiff) { cachedTotalBalance += _transferUpwardBalance; transferUpwardBalance = 0; // pendingBonds = 0; emit UpwardComplete(_transferUpwardBalance); _transferUpwardBalance = 0; } } if (_transferDownwardBalance == 0 && _transferUpwardBalance == 0) { // update ledger data from oracle report totalBalance = _report.stashBalance; lockedBalance = _report.totalBalance; return true; } return false; } /** * @notice Refresh allowances for ledger */ function _refreshAllowances() internal { VKSM.approve(address(LIDO), type(uint256).max); VKSM.approve(address(CONTROLLER), type(uint256).max); } }
Await for all transfers from/to relay chain _report - data that represent state of ledger on relaychain/ wait for the downward transfer to complete
function _processRelayTransfers(Types.OracleData memory _report) internal returns(bool) { uint128 _transferDownwardBalance = transferDownwardBalance; if (_transferDownwardBalance > 0) { uint128 totalDownwardTransferred = uint128(VKSM.balanceOf(address(this))); if (totalDownwardTransferred >= _transferDownwardBalance ) { LIDO.transferFromLedger(_transferDownwardBalance, totalDownwardTransferred - _transferDownwardBalance); cachedTotalBalance -= _transferDownwardBalance; transferDownwardBalance = 0; emit DownwardComplete(_transferDownwardBalance); _transferDownwardBalance = 0; } } if (_transferDownwardBalance > 0) { uint128 totalDownwardTransferred = uint128(VKSM.balanceOf(address(this))); if (totalDownwardTransferred >= _transferDownwardBalance ) { LIDO.transferFromLedger(_transferDownwardBalance, totalDownwardTransferred - _transferDownwardBalance); cachedTotalBalance -= _transferDownwardBalance; transferDownwardBalance = 0; emit DownwardComplete(_transferDownwardBalance); _transferDownwardBalance = 0; } } uint128 _transferUpwardBalance = transferUpwardBalance; if (_transferUpwardBalance > 0) { uint128 ledgerFreeBalance = (totalBalance - lockedBalance); int128 freeBalanceDiff = int128(_report.getFreeBalance()) - int128(ledgerFreeBalance); int128 expectedBalanceDiff = int128(transferUpwardBalance) - int128(pendingBonds); if (freeBalanceDiff >= expectedBalanceDiff) { cachedTotalBalance += _transferUpwardBalance; transferUpwardBalance = 0; emit UpwardComplete(_transferUpwardBalance); _transferUpwardBalance = 0; } } if (_transferUpwardBalance > 0) { uint128 ledgerFreeBalance = (totalBalance - lockedBalance); int128 freeBalanceDiff = int128(_report.getFreeBalance()) - int128(ledgerFreeBalance); int128 expectedBalanceDiff = int128(transferUpwardBalance) - int128(pendingBonds); if (freeBalanceDiff >= expectedBalanceDiff) { cachedTotalBalance += _transferUpwardBalance; transferUpwardBalance = 0; emit UpwardComplete(_transferUpwardBalance); _transferUpwardBalance = 0; } } if (_transferDownwardBalance == 0 && _transferUpwardBalance == 0) { totalBalance = _report.stashBalance; lockedBalance = _report.totalBalance; return true; } return false; }
916,483
//SPDX-License-Identifier: MIT //Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) pragma solidity ^0.8.0; /* .・。.・゜✭・.・✫・゜・。..・。.・゜✭・.・✫・゜・。.✭・.・✫・゜・。..・✫・゜・。.・。.・゜✭・.・✫・゜・。..・。.・゜✭・.・✫・゜・。.✭・.・✫・゜・。..・✫・゜・。 s _ .. :8 u .u . @L .d`` .88 u. u. 88Nu. u. u. u. . .d88B :@8c 9888i .dL @8Ne. .u :888ooo ...ue888b . ...ue888b '88888.o888c .u x@88k u@88c. .udR88N ="8888f8888r `Y888k:*888. %8888:u@88N -*8888888 888R Y888r .udR88N 888R Y888r ^8888 8888 ud8888. ^"8888""8888" <888'888k 4888>'88" 888E 888I `888I 888. 8888 888R I888> <888'888k 888R I888> 8888 8888 :888'8888. 8888 888R 9888 'Y" 4888> ' 888E 888I 888I 888I 8888 888R I888> 9888 'Y" 888R I888> 8888 8888 d888 '88%" 8888 888R 9888 4888> 888E 888I 888I 888I 8888 888R I888> 9888 888R I888> 8888 8888 8888.+" 8888 888R 9888 .d888L .+ 888E 888I uW888L 888' .8888Lu= u8888cJ888 9888 u8888cJ888 .8888b.888P 8888L 8888 888R ?8888u../ ^"8888*" x888N><888' '*88888Nu88P ^%888* "*888*P" ?8888u../ "*888*P" ^Y8888*"" '8888c. .+ "*88*" 8888" "8888P' "Y" "88" 888 ~ '88888F` 'Y" 'Y" "8888P' 'Y" `Y" "88888% "" 'Y" "P' 88F 888 ^ "P' "YP' 98" *8E ./" '8> ~` " .・。.・゜✭・.・✫・゜・。..・。.・゜✭・.・✫・゜・。.✭・.・✫・゜・。..・✫・゜・。.・。.・゜✭・.・✫・゜・。..・。.・゜✭・.・✫・゜・。.✭・.・✫・゜・。..・✫・゜・。 */ import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /* I will make some comments with KW "Frank" */ // Frank: IERC2981 is for royalties // Frank: ReentrancyGuard is for contract securities contract CryptoCoven is ERC721, IERC2981, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string private baseURI; string public verificationHash; // Frank: related to pre-sale? // Frank: opnSea staffs address private openSeaProxyRegistryAddress; bool private isOpenSeaProxyActive = true; uint256 public constant MAX_WITCHES_PER_WALLET = 3; uint256 public maxWitches; // frank: public sale settings uint256 public constant PUBLIC_SALE_PRICE = 0.07 ether; bool public isPublicSaleActive; //frank: pre-sale mint settings uint256 public constant COMMUNITY_SALE_PRICE = 0.05 ether; uint256 public maxCommunitySaleWitches; bytes32 public communitySaleMerkleRoot; //frank: related to validation? bool public isCommunitySaleActive; uint256 public maxGiftedWitches; //frank: 合约查询为250个 uint256 public numGiftedWitches; //frank: 合约查询为101个 bytes32 public claimListMerkleRoot; // frank: record the pre-sale mint address with mint counts mapping(address => uint256) public communityMintCounts; //frank:claimed mapping mapping(address => bool) public claimed; // ============ ACCESS CONTROL/SANITY MODIFIERS ============ modifier publicSaleActive() { require(isPublicSaleActive, "Public sale is not open"); _; } modifier communitySaleActive() { require(isCommunitySaleActive, "Community sale is not open"); _; } //frank: 没有用mapping来记录钱包mint数量,所以可以通过转移到其他钱包规避该限制? modifier maxWitchesPerWallet(uint256 numberOfTokens) { require( balanceOf(msg.sender) + numberOfTokens <= MAX_WITCHES_PER_WALLET, "Max witches to mint is three" ); _; } //frank: mint的数量超出最大供应量(初始最大供应量-最大gifted的数量) modifier canMintWitches(uint256 numberOfTokens) { require( tokenCounter.current() + numberOfTokens <= maxWitches - maxGiftedWitches, "Not enough witches remaining to mint" ); _; } modifier canGiftWitches(uint256 num) { require( numGiftedWitches + num <= maxGiftedWitches, "Not enough witches remaining to gift" ); require( tokenCounter.current() + num <= maxWitches, "Not enough witches remaining to mint" ); _; } // frank:检查mint提交的金额是否等于价格*mint数量 modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { require( price * numberOfTokens == msg.value, "Incorrect ETH value sent" ); _; } // Frank: verify if the address is valid. For pre-sale? modifier isValidMerkleProof(bytes32[] calldata merkleProof, bytes32 root) { require( MerkleProof.verify( merkleProof, root, keccak256(abi.encodePacked(msg.sender)) ), "Address does not exist in list" ); _; } // frank: 合约初始化 constructor( address _openSeaProxyRegistryAddress, uint256 _maxWitches, //frank 9999 uint256 _maxCommunitySaleWitches, //frank 3333 uint256 _maxGiftedWitches // frank 250 ) ERC721("Crypto Coven", "WITCH") { openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; maxWitches = _maxWitches; maxCommunitySaleWitches = _maxCommunitySaleWitches; maxGiftedWitches = _maxGiftedWitches; } // ============ PUBLIC FUNCTIONS FOR MINTING ============ function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintWitches(numberOfTokens) maxWitchesPerWallet(numberOfTokens) { for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } //frank: pre-sale community sale function mintCommunitySale( uint8 numberOfTokens, bytes32[] calldata merkleProof ) external payable nonReentrant communitySaleActive canMintWitches(numberOfTokens) isCorrectPayment(COMMUNITY_SALE_PRICE, numberOfTokens) isValidMerkleProof(merkleProof, communitySaleMerkleRoot) { // check the current balance of the accouts uint256 numAlreadyMinted = communityMintCounts[msg.sender]; require( numAlreadyMinted + numberOfTokens <= MAX_WITCHES_PER_WALLET, "Max witches to mint in community sale is three" ); require( tokenCounter.current() + numberOfTokens <= maxCommunitySaleWitches, "Not enough witches remaining to mint" ); // update this addr balance account communityMintCounts[msg.sender] = numAlreadyMinted + numberOfTokens; for (uint256 i = 0; i < numberOfTokens; i++) { _safeMint(msg.sender, nextTokenId()); } } // frank: not payable, so no ether transfer. I think the team gives to addr as a gift. One for each addr. function claim(bytes32[] calldata merkleProof) external isValidMerkleProof(merkleProof, claimListMerkleRoot) canGiftWitches(1) { require(!claimed[msg.sender], "Witch already claimed by this wallet"); claimed[msg.sender] = true; numGiftedWitches += 1; _safeMint(msg.sender, nextTokenId()); } // ============ PUBLIC READ-ONLY FUNCTIONS ============ // frank: just for return the current states function getBaseURI() external view returns (string memory) { return baseURI; } function getLastTokenId() external view returns (uint256) { return tokenCounter.current(); } // ============ OWNER-ONLY ADMIN FUNCTIONS ============ // frank: "onlyOwner" as the keyword function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } // function to disable gasless listings for security in case // opensea ever shuts down or is compromised function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive) external onlyOwner { isOpenSeaProxyActive = _isOpenSeaProxyActive; } function setVerificationHash(string memory _verificationHash) external onlyOwner { verificationHash = _verificationHash; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setIsCommunitySaleActive(bool _isCommunitySaleActive) external onlyOwner { isCommunitySaleActive = _isCommunitySaleActive; } function setCommunityListMerkleRoot(bytes32 merkleRoot) external onlyOwner { communitySaleMerkleRoot = merkleRoot; } function setClaimListMerkleRoot(bytes32 merkleRoot) external onlyOwner { claimListMerkleRoot = merkleRoot; } //frank: 项目方自己mint出来保留 function reserveForGifting(uint256 numToReserve) external nonReentrant onlyOwner canGiftWitches(numToReserve) { numGiftedWitches += numToReserve; for (uint256 i = 0; i < numToReserve; i++) { _safeMint(msg.sender, nextTokenId()); } } // frank: 项目方送给这些下面这些的钱包 function giftWitches(address[] calldata addresses) external nonReentrant onlyOwner canGiftWitches(addresses.length) { uint256 numToGift = addresses.length; numGiftedWitches += numToGift; for (uint256 i = 0; i < numToGift; i++) { _safeMint(addresses[i], nextTokenId()); } } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } // frank: roll over 的逻辑是啥?为啥限定在128? function rollOverWitches(address[] calldata addresses) external nonReentrant onlyOwner { require( tokenCounter.current() + addresses.length <= 128, "All witches are already rolled over" ); for (uint256 i = 0; i < addresses.length; i++) { communityMintCounts[addresses[i]] += 1; // use mint rather than _safeMint here to reduce gas costs // and prevent this from failing in case of grief attempts _mint(addresses[i], nextTokenId()); } } // ============ SUPPORTING FUNCTIONS ============ //frank: helper function function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } // ============ FUNCTION OVERRIDES ============ //frank: override "supportsInterface" function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Override isApprovedForAll to allowlist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Get a reference to OpenSea's proxy registry contract by instantiating // the contract using the already existing address. ProxyRegistry proxyRegistry = ProxyRegistry( openSeaProxyRegistryAddress ); if ( isOpenSeaProxyActive && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json")); } /** * @dev See {IERC165-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100)); } } // These contract definitions are used to create a reference to the OpenSea // ProxyRegistry contract by using the registry's address (see isApprovedForAll). contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
frank: 项目方自己mint出来保留
function reserveForGifting(uint256 numToReserve) external nonReentrant onlyOwner canGiftWitches(numToReserve) { numGiftedWitches += numToReserve; for (uint256 i = 0; i < numToReserve; i++) { _safeMint(msg.sender, nextTokenId()); } }
12,692,285
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "../utils/Bearable.sol"; import "../utils/TwoBitHoneyErrors.sol"; /// @title Honey Processor: Phase 1 contract TwoBitHoney is Bearable, ERC1155, Ownable { /* .:.. .=++=-::-++=. .*= .+* :#. :# %. =+ @ .# ==: %. -+ :=+===: +==#- -# %=++: -*- :+++= %: ++ ##- *- :+. :%: +* =* .#- .# -% *= :#: =*. =+ .=%=*+=- +*. -*- :*= ++. :*++*==%@*+#= .:-=++- =* .: :@@# #@@@=-@@@#+#@*=-:. =*.-.: =@@= @@@@ @@@+ -@@#: *= .@@% *@@@= -@@@- *@@+++ :+=====#@* +@@@* %@@% .@@@..@+ +*-%@@@+ #@@@: %@@+ +@@*- .+@@%: .#@@@: #@@* +@#=-- =+++@@@%..#@@#=*+: .-*#+: :-+*==**+=-. :+*+- .=**- .=**=. -*#+: :+*+: .=**: ** +* *+ +* *+ +* *+ +* *+ +* *+ +* *# ** -**=: .=**-. -+**#=: :=**- -+*+: .=**-. :+**- -**+:.=**-. -**+: -**=. .=+: -#*- :+#= +* =# +* =# +* =# +* =# +* =# +* =# =%-. -#* -+*+: .=**=. .: .=**=. -+*+: :+*+=**=. -*#+=#*=. .=*#=. :*#+: :- :+*+- :+**- =#=. -#+ *+ +* *+ +* *+ +* *+ +* *+ +* *+ +* -#+: :=#= .-+- .=**=. -**=: :+*+-.=**=. :+#+: :+**- .=**=. :+#+: .=****=. -+*+: .=**- +#. *# +* =# +* =# +* =# +* =# +* =# +* =# :+*+: .=**- .=**=. -+*+: :+*+: .=**-. .=**+: */ /// @dev Counter for total minted honey token uint256 private _totalSupply; /// @dev Address of the cubs contract, for burning address private _cubsContract; /// @dev Marks when drop of honey is complete (and there will be no more) bool private _honeyFrozen; /// Let's the world know whether the base URI has changed event SetBaseURI(string indexed _baseURI); /// Let OpenSea know that the uri is now frozen event PermanentURI(string _value, uint256 indexed _id); /// Creates a new instance of the TwoBitHoney contract, with the address of the TwoBitBears contract and a baseURI for metadata constructor(address twoBitBears, string memory baseURI) Bearable(twoBitBears) ERC1155(baseURI) { _totalSupply = 0; _honeyFrozen = false; } /// Sets the address of the TwoBitCubs contract, which will have rights to burn honey tokens function setCubsContractAddress(address cubsContract) external onlyOwner { _cubsContract = cubsContract; } /// Performs the burn of a single honey token on behalf of the TwoBitCubs contract /// @dev Throws if the msg.sender is not the configured TwoBitCubs contract function burnHoneyForAddress(address burnTokenAddress) external { if (msg.sender != _cubsContract) revert InvalidBurner(); _burn(burnTokenAddress, 0, 1); } /// Calculate the honey drop count for the specified owner /// @dev external read-only function to reduce gas cost of delivering the drop function calculateDrop(address owner) external view onlyOwner returns (uint256 bearsOwned, uint256 honeyCount) { uint256 browns; uint256 blacks; uint256 polars; uint256 pandas; bearsOwned = _twoBitBears.balanceOf(owner); for (uint256 index = 0; index < bearsOwned; index++) { uint256 tokenId = _twoBitBears.tokenOfOwnerByIndex(owner, index); BearSpeciesType species = bearSpecies(tokenId); if (species == IBearable.BearSpeciesType.Brown) { browns += 1; } else if (species == IBearable.BearSpeciesType.Black) { blacks += 1; } else if (species == IBearable.BearSpeciesType.Polar) { polars += 1; } else if (species == IBearable.BearSpeciesType.Panda) { pandas += 1; } } honeyCount = (browns >> 1) + (blacks >> 1) + (polars >> 1) + (pandas >> 1); } /// Performs the drop to TwoBitBear holders function dropHoney(address[] memory accounts, uint256[] memory amounts) public onlyOwner { if (accounts.length != amounts.length) revert MismatchedArraySizes(); if (_honeyFrozen) revert HoneyDropFrozen(); uint256 additionalSupply = 0; for (uint256 index = 0; index < accounts.length; index++) { uint256 amount = amounts[index]; _mint(accounts[index], 0, amount, ""); additionalSupply += amount; } _totalSupply += additionalSupply; } /// Freezes the metadata and any additional honey drops function freezeHoney() public onlyOwner { if (_honeyFrozen) revert HoneyDropFrozen(); _honeyFrozen = true; emit PermanentURI(uri(0), 0); } /// Returns the owner of the TwoBitBear specified by the bearTokenId function ownerOfBear(uint256 bearTokenId) external view onlyOwner returns (address owner) { owner = _twoBitBears.ownerOf(bearTokenId); } /// @dev Total amount of tokens in with a given id. function totalSupply(uint256 id) public view virtual returns (uint256) { if (id != 0) { return 0; } return _totalSupply; } /// @dev Indicates weither any token exist with a given id, or not. function exists(uint256 id) public view virtual returns (bool) { return totalSupply(id) > 0; } /// Updates the baseURI function updateBaseUri(string memory newuri) external onlyOwner { if (_honeyFrozen) revert HoneyDropFrozen(); _setURI(newuri); emit SetBaseURI(newuri); } /// @dev Reverts with `InvalidHoneyTypeId()` if the `typeId` is > 0 function uri(uint256 typeId) public view override returns (string memory) { if (typeId > 0) revert InvalidHoneyTypeId(); return super.uri(typeId); } } // 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 "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = _balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][account] = accountBalance - amount; } } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IBearable.sol"; import "../nfts/TwoBitBears.sol"; /// @title Bearable base contract for accessing a deployed TwoBitBears ERC721 /// @dev You may inherit or deploy separately contract Bearable is IBearable { /// @dev Stores the address to the deployed TwoBitBears contract TwoBitBears internal immutable _twoBitBears; /// Constructs a new instance of the Bearable contract /// @param twoBitBears The address of the twoBitBears contract on the deployment blockchain constructor(address twoBitBears) { _twoBitBears = TwoBitBears(twoBitBears); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .ownerOf() call function ownsBear(address possibleOwner, uint256 tokenId) public view override returns (bool) { return _twoBitBears.ownerOf(tokenId) == possibleOwner; } /// @inheritdoc IBearable function totalBears() public view override returns (uint256) { return _twoBitBears.totalSupply(); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearBottomColor(uint256 tokenId) public view override returns (ISVG.Color memory color) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); color.red = details.bottomColor.red; color.green = details.bottomColor.green; color.blue = details.bottomColor.blue; color.alpha = 0xFF; } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearMood(uint256 tokenId) public view override returns (BearMoodType) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); return BearMoodType(details.moodIndex); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearSpecies(uint256 tokenId) public view override returns (BearSpeciesType) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); return BearSpeciesType(details.speciesIndex); } /// @inheritdoc IBearable /// @dev Throws if the token ID is not valid. Requirements already handled by the .details() call function bearTopColor(uint256 tokenId) public view override returns (ISVG.Color memory color) { IBearDetail.Detail memory details = _twoBitBears.details(tokenId); color.red = details.topColor.red; color.green = details.topColor.green; color.blue = details.topColor.blue; color.alpha = 0xFF; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev Honey drop is frozen error HoneyDropFrozen(); /// @dev When the burn requestor is invalid error InvalidBurner(); /// @dev When a tokenId > 0 is supplied error InvalidHoneyTypeId(); /// @dev When array parameters sizes don't match error MismatchedArraySizes(); // 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 ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./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 "./ISVG.sol"; /// @title Interface for accessing official TwoBitBears data interface IBearable { /// Represents the species of a TwoBitBear enum BearSpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a TwoBitBear enum BearMoodType { Happy, Hungry, Sleepy, Grumpy } /// Returns whether the TwoBitBear at tokenId currently belongs to the owner /// @dev Throws if the token ID is not valid. function ownsBear(address possibleOwner, uint256 tokenId) external view returns (bool); /// Returns the total tokens in the TwoBitBear contract function totalBears() external view returns (uint256); /// Returns the realistic body fur color of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearBottomColor(uint256 tokenId) external view returns (ISVG.Color memory color); /// Returns the all-important `BearMoodType` of the TwoBitBear at tokenId (be nice) /// @dev Throws if the token ID is not valid. function bearMood(uint256 tokenId) external view returns (BearMoodType); /// Returns the BearSpeciesType of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearSpecies(uint256 tokenId) external view returns (BearSpeciesType); /// Returns the realistic head fur color of the TwoBitBear at tokenId /// @dev Throws if the token ID is not valid. function bearTopColor(uint256 tokenId) external view returns (ISVG.Color memory color); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/IBearDetail.sol"; /// Represents a deployed TwoBitBears contract abstract contract TwoBitBears is IBearDetail, IERC721Enumerable { /// The only public non-interface function declared usable for any caller /// @dev This call will fail for the official mainnet contract because TwoBitBears are sold out function createBear(uint256 quantity) public payable virtual; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISVG image library interface interface ISVG { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color type in an SVG image file enum ColorType { Fill, Stroke, None } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title TwoBitBears NFT Detail Interface interface IBearDetail { /// Represents the colors of a TwoBitBear struct Color { uint8 red; uint8 green; uint8 blue; } /// Represents the details of a TwoBitBear struct Detail { uint256 timestamp; uint8 nameIndex; uint8 moodIndex; uint8 familyIndex; uint8 speciesIndex; Color topColor; Color bottomColor; } /// Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Bear /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // 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; }
Reverts with `InvalidHoneyTypeId()` if the `typeId` is > 0
function uri(uint256 typeId) public view override returns (string memory) { if (typeId > 0) revert InvalidHoneyTypeId(); return super.uri(typeId); }
5,392,287
./full_match/1/0x9f6a8939d5f45d3C51bAF58dadaB04D75b8Da4C1/sources/contracts/MAHAXLocker.sol
Clear an approval of a given address Throws if `_owner` is not the current owner. Throws if `_owner` is not the current owner Reset approvals
function _clearApproval(address _owner, uint256 _tokenId) internal { assert(idToOwner[_tokenId] == _owner); if (idToApprovals[_tokenId] != address(0)) { idToApprovals[_tokenId] = address(0); } }
2,959,328
./full_match/42/0x9978Bc141d6fb9E9b3E0E63EfEAaa359c8355081/sources/contracts/FController.sol
Calculate additional accrued COMP for a contributor since last accrual contributor The address to calculate contributor rewards for/
function updateContributorRewards(address contributor) public { uint parSpeed = parContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && parSpeed > 0) { uint newAccrued = mul_(deltaBlocks, parSpeed); uint contributorAccrued = add_(parAccrued[contributor], newAccrued); parAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } }
16,224,512
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {SafeERC20} from '@aave/aave-stake/contracts/lib/SafeERC20.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {VersionedInitializable} from '@aave/aave-stake/contracts/utils/VersionedInitializable.sol'; import {DistributionManager} from './DistributionManager.sol'; import {IStakedTokenWithConfig} from '../interfaces/IStakedTokenWithConfig.sol'; import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol'; import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol'; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; /** * @title StakedTokenIncentivesController * @notice Distributor contract for rewards to the Aave protocol, using a staked token as rewards asset. * The contract stakes the rewards before redistributing them to the Aave protocol participants. * The reference staked token implementation is at https://github.com/aave/aave-stake-v2 * @author Aave **/ contract StakedTokenIncentivesController is IAaveIncentivesController, VersionedInitializable, DistributionManager { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant REVISION = 1; IStakedTokenWithConfig public immutable STAKE_TOKEN; mapping(address => uint256) internal _usersUnclaimedRewards; // this mapping allows whitelisted addresses to claim on behalf of others // useful for contracts that hold tokens to be rewarded but don't have any native logic to claim Liquidity Mining rewards mapping(address => address) internal _authorizedClaimers; modifier onlyAuthorizedClaimers(address claimer, address user) { require(_authorizedClaimers[user] == claimer, 'CLAIMER_UNAUTHORIZED'); _; } constructor(IStakedTokenWithConfig stakeToken, address emissionManager) DistributionManager(emissionManager) { STAKE_TOKEN = stakeToken; } /** * @dev Initialize IStakedTokenIncentivesController * @param addressesProvider the address of the corresponding addresses provider **/ function initialize(address addressesProvider) external initializer { //approves the safety module to allow staking IERC20(STAKE_TOKEN.STAKED_TOKEN()).safeApprove(address(STAKE_TOKEN), type(uint256).max); } /// @inheritdoc IAaveIncentivesController function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external override onlyEmissionManager { require(assets.length == emissionsPerSecond.length, 'INVALID_CONFIGURATION'); DistributionTypes.AssetConfigInput[] memory assetsConfig = new DistributionTypes.AssetConfigInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { assetsConfig[i].underlyingAsset = assets[i]; assetsConfig[i].emissionPerSecond = uint104(emissionsPerSecond[i]); require(assetsConfig[i].emissionPerSecond == emissionsPerSecond[i], 'INVALID_CONFIGURATION'); assetsConfig[i].totalStaked = IScaledBalanceToken(assets[i]).scaledTotalSupply(); } _configureAssets(assetsConfig); } /// @inheritdoc IAaveIncentivesController function handleAction( address user, uint256 totalSupply, uint256 userBalance ) external override { uint256 accruedRewards = _updateUserAssetInternal(user, msg.sender, userBalance, totalSupply); if (accruedRewards != 0) { _usersUnclaimedRewards[user] = _usersUnclaimedRewards[user].add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } } /// @inheritdoc IAaveIncentivesController function getRewardsBalance(address[] calldata assets, address user) external view override returns (uint256) { uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } unclaimedRewards = unclaimedRewards.add(_getUnclaimedRewards(user, userState)); return unclaimedRewards; } /// @inheritdoc IAaveIncentivesController function claimRewards( address[] calldata assets, uint256 amount, address to ) external override returns (uint256) { require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, msg.sender, to); } /// @inheritdoc IAaveIncentivesController function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, user, to); } /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ /// @inheritdoc IAaveIncentivesController function setClaimer(address user, address caller) external override onlyEmissionManager { _authorizedClaimers[user] = caller; emit ClaimerSet(user, caller); } /// @inheritdoc IAaveIncentivesController function getClaimer(address user) external view override returns (address) { return _authorizedClaimers[user]; } /// @inheritdoc IAaveIncentivesController function getUserUnclaimedRewards(address _user) external view override returns (uint256) { return _usersUnclaimedRewards[_user]; } /// @inheritdoc IAaveIncentivesController function REWARD_TOKEN() external view override returns (address) { return address(STAKE_TOKEN); } /** * @dev returns the revision of the implementation contract */ function getRevision() internal pure override returns (uint256) { return REVISION; } /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; _usersUnclaimedRewards[user] = unclaimedRewards - amountToClaim; // Safe due to the previous line STAKE_TOKEN.stake(to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import {IERC20} from '../interfaces/IERC20.sol'; import {SafeMath} from './SafeMath.sol'; import {Address} from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Interface of the ERC20 standard as defined in the EIP. * From https://github.com/OpenZeppelin/openzeppelin-contracts */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Collection of functions related to the address type * From https://github.com/OpenZeppelin/openzeppelin-contracts */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.7.5; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost /// inspired by uniswap V3 library SafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } function div(uint256 x, uint256 y) internal pure returns(uint256) { // no need to check for division by zero - solidity already reverts return x / y; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint104 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * @author Aave, inspired by the OpenZeppelin Initializable contract */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, 'Contract instance has already been initialized'); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns (uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; /** * @title DistributionManager * @notice Accounting contract to manage multiple staking distributions * @author Aave **/ contract DistributionManager is IAaveDistributionManager { using SafeMath for uint256; struct AssetData { uint104 emissionPerSecond; uint104 index; uint40 lastUpdateTimestamp; mapping(address => uint256) users; } address public immutable EMISSION_MANAGER; uint8 public constant PRECISION = 18; mapping(address => AssetData) public assets; uint256 internal _distributionEnd; modifier onlyEmissionManager() { require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER'); _; } constructor(address emissionManager) { EMISSION_MANAGER = emissionManager; } /// @inheritdoc IAaveDistributionManager function setDistributionEnd(uint256 distributionEnd) external override onlyEmissionManager { _distributionEnd = distributionEnd; emit DistributionEndUpdated(distributionEnd); } /// @inheritdoc IAaveDistributionManager function getDistributionEnd() external view override returns (uint256) { return _distributionEnd; } /// @inheritdoc IAaveDistributionManager function DISTRIBUTION_END() external view override returns (uint256) { return _distributionEnd; } /// @inheritdoc IAaveDistributionManager function getUserAssetData(address user, address asset) public view override returns (uint256) { return assets[asset].users[user]; } /** * @dev Configure the assets for a specific emission * @param assetsConfigInput The array of each asset configuration **/ function _configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) internal { for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param asset The address of the asset being updated * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address asset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint256 emissionPerSecond = assetConfig.emissionPerSecond; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex(oldIndex, emissionPerSecond, lastUpdateTimestamp, totalStaked); if (newIndex != oldIndex) { require(uint104(newIndex) == newIndex, 'Index overflow'); //optimization: storing one after another saves one SSTORE assetConfig.index = uint104(newIndex); assetConfig.lastUpdateTimestamp = uint40(block.timestamp); emit AssetIndexUpdated(asset, newIndex); } else { assetConfig.lastUpdateTimestamp = uint40(block.timestamp); } return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal pure returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)) / 10**uint256(PRECISION); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { uint256 distributionEnd = _distributionEnd; if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= distributionEnd ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > distributionEnd ? distributionEnd : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {DistributionTypes} from '../lib/DistributionTypes.sol'; interface IAaveDistributionManager { event AssetConfigUpdated(address indexed asset, uint256 emission); event AssetIndexUpdated(address indexed asset, uint256 index); event UserIndexUpdated(address indexed user, address indexed asset, uint256 index); event DistributionEndUpdated(uint256 newDistributionEnd); /** * @dev Sets the end date for the distribution * @param distributionEnd The end date timestamp **/ function setDistributionEnd(uint256 distributionEnd) external; /** * @dev Gets the end date for the distribution * @return The end of the distribution **/ function getDistributionEnd() external view returns (uint256); /** * @dev for backwards compatibility with the previous DistributionManager used * @return The end of the distribution **/ function DISTRIBUTION_END() external view returns(uint256); /** * @dev Returns the data of an user on a distribution * @param user Address of the user * @param asset The address of the reference asset of the distribution * @return The new index **/ function getUserAssetData(address user, address asset) external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import {IStakedToken} from '@aave/aave-stake/contracts/interfaces/IStakedToken.sol'; interface IStakedTokenWithConfig is IStakedToken { function STAKED_TOKEN() external view returns(address); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IStakedToken { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IScaledBalanceToken { /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256); /** * @dev Returns the scaled balance of the user and the scaled total supply. * @param user The address of the user * @return The scaled balance of the user * @return The scaled balance and the scaled total supply **/ function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256); /** * @dev Returns the scaled total supply of the token. Represents sum(debt/index) * @return The scaled total supply **/ function scaledTotalSupply() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol'; interface IAaveIncentivesController is IAaveDistributionManager { event RewardsAccrued(address indexed user, uint256 amount); event RewardsClaimed( address indexed user, address indexed to, address indexed claimer, uint256 amount ); event ClaimerSet(address indexed user, address indexed claimer); /** * @dev Whitelists an address to claim the rewards on behalf of another address * @param user The address of the user * @param claimer The address of the claimer */ function setClaimer(address user, address claimer) external; /** * @dev Returns the whitelisted claimer for a certain address (0x0 if not set) * @param user The address of the user * @return The claimer address */ function getClaimer(address user) external view returns (address); /** * @dev Configure assets for a certain rewards emission * @param assets The assets to incentivize * @param emissionsPerSecond The emission for each asset */ function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external; /** * @dev Called by the corresponding asset on any update that affects the rewards distribution * @param asset The address of the user * @param userBalance The balance of the user of the asset in the lending pool * @param totalSupply The total supply of the asset in the lending pool **/ function handleAction( address asset, uint256 userBalance, uint256 totalSupply ) external; /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must * be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager * @param amount Amount of rewards to claim * @param user Address to check and claim rewards * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); /** * @dev for backward compatibility with previous implementation of the Incentives controller */ function REWARD_TOKEN() external view returns (address); }
Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. amount Amount of rewards to claim user Address to check and claim rewards to Address that will be receiving the rewards return Rewards claimed/
function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; STAKE_TOKEN.stake(to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; }
1,640,123
./full_match/5/0xCf86e56b395032163dd4Af966500e2F189f29637/sources/contracts/contracts-V6/src/StandardCampaign.sol
Close project ✅ Sender must be the campaign owner Project must fulfill the closed conditions Update state
function closeProject(uint256 _id) public { checkProjectExists(_id); require(checkIsCampaignOwner(projects[_id].parentCampaign), "E23"); require(Iupmas(updateMasterAddress).toClosedConditions(_id), "E24"); projects[_id].status = ProjectManager.ProjectStatus.Closed; }
7,070,499
// 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.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.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); } } } } // 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 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns (address); function getModuleFee(address _module, uint256 _feeType) external view returns (uint256); function isModule(address _module) external view returns (bool); function isSet(address _setToken) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns (address); } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; interface IIntegrationRegistry { function addIntegration( address _module, string memory _id, address _wrapper ) external; function getIntegrationAdapter(address _module, string memory _id) external view returns (address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns (address); function isValidIntegration(address _module, string memory _id) external view returns (bool); } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IModule * @author Set Protocol * * Interface for interacting with Modules. */ interface IModule { /** * Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title IPriceOracle * @author Set Protocol * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit( address _component, address _positionModule, int256 _realUnit ) external; function editExternalPositionData( address _component, address _positionModule, bytes calldata _data ) external; function invoke( address _target, uint256 _value, bytes calldata _data ) external returns (bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns (int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns (int256); function getComponents() external view returns (address[] memory); function getExternalPositionModules(address _component) external view returns (address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns (bytes memory); function isExternalPositionModule(address _component, address _module) external view returns (bool); function isComponent(address _component) external view returns (bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns (int256); function isInitializedModule(address _module) external view returns (bool); function isPendingModule(address _module) external view returns (bool); function isLocked() external view returns (bool); } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {ISetToken} from "../interfaces/ISetToken.sol"; interface ISetValuer { function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256); } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays * * CHANGELOG: * - 4/21/21: Added validatePairsWithArray methods */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns (bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A, ) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint256[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title ExplicitERC20 * @author Set Protocol * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom(_token, _from, _to, _quantity); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require(newBalance == existingBalance.add(_quantity), "Invalid post transfer balance"); } } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function * - 4/21/21: Added approximatelyEquals function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals( uint256 a, uint256 b, uint256 range ) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; /** * @title Invoke * @author Set Protocol * * A collection of common utility functions for interacting with the SetToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the SetToken to set approvals of the ERC20 token to a spender. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the SetToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ISetToken _setToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature( "approve(address,uint256)", _spender, _quantity ); _setToken.invoke(_token, 0, callData); } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _setToken.invoke(_token, 0, callData); } } /** * Instructs the SetToken to transfer the ERC20 token to a recipient. * The new SetToken balance must equal the existing balance less the quantity transferred * * @param _setToken SetToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ISetToken _setToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the SetToken uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken)); Invoke.invokeTransfer(_setToken, _token, _to, _quantity); // Get new balance of transferred token for SetToken uint256 newBalance = IERC20(_token).balanceOf(address(_setToken)); // Verify only the transfer quantity is subtracted require(newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance"); } } /** * Instructs the SetToken to unwrap the passed quantity of WETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _setToken.invoke(_weth, 0, callData); } /** * Instructs the SetToken to wrap the passed quantity of ETH * * @param _setToken SetToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH( ISetToken _setToken, address _weth, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _setToken.invoke(_weth, _quantity, callData); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {ExplicitERC20} from "../../lib/ExplicitERC20.sol"; import {IController} from "../../interfaces/IController.sol"; import {IModule} from "../../interfaces/IModule.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {Invoke} from "./Invoke.sol"; import {Position} from "./Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; import {ResourceIdentifier} from "./ResourceIdentifier.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title ModuleBase * @author Set Protocol * * Abstract class that houses common Module-related state and functions. * * CHANGELOG: * - 4/21/21: Delegated modifier logic to internal helpers to reduce contract size * */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidSet(ISetToken _setToken) { _validateOnlyManagerAndValidSet(_setToken); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { _validateOnlySetManager(_setToken, _caller); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { _validateOnlyValidAndInitializedSet(_setToken); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { _validateOnlyModule(_setToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { _validateOnlyValidAndPendingSet(_setToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns (address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns (address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns (uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromSetToken( ISetToken _setToken, address _token, uint256 _feeQuantity ) internal { if (_feeQuantity > 0) { _setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the SetToken */ function isSetPendingInitialization(ISetToken _setToken) internal view returns (bool) { return _setToken.isPendingModule(address(this)); } /** * Returns true if the address is the SetToken's manager */ function isSetManager(ISetToken _setToken, address _toCheck) internal view returns (bool) { return _setToken.manager() == _toCheck; } /** * Returns true if SetToken must be enabled on the controller * and module is registered on the SetToken */ function isSetValidAndInitialized(ISetToken _setToken) internal view returns (bool) { return controller.isSet(address(_setToken)) && _setToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns (bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must SetToken manager and SetToken must be valid and initialized */ function _validateOnlyManagerAndValidSet(ISetToken _setToken) internal view { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must SetToken manager */ function _validateOnlySetManager(ISetToken _setToken, address _caller) internal view { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); } /** * SetToken must be valid and initialized */ function _validateOnlyValidAndInitializedSet(ISetToken _setToken) internal view { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ISetToken _setToken) internal view { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require(controller.isModule(msg.sender), "Module must be enabled on controller"); } /** * SetToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingSet(ISetToken _setToken) internal view { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SignedSafeMath} from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title Position * @author Set Protocol * * Collection of helper functions for handling and updating SetToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the SetToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the SetToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ISetToken _setToken, address _component) internal view returns (bool) { return _setToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the SetToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits( ISetToken _setToken, address _component, uint256 _unit ) internal view returns (bool) { return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the SetToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ISetToken _setToken, address _component, address _positionModule, uint256 _unit ) internal view returns (bool) { return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the SetToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _setToken Address of SetToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition( ISetToken _setToken, address _component, uint256 _newUnit ) internal { bool isPositionFound = hasDefaultPosition(_setToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_setToken, _component)) { _setToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_setToken, _component)) { _setToken.removeComponent(_component); } } _setToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _setToken SetToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ISetToken _setToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_setToken.isComponent(_component)) { _setToken.addComponent(_component); _setToken.addExternalPositionModule(_component, _module); } else if (!_setToken.isExternalPositionModule(_component, _module)) { _setToken.addExternalPositionModule(_component, _module); } _setToken.editExternalPositionUnit(_component, _module, _newUnit); _setToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _setToken.getExternalPositionModules(_component); if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require( positionModules[0] == _module, "External positions must be 0 to remove component" ); _setToken.removeComponent(_component); } _setToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _setTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_setTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns (uint256) { int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component); return _setToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _setToken Address of the SetToken * @param _component Address of the component * @param _setTotalSupply Current SetToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ISetToken _setToken, address _component, uint256 _setTotalSupply, uint256 _componentPreviousBalance ) internal returns ( uint256, uint256, uint256 ) { uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken)); uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _setTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_setToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _setTokenSupply Supply of SetToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of SetToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _setTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; import {IController} from "../../interfaces/IController.sol"; import {IIntegrationRegistry} from "../../interfaces/IIntegrationRegistry.sol"; import {IPriceOracle} from "../../interfaces/IPriceOracle.sol"; import {ISetValuer} from "../../interfaces/ISetValuer.sol"; /** * @title ResourceIdentifier * @author Set Protocol * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 internal constant INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 internal constant PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 internal constant SET_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller */ function getSetValuer(IController _controller) internal view returns (ISetValuer) { return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID)); } } /* Copyright 2020 Set Labs 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.7.6; pragma experimental "ABIEncoderV2"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/SafeCast.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {AddressArrayUtils} from "../../lib/AddressArrayUtils.sol"; import {IController} from "../../interfaces/IController.sol"; import {ISetToken} from "../../interfaces/ISetToken.sol"; import {Invoke} from "../lib/Invoke.sol"; import {ModuleBase} from "../lib/ModuleBase.sol"; import {Position} from "../lib/Position.sol"; import {PreciseUnitMath} from "../../lib/PreciseUnitMath.sol"; /** * @title AirdropModule * @author Set Protocol * * Module that enables managers to absorb tokens sent to the SetToken into the token's positions. With each SetToken, * managers are able to specify 1) the airdrops they want to include, 2) an airdrop fee recipient, 3) airdrop fee, * and 4) whether all users are allowed to trigger an airdrop. */ contract AirdropModule is ModuleBase, ReentrancyGuard { using PreciseUnitMath for uint256; using SafeMath for uint256; using Position for uint256; using SafeCast for int256; using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; /* ============ Structs ============ */ struct AirdropSettings { address[] airdrops; // Array of tokens manager is allowing to be absorbed address feeRecipient; // Address airdrop fees are sent to uint256 airdropFee; // Percentage in preciseUnits of airdrop sent to feeRecipient (1e16 = 1%) bool anyoneAbsorb; // Boolean indicating if any address can call absorb or just the manager } /* ============ Events ============ */ event ComponentAbsorbed( ISetToken indexed _setToken, address _absorbedToken, uint256 _absorbedQuantity, uint256 _managerFee, uint256 _protocolFee ); /* ============ Modifiers ============ */ /** * Throws if claim is confined to the manager and caller is not the manager */ modifier onlyValidCaller(ISetToken _setToken) { require(_isValidCaller(_setToken), "Must be valid caller"); _; } /* ============ Constants ============ */ uint256 public constant AIRDROP_MODULE_PROTOCOL_FEE_INDEX = 0; /* ============ State Variables ============ */ mapping(ISetToken => AirdropSettings) public airdropSettings; /* ============ Constructor ============ */ // solhint-disable-next-line no-empty-blocks constructor(IController _controller) ModuleBase(_controller) {} /* ============ External Functions ============ */ /** * Absorb passed tokens into respective positions. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _tokens Array of tokens to absorb */ function batchAbsorb(ISetToken _setToken, address[] memory _tokens) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _batchAbsorb(_setToken, _tokens); } /** * Absorb specified token into position. If airdropFee defined, send portion to feeRecipient and portion to * protocol feeRecipient address. Callable only by manager unless manager has set anyoneAbsorb to true. * * @param _setToken Address of SetToken * @param _token Address of token to absorb */ function absorb(ISetToken _setToken, address _token) external nonReentrant onlyValidCaller(_setToken) onlyValidAndInitializedSet(_setToken) { _absorb(_setToken, _token); } /** * SET MANAGER ONLY. Adds new tokens to be added to positions when absorb is called. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to add */ function addAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(!isAirdropToken(_setToken, _airdrop), "Token already added."); airdropSettings[_setToken].airdrops.push(_airdrop); } /** * SET MANAGER ONLY. Removes tokens from list to be absorbed. * * @param _setToken Address of SetToken * @param _airdrop List of airdrops to remove */ function removeAirdrop(ISetToken _setToken, address _airdrop) external onlyManagerAndValidSet(_setToken) { require(isAirdropToken(_setToken, _airdrop), "Token not added."); airdropSettings[_setToken].airdrops = airdropSettings[_setToken].airdrops.remove(_airdrop); } /** * SET MANAGER ONLY. Update whether manager allows other addresses to call absorb. * * @param _setToken Address of SetToken */ function updateAnyoneAbsorb(ISetToken _setToken) external onlyManagerAndValidSet(_setToken) { airdropSettings[_setToken].anyoneAbsorb = !airdropSettings[_setToken].anyoneAbsorb; } /** * SET MANAGER ONLY. Update address manager fees are sent to. * * @param _setToken Address of SetToken * @param _newFeeRecipient Address of new fee recipient */ function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFeeRecipient != address(0), "Passed address must be non-zero"); airdropSettings[_setToken].feeRecipient = _newFeeRecipient; } /** * SET MANAGER ONLY. Update airdrop fee percentage. * * @param _setToken Address of SetToken * @param _newFee Percentage, in preciseUnits, of new airdrop fee (1e16 = 1%) */ function updateAirdropFee(ISetToken _setToken, uint256 _newFee) external onlySetManager(_setToken, msg.sender) onlyValidAndInitializedSet(_setToken) { require(_newFee < PreciseUnitMath.preciseUnit(), "Airdrop fee can't exceed 100%"); // Absorb all outstanding tokens before fee is updated _batchAbsorb(_setToken, airdropSettings[_setToken].airdrops); airdropSettings[_setToken].airdropFee = _newFee; } /** * SET MANAGER ONLY. Initialize module with SetToken and set initial airdrop tokens as well as specify * whether anyone can call absorb. * * @param _setToken Address of SetToken * @param _airdropSettings Struct of airdrop setting for Set including accepted airdrops, feeRecipient, * airdropFee, and indicating if anyone can call an absorb */ function initialize(ISetToken _setToken, AirdropSettings memory _airdropSettings) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_airdropSettings.airdrops.length > 0, "At least one token must be passed."); require(_airdropSettings.airdropFee <= PreciseUnitMath.preciseUnit(), "Fee must be <= 100%."); airdropSettings[_setToken] = _airdropSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Token's airdrop settings are deleted. * Airdrops are not absorbed. */ function removeModule() external override { delete airdropSettings[ISetToken(msg.sender)]; } /** * Get list of tokens approved to collect airdrops for the SetToken. * * @param _setToken Address of SetToken * @return Array of tokens approved for airdrops */ function getAirdrops(ISetToken _setToken) external view returns (address[] memory) { return _airdrops(_setToken); } /** * Get boolean indicating if token is approved for airdrops. * * @param _setToken Address of SetToken * @return Boolean indicating approval for airdrops */ function isAirdropToken(ISetToken _setToken, address _token) public view returns (bool) { return _airdrops(_setToken).contains(_token); } /* ============ Internal Functions ============ */ /** * Check token approved for airdrops then handle airdropped postion. */ function _absorb(ISetToken _setToken, address _token) internal { require(isAirdropToken(_setToken, _token), "Must be approved token."); _handleAirdropPosition(_setToken, _token); } function _batchAbsorb(ISetToken _setToken, address[] memory _tokens) internal { for (uint256 i = 0; i < _tokens.length; i++) { _absorb(_setToken, _tokens[i]); } } /** * Calculate amount of tokens airdropped since last absorption, then distribute fees and update position. * * @param _setToken Address of SetToken * @param _token Address of airdropped token */ function _handleAirdropPosition(ISetToken _setToken, address _token) internal { uint256 preFeeTokenBalance = ERC20(_token).balanceOf(address(_setToken)); uint256 amountAirdropped = preFeeTokenBalance.sub(_setToken.getDefaultTrackedBalance(_token)); if (amountAirdropped > 0) { (uint256 managerTake, uint256 protocolTake, uint256 totalFees) = _handleFees( _setToken, _token, amountAirdropped ); uint256 newUnit = _getPostAirdropUnit(_setToken, preFeeTokenBalance, totalFees); _setToken.editDefaultPosition(_token, newUnit); emit ComponentAbsorbed(_setToken, _token, amountAirdropped, managerTake, protocolTake); } } /** * Calculate fee total and distribute between feeRecipient defined on module and the protocol feeRecipient. * * @param _setToken Address of SetToken * @param _component Address of airdropped component * @param _amountAirdropped Amount of tokens airdropped to the SetToken * @return Amount of airdropped tokens set aside for manager fees * @return Amount of airdropped tokens set aside for protocol fees * @return Total fees paid */ function _handleFees( ISetToken _setToken, address _component, uint256 _amountAirdropped ) internal returns ( uint256, uint256, uint256 ) { uint256 airdropFee = airdropSettings[_setToken].airdropFee; if (airdropFee > 0) { uint256 managerTake = _amountAirdropped.preciseMul(airdropFee); uint256 protocolTake = ModuleBase.getModuleFee( AIRDROP_MODULE_PROTOCOL_FEE_INDEX, managerTake ); uint256 netManagerTake = managerTake.sub(protocolTake); uint256 totalFees = netManagerTake.add(protocolTake); _setToken.invokeTransfer(_component, airdropSettings[_setToken].feeRecipient, netManagerTake); ModuleBase.payProtocolFeeFromSetToken(_setToken, _component, protocolTake); return (netManagerTake, protocolTake, totalFees); } else { return (0, 0, 0); } } /** * Retrieve new unit, which is the current balance less fees paid divided by total supply */ function _getPostAirdropUnit( ISetToken _setToken, uint256 _totalComponentBalance, uint256 _totalFeesPaid ) internal view returns (uint256) { uint256 totalSupply = _setToken.totalSupply(); return totalSupply.getDefaultPositionUnit(_totalComponentBalance.sub(_totalFeesPaid)); } /** * If absorption is confined to the manager, manager must be caller */ function _isValidCaller(ISetToken _setToken) internal view returns (bool) { return airdropSettings[_setToken].anyoneAbsorb || isSetManager(_setToken, msg.sender); } function _airdrops(ISetToken _setToken) internal view returns (address[] memory) { return airdropSettings[_setToken].airdrops; } }
IModule Set Protocol Interface for interacting with Modules./
interface IModule { function removeModule() external; Copyright 2020 Set Labs Inc. pragma solidity 0.7.6; }
100,857
./full_match/42/0x49cc49a795C11d84E3519f71bF82836d4540ff13/sources/browser/universbase.sol
The address of the fusioning contract that is used to implement the fusion
function setFusionContractAddress(address _address) external onlyOwner { fusionInterface = FusionInterface(_address); }
9,578,434