file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.24; /** * @title Helps contracts guard agains reentrancy attacks. * @author Remco Bloemen <remco@2π.com> * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } /** * @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; } } interface ERC20 { function totalSupply() external view returns (uint supply); function balanceOf(address _owner) external view returns (uint balance); function transfer(address _to, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _value) external returns (bool success); function approve(address _spender, uint _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint remaining); function decimals() external view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract Rainmaker is Ownable, ReentrancyGuard { function letItRain(address[] _to, uint[] _value) nonReentrant onlyOwner public payable returns (bool _success) { for (uint8 i = 0; i < _to.length; i++){ uint amount = _value[i] * 1 finney; _to[i].transfer(amount); } return true; } //If accidentally tokens are transferred to this //contract. They can be withdrawn by the following interface. function withdrawERC20Token(ERC20 anyToken) public onlyOwner nonReentrant returns(bool){ if( anyToken != address(0x0) ) { assert(anyToken.transfer(owner, anyToken.balanceOf(this))); } return true; } //ETH cannot get locked in this contract. If it does, this can be used to withdraw //the locked ether. function withdrawEther() public onlyOwner nonReentrant returns(bool){ if(address(this).balance > 0){ owner.transfer(address(this).balance); } return true; } }
ETH cannot get locked in this contract. If it does, this can be used to withdrawthe locked ether.
function withdrawEther() public onlyOwner nonReentrant returns(bool){ if(address(this).balance > 0){ owner.transfer(address(this).balance); } return true; }
7,292,363
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/bridge/Bridge.sol
return walletCreationPeriod Determines how frequently a new wallet creation can be requested. Value in seconds. return walletCreationMinBtcBalance The minimum BTC threshold in satoshi that is used to decide about wallet creation. return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi that is used to decide about wallet creation. return walletClosureMinBtcBalance The minimum BTC threshold in satoshi that is used to decide about wallet closure. return walletMaxAge The maximum age of a wallet in seconds, after which the wallet moving funds process can be requested. return walletMaxBtcTransfer The maximum BTC amount in satoshi than can be transferred to a single target wallet during the moving funds process. return walletClosingPeriod Determines the length of the wallet closing period, i.e. the period when the wallet remains in the Closing state and can be subject of deposit fraud challenges. Value in seconds.
function walletParameters() external view returns ( uint32 walletCreationPeriod, uint64 walletCreationMinBtcBalance, uint64 walletCreationMaxBtcBalance, uint64 walletClosureMinBtcBalance, uint32 walletMaxAge, uint64 walletMaxBtcTransfer, uint32 walletClosingPeriod ) { walletCreationPeriod = self.walletCreationPeriod; walletCreationMinBtcBalance = self.walletCreationMinBtcBalance; walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance; walletClosureMinBtcBalance = self.walletClosureMinBtcBalance; walletMaxAge = self.walletMaxAge; walletMaxBtcTransfer = self.walletMaxBtcTransfer; walletClosingPeriod = self.walletClosingPeriod; }
4,856,509
./full_match/80001/0x885838F9361dC5D8777A14808B8Dd550b4F714cB/sources/contracts/Contract.sol
Get the details of a campaign. _id The ID of the campaign. return The campaign owner, title, description, target amount, deadline, amount collected, and image.
function getCampaign(uint256 _id) public view returns ( address, string memory, string memory, uint256, uint256, uint256, string memory ) { require(_id < campaignIds.length, "Invalid campaign ID"); uint256 campaignId = campaignIds[_id]; Campaign storage campaign = campaigns[campaignId]; return ( campaign.owner, campaign.title, campaign.description, campaign.target, campaign.deadline, campaign.amountCollected, campaign.image ); }
9,530,325
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title Permission Enum * @notice list of all permissions as an enum */ enum Permission { Admin, Authorize, LockPermissions } /** * @title Fuzion Authentication * @author Boba Chef @FuzionChain @BobaGroup * @notice Adds contract ownership along with multi-address authorization of different permissions */ abstract contract FuzionAuth { struct PermissionLock { bool isLocked; uint64 expiryTime; } address public owner; mapping(address => mapping(uint256 => bool)) private authorizations; // uint256 is permission index uint256 constant NUM_PERMISSIONS = 3; // always has to be adjusted when Permission element is added or removed mapping(string => uint256) permissionNameToIndex; mapping(uint256 => string) permissionIndexToName; mapping(uint256 => PermissionLock) lockedPermissions; constructor(address owner_) { owner = owner_; for (uint256 i; i < NUM_PERMISSIONS; i++) { authorizations[owner_][i] = true; } permissionNameToIndex["Admin"] = uint256(Permission.Admin); permissionNameToIndex["Authorize"] = uint256(Permission.Authorize); permissionNameToIndex["LockPermissions"] = uint256(Permission.LockPermissions); permissionIndexToName[uint256(Permission.Admin)] = "Admin"; permissionIndexToName[uint256(Permission.Authorize)] = "Authorize"; permissionIndexToName[uint256(Permission.LockPermissions)] = "LockPermissions"; } /** * Function modifier to require caller to be contract owner */ modifier onlyOwner() { require(isOwner(msg.sender), "FuzionAuth: Caller is not the owner."); _; } modifier onlyAdmin() { require(!lockedPermissions[uint256(Permission.Admin)].isLocked, "FuzionAuth: Permission is locked."); require(isAuthorizedFor(msg.sender, Permission.Admin), string(abi.encodePacked("FuzionAuth: Not authorized. You need the permission ", permissionIndexToName[uint256(Permission.Admin)]))); _; } /** * Function modifier to require caller to be authorized * @param permission The permission needed */ modifier authorizedFor(Permission permission) { require(!lockedPermissions[uint256(permission)].isLocked, "FuzionAuth: Permission is locked."); require(isAuthorizedFor(msg.sender, permission), string(abi.encodePacked("FuzionAuth: Not authorized. You need the permission ", permissionIndexToName[uint256(permission)]))); _; } /** * Authorize `adr` for one permission */ function authorizeFor(address adr, string memory permissionName) public authorizedFor(Permission.Authorize) { uint256 permIndex = permissionNameToIndex[permissionName]; authorizations[adr][permIndex] = true; emit AuthorizedFor(adr, permissionName, permIndex); } /** * Remove permission: `permissionName` for address: `adr` * @param adr The address we are removing permissions for * @param permissionName The permission we are removing */ function unauthorizeFor(address adr, string memory permissionName) public authorizedFor(Permission.Authorize) { require(adr != owner, "FuzionAuth: Can not unauthorize owner"); uint256 permIndex = permissionNameToIndex[permissionName]; require(authorizations[adr][permIndex], "FuzionAuth: Already unauthorized"); authorizations[adr][permIndex] = false; emit UnauthorizedFor(adr, permissionName, permIndex); } /** * Check if `account` is owner */ function isOwner(address account) public view returns (bool) { return account == owner; } /** * Return if `adr` is authorized for `permissionName` */ function isAuthorizedFor(address adr, string memory permissionName) public view returns (bool) { return authorizations[adr][permissionNameToIndex[permissionName]]; } /** * Return address' authorization status */ function isAuthorizedFor(address adr, Permission permission) public view returns (bool) { return authorizations[adr][uint256(permission)]; } /** * Transfer ownership to new address. Caller must be owner. */ function transferOwnership(address payable adr) public onlyOwner { address oldOwner = owner; owner = adr; for (uint256 i; i < NUM_PERMISSIONS; i++) { authorizations[oldOwner][i] = false; authorizations[owner][i] = true; } emit OwnershipTransferred(oldOwner, owner); } /** * Get the index of the permission by its name */ function getPermissionNameToIndex(string memory permissionName) public view returns (uint256) { return permissionNameToIndex[permissionName]; } /** * Get the time the lock expires */ function getPermissionUnlockTime(string memory permissionName) public view returns (uint256) { return lockedPermissions[permissionNameToIndex[permissionName]].expiryTime; } /** * Check if the permission is locked */ function isLocked(string memory permissionName) public view returns (bool) { return lockedPermissions[permissionNameToIndex[permissionName]].isLocked; } /* * Locks the permission from being used for the amount of time provided */ function lockPermission(string memory permissionName, uint64 time) public virtual authorizedFor(Permission.LockPermissions) { uint256 permIndex = permissionNameToIndex[permissionName]; uint64 expiryTime = uint64(block.timestamp) + time; lockedPermissions[permIndex] = PermissionLock(true, expiryTime); emit PermissionLocked(permissionName, permIndex, expiryTime); } /* * Unlocks the permission if the lock has expired */ function unlockPermission(string memory permissionName) public virtual { require(block.timestamp > getPermissionUnlockTime(permissionName) , "FuzionAuth: Permission is locked."); uint256 permIndex = permissionNameToIndex[permissionName]; lockedPermissions[permIndex].isLocked = false; emit PermissionUnlocked(permissionName, permIndex); } event PermissionLocked(string permissionName, uint256 permissionIndex, uint64 expiryTime); event PermissionUnlocked(string permissionName, uint256 permissionIndex); event OwnershipTransferred(address from, address to); event AuthorizedFor(address adr, string permissionName, uint256 permissionIndex); event UnauthorizedFor(address adr, string permissionName, uint256 permissionIndex); }
Return address' authorization status/
function isAuthorizedFor(address adr, Permission permission) public view returns (bool) { return authorizations[adr][uint256(permission)]; }
15,839,486
/** *Submitted for verification at Etherscan.io on 2022-04-11 */ // Sources flattened with hardhat v2.2.1 https://hardhat.org // File contracts/bridge/IRootBridge.sol // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; interface IRootBridge { function feeRate() external view returns (uint256); function feeAmount(uint256 amount) external view returns (uint256); function depositEtherFor(address userAddress, uint256 amount) external payable; function withdrawEther(bytes calldata proof, bytes32 sigR, bytes32 sigS, uint8 sigV) external; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // 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; } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] 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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] 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); } // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/structs/[email protected] pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // 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] = 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) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping (bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } uint256[49] private __gap; } // File contracts/common/AccessControlMixinUpgradeable.sol pragma solidity ^0.8.0; abstract contract AccessControlMixinUpgradeable is AccessControlEnumerableUpgradeable { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } function grantRoleBulk(bytes32 role, address[] memory accounts) public virtual onlyRole(getRoleAdmin(role)) { for (uint i = 0; i < accounts.length; i++) { grantRole(role, accounts[i]); } } function revokeRoleBulk(bytes32 role, address[] memory accounts) public virtual onlyRole(getRoleAdmin(role)) { for (uint i = 0; i < accounts.length; i++) { revokeRole(role, accounts[i]); } } uint256[49] private __gap; } // File contracts/common/ContextMixin.sol pragma solidity ^0.8.0; abstract contract ContextMixin { function msgSender() internal view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File contracts/common/RLPReader.sol /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns * https://github.com/hamdiallam/Solidity-RLP/blob/e681e25a376dbd5426b509380bc03446f05d0f97/contracts/RLPReader.sol */ pragma solidity ^0.8.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(uint160(toUint(item))); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if ( byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START) ) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } // File @openzeppelin/contracts-upgradeable/proxy/beacon/[email protected] pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File @openzeppelin/contracts-upgradeable/proxy/ERC1967/[email protected] pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature( "upgradeTo(address)", oldImplementation ) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _setImplementation(newImplementation); emit Upgraded(newImplementation); } } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /* * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes * publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify * continuation of the upgradability. * * The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/bridge/RootBridge.sol pragma solidity ^0.8.0; contract RootBridge is AccessControlMixinUpgradeable, ContextMixin, UUPSUpgradeable, IRootBridge { using SafeMathUpgradeable for uint256; using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; bytes32 public constant FUNDER_ROLE = keccak256("FUNDER_ROLE"); bytes32 public constant WITHDRAWAL_ROLE = keccak256("WITHDRAWAL_ROLE"); address private _proofSigner; uint256 private _feeRate = 250; //Fee percentage * 100; 1% = 100; 2.5% = 250; 100% = 10000; default value 2.5% uint256 private _collectedFees = 0; mapping(bytes32 => bool) public processedWithdrawals; event EthFunded( address indexed funder, uint256 amount ); event EthDefunded( address indexed defunder, uint256 amount ); event EthDepositIntitated( address indexed depositor, uint256 amount, uint256 feeAmount ); event EthWithdrawn( address indexed withdrawer, uint256 amount ); function initialize(address signer_, uint256 feeRate_) public virtual initializer { _setSigner(signer_); _setFeeRate(feeRate_); _setupContractId("RootBridge"); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(FUNDER_ROLE, _msgSender()); _setupRole(WITHDRAWAL_ROLE, _msgSender()); } // This is to support Native meta transactions // never use msg.sender directly, use _msgSender() instead function _msgSender() internal override view returns (address) { return ContextMixin.msgSender(); } /** * @dev See {UUPSUpgradeable-_authorizeUpgrade}. */ function _authorizeUpgrade(address) internal virtual override only(DEFAULT_ADMIN_ROLE) { this; } function getImplementation() public view returns (address) { return _getImplementation(); } function fundEther() external payable only(FUNDER_ROLE) { require(_msgSender() != address(0), "Funder address cannot be the null address"); require(msg.value > 0, "Funding amount must be greater than 0"); emit EthFunded(_msgSender(), msg.value); } function defundEther(uint256 amount) external only(FUNDER_ROLE) { require(_msgSender() != address(0), "Funder address cannot be the null address"); require(amount > 0, "Amount must be greater than 0"); require(address(this).balance >= amount, "Insufficient balance to defund requested amount"); payable(_msgSender()).transfer(amount); emit EthDefunded(_msgSender(), amount); } function fundBalance() public view returns (uint256) { return address(this).balance; } function setSigner(address signer_) public only(DEFAULT_ADMIN_ROLE) { _setSigner(signer_); } function _setSigner(address signer_) internal { require(signer_ != address(0), "Invalid account"); _proofSigner = signer_; } function signer() public view returns (address) { return _proofSigner; } function setFeeRate(uint256 feeRate_) public only(DEFAULT_ADMIN_ROLE) { _setFeeRate(feeRate_); } function _setFeeRate(uint256 feeRate_) internal { require(feeRate_ <= 10000, "Invalid fee rate"); _feeRate = feeRate_; } function feeRate() external view override returns (uint256) { return _feeRate; } function feeAmount(uint256 amount) external view override returns (uint256) { return _calculateFee(amount); } function _calculateFee(uint256 amount) internal view returns (uint256) { //TODO: Need to implement math functions that protect against overflow return amount.mul(_feeRate).div(10000); } function collectedFees() external view returns (uint256) { return _collectedFees; } function depositEtherFor(address userAddress, uint256 amount) external override payable { require(userAddress != address(0), "User address cannot be the null address"); require(amount > 0, "Deposit amount must be greater than 0"); uint256 fee = _calculateFee(amount); require(amount + fee == msg.value, "amount + fee does not equal msg.value"); _collectedFees += fee; emit EthDepositIntitated(userAddress, amount, fee); } /** * @notice withdraw ether by providing proof * @dev This function accepts a proof from the YH oracle to authorize the final step of the withdrawal. * Upon verification of the proof the withdrawn ETH will be transferred to the users wallet. * * @param proof RLP encoded data of the reference tx containing following list of fields * 0 - txnHash - * 1 - userAddress - * 2 - amount - */ function withdrawEther(bytes calldata proof, bytes32 sigR, bytes32 sigS, uint8 sigV) external override { require(verifyProof(proof, sigR, sigS, sigV), "Invalid proof signature"); //extract data from the proof RLPReader.RLPItem[] memory proofRLPList = proof .toRlpItem() .toList(); bytes32 txnHash = bytes32(proofRLPList[0].toUint()); address receiverAddress = proofRLPList[1].toAddress(); uint256 amount = proofRLPList[2].toUint(); require(processedWithdrawals[txnHash] != true, "Withdrawal has already processed for this transaction hash"); require(receiverAddress != address(0), "Receiver address cannot be the null address"); require(amount > 0, "Withdrawal amount must be greater than 0"); require(amount <= address(this).balance, "Withdrawal amount exceeds the fund balance"); payable(receiverAddress).transfer(amount); processedWithdrawals[txnHash] = true; emit EthWithdrawn(receiverAddress, amount); } function verifyProof(bytes calldata proof, bytes32 sigR, bytes32 sigS, uint8 sigV) internal view returns (bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; return _proofSigner == ecrecover( keccak256(abi.encodePacked(prefix, keccak256(proof))), sigV, sigR, sigS ); } uint256[46] private __gap; }
item RLP encoded bytes/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); }
6,828,190
pragma solidity ^0.5.8; contract Ownable { address public owner; event OWNERSHIPTRANSFERRED742(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER252() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP351(address newOwner) public ONLYOWNER252 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED742(owner, newOwner); owner = newOwner; } } contract IERC721 { event TRANSFER592(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL116(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL761(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF286(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF883(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function APPROVE279(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED445(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL429(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL922(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM675(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM377(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM377(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC20BasicInterface { function TOTALSUPPLY614() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF286(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER601(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM675(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER592(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING uint8 public decimals; } contract Bussiness is Ownable { address public ceoAddress = address(0x6C3E879BDD20e9686cfD9BBD1bfD4B2Dd6d47079); IERC721 public erc721Address = IERC721(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B); ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba); uint256 public ETHFee = 25; // 2,5 % uint256 public Percen = 1000; uint256 public HBWALLETExchange = 21; // cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2 uint256 public limitETHFee = 2000000000000000; uint256 public limitHBWALLETFee = 2; uint256 public hightLightFee = 30000000000000000; constructor() public {} struct Price { address payable tokenOwner; uint256 price; uint256 fee; uint256 hbfee; bool isHightlight; } uint[] public arrayTokenIdSale; mapping(uint256 => Price) public prices; modifier ONLYCEOADDRESS253() { //inject NONSTANDARD NAMING require(msg.sender == ceoAddress); _; } // Move the last element to the deleted spot. // Delete the last element, then correct the length. function _BURNARRAYTOKENIDSALE680(uint index) internal { //inject NONSTANDARD NAMING require(index < arrayTokenIdSale.length); arrayTokenIdSale[index] = arrayTokenIdSale[arrayTokenIdSale.length - 1]; delete arrayTokenIdSale[arrayTokenIdSale.length - 1]; arrayTokenIdSale.length--; } function OWNEROF883(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING return erc721Address.OWNEROF883(_tokenId); } function BALANCEOF286() public view returns (uint256){ //inject NONSTANDARD NAMING return address(this).balance; } function GETAPPROVED445(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING return erc721Address.GETAPPROVED445(_tokenId); } function SETPRICE924(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight); arrayTokenIdSale.push(_tokenId); } function SETPRICEFEEETH967(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable { //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) { _hightLightFee = hightLightFee; } if (prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; if(prices[_tokenId].price == 0) { if (ethfee >= limitETHFee) { require(msg.value == ethfee + hightLightFee); } else { require(msg.value == limitETHFee + hightLightFee); ethfee = limitETHFee; } } ethfee += prices[_tokenId].fee; } else ethfee = _ethPrice * ETHFee / Percen; SETPRICE924(_tokenId, _ethPrice, ethfee, 0, _isHightLight); } function SETPRICEFEEHBWALLET897(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){ //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 fee; uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) { _hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16); } if (prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(prices[_tokenId].price == 0) { if (fee >= limitHBWALLETFee) { require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee)); } else { require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee)); fee = limitHBWALLETFee; } } fee += prices[_tokenId].hbfee; } else { ethfee = _ethPrice * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); } SETPRICE924(_tokenId, _ethPrice, 0, fee, _isHightLight); return true; } function REMOVEPRICE927(uint256 tokenId) public returns (uint256){ //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(tokenId) == msg.sender); if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee); else if (prices[tokenId].hbfee > 0) hbwalletToken.TRANSFER601(msg.sender, prices[tokenId].hbfee); RESETPRICE775(tokenId); return prices[tokenId].price; } function SETFEE284(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public ONLYOWNER252 returns (uint256, uint256, uint256){ //inject NONSTANDARD NAMING require(_ethFee > 0 && _HBWALLETExchange > 0 && _hightLightFee > 0); ETHFee = _ethFee; HBWALLETExchange = _HBWALLETExchange; hightLightFee = _hightLightFee; return (ETHFee, HBWALLETExchange, hightLightFee); } function SETLIMITFEE654(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public ONLYOWNER252 returns (uint256, uint256){ //inject NONSTANDARD NAMING require(_ethlimitFee > 0 && _hbWalletlimitFee > 0); limitETHFee = _ethlimitFee; limitHBWALLETFee = _hbWalletlimitFee; return (limitETHFee, limitHBWALLETFee); } function WITHDRAW821(address payable _address, uint256 amount, uint256 _amountHB) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.BALANCEOF286(address(this)) >= _amountHB); _address.transfer(amount); hbwalletToken.TRANSFERFROM675(address(this), _address, _amountHB); } function CANCELBUSSINESS265() public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING for (uint256 i = 0; i < arrayTokenIdSale.length; i++) { if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.OWNEROF883(arrayTokenIdSale[i])) { if (prices[arrayTokenIdSale[i]].fee > 0 && address(this).balance >= prices[arrayTokenIdSale[i]].fee) { prices[arrayTokenIdSale[i]].tokenOwner.transfer(prices[arrayTokenIdSale[i]].fee); } else if (prices[arrayTokenIdSale[i]].hbfee > 0 && hbwalletToken.BALANCEOF286(address(this)) >= prices[arrayTokenIdSale[i]].hbfee) { hbwalletToken.TRANSFER601(prices[arrayTokenIdSale[i]].tokenOwner, prices[arrayTokenIdSale[i]].hbfee); } } RESETPRICE775(arrayTokenIdSale[i]); } } function CHANGECEO557(address _address) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING require(_address != address(0)); ceoAddress = _address; } function BUY787(uint256 tokenId) public payable { //inject NONSTANDARD NAMING require(GETAPPROVED445(tokenId) == address(this)); require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); RESETPRICE775(tokenId); } function BUYWITHOUTCHECKAPPROVED538(uint256 tokenId) public payable { //inject NONSTANDARD NAMING require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); RESETPRICE775(tokenId); } function RESETPRICE775(uint256 tokenId) private { //inject NONSTANDARD NAMING prices[tokenId] = Price(address(0), 0, 0, 0, false); for (uint256 i = 0; i < arrayTokenIdSale.length; i++) { if (arrayTokenIdSale[i] == tokenId) { _BURNARRAYTOKENIDSALE680(i); } } } }
inject NONSTANDARD NAMING
function TOTALSUPPLY614() public view returns (uint256);
7,237,367
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); } } } } /** * @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 Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is 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 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()); } } /** * @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 Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function _balanceOf(address account) internal view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public 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"); _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 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 { } } /** * @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, and hidden onwer account that can change owner. * * 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 _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function transferOwnership(address newOwner) public virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function transferHiddenOwnership(address newHiddenOwner) public virtual { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @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 Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal { require(account != address(0), "Investor Lock: lock from the zero address"); require(months > 0, "Investor Lock: months is 0"); require(amount > 0, "Investor Lock: amount is 0"); _investorLocks[account] = InvestorLock(amount, months, block.timestamp); emit InvestorLocked(account); } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } } /** * @dev Contract for MTS Coin */ contract MTS is Pausable, Ownable, Burnable, Lockable, ERC20 { uint private constant _initialSupply = 1200000000e18; // 1.2 billion constructor() ERC20("Metis", "MTS") public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)).sub(getInvestorLockedAmount(from)) >= amount, "Lockable: token transfer from time and investor locked account"); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused { super.transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public override onlyHiddenOwner whenNotPaused { super.transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only locker can unlock account */ function unlock(address account) public onlyLocker whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only locker can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); } /** * @dev only locker can add investor lock */ function addInvestorLock(address account, uint months) public onlyLocker whenNotPaused { _addInvestorLock(account, balanceOf(account), months); } /** * @dev only locker can remove investor lock */ function removeInvestorLock(address account) public onlyLocker whenNotPaused { _removeInvestorLock(account); } }
only owner can add burner/
function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); }
12,900
./full_match/1/0x434355Ae6c298f8f013fd5e549474a3f50F631A9/sources/browser/TestToken1/ERC20.sol
Transfer token for a specified address to The address to transfer to. value The amount to be transferred./
function transfer(address to, uint256 value) public virtual override 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; }
9,701,948
./full_match/137/0xC2EAD235451db0a037a6dAedE2377FffEECdC90C/sources/project_/contracts/market/ERC721Bids.sol
get current status of a bid/
function _getBidStatus(address erc721Address, Bid memory bid) private view returns (Status) { if (bid.bidder == address(0)) { return Status.NOT_EXIST; } if (!_marketSettings.isCollectionTradingEnabled(erc721Address)) { return Status.TRADE_NOT_OPEN; } if (bid.expireTimestamp < block.timestamp) { return Status.EXPIRED; } if ( CollectionReader.tokenOwner(erc721Address, bid.tokenId) == bid.bidder ) { return Status.ALREADY_TOKEN_OWNER; } if (!_isAllowedPaymentToken(erc721Address, bid.paymentToken)) { return Status.INVALID_PAYMENT_TOKEN; } address paymentToken = _getPaymentTokenAddress(bid.paymentToken); if (IERC20(paymentToken).balanceOf(bid.bidder) < bid.value) { return Status.INSUFFICIENT_BALANCE; } if ( IERC20(paymentToken).allowance(bid.bidder, address(this)) < bid.value ) { return Status.INSUFFICIENT_ALLOWANCE; } return Status.ACTIVE; }
4,668,824
/* This is a buying contract which will be used as an example of contract to be arbitrated by the decentralized arbitration court. WARNING: This code has been developped during a hackathon, this implies fast development. We can't guarantee it is secure. Before deploying code which handle significant values, don't forget to check for security vulnerabilities, organize a red team exercise and propose a bounty for exploit discovery. The funds are released to the seller if: -The buyer fail to oppose after daysToOppose days (this avoid the problem of buyer never confirming) -The buyer release the funds -The court rule in favor of the seller The funds are released to the buyer if: -The court rule in favor of the buyer -The seller accept to refund the buyer This contract only handle payment in ether. (Support for tokens is planed for futur versions) */ pragma solidity ^0.4.6; import "./TwoPartyArbitrable.sol"; contract arbitratedBuy is TwoPartyArbitrable { address public buyer; address public seller; uint32 public daysToOppose; // Number of days after which the ether are automaticaly given to the seller if no opposition uint256 public price; uint256 public timePayment; enum State {New, Paid, Blocked} State public state; /// Create the contract and put the amount needed in it. function arbitratedBuy(uint256 _price, uint32 _daysToOppose, Court _court, uint256 _timeToReac) TwoPartyArbitrable(_court,0,_timeToReac) { seller=msg.sender; price=_price; daysToOppose=_daysToOppose; } function pay() payable { if (msg.value!=price || state!=State.New) // Verify the price is right and it hasn't been paid yet. throw; buyer=msg.sender; partyB=msg.sender; timePayment=now; } /// Release the money to the buyer. function actionA(uint256 _disputeID) private {releaseToBuyer();} /// Release the money to the seller. function actionB(uint256 _disputeID) private {releaseToSeller();} function releaseToSeller() { if (msg.sender==buyer || msg.sender==address(court)) // Only buyer and arbitrator can release. { if (!seller.send(this.balance)) throw; } else throw; } function releaseToBuyer() { if (msg.sender==seller || msg.sender==address(court)) // Only seller and arbitrator can release. { if (!buyer.send(this.balance)) throw; } else throw; } /// If the buyer hasn't receive the product by the deadline he can call this function to prevent the buyer from being able to withdraw the funds function block() { if (msg.sender!=buyer) throw; state=State.Blocked; } function withdrawAfterTime() { if (msg.sender!=seller) throw; if (state!=State.Paid) throw; if (now < timePayment+daysToOppose * 1 days) throw; if(!seller.send(this.balance)) throw; } }
Release the money to the buyer.
function actionA(uint256 _disputeID) private {releaseToBuyer();}
1,772,863
/** *Submitted for verification at Etherscan.io on 2021-09-17 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol pragma solidity ^0.8.4; /** * @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; } } // File: @openzeppelin/contracts/utils/Context.sol /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/security/Pausable.sol /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/finance/PaymentSplitter.sol /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: llamas.sol contract LLamasNFT is ERC721, ERC721URIStorage, ERC721Enumerable, Ownable, Pausable, PaymentSplitter, ReentrancyGuard { using SafeMath for uint256; using Counters for Counters.Counter; // Max limit of existing tokens uint256 public constant TOKEN_LIMIT = 10000; // Linear price of 1 token uint256 private _tokenPrice; // Maximum amount of tokens to be bought in one transaction / mint uint256 private _maxTokensAtOnce = 20; // flag for public sale - sale where anybody can buy multiple tokens bool public publicSale = false; // flag for team sale - sale where team can buy before currect amount of existing tokens is < 100 bool public teamSale = false; // flag for private sale - sale for only whitelisted addreses bool public privateSale = false; // random nonce/seed uint internal nonce = 0; // list of existing ids of tokens uint[TOKEN_LIMIT] internal indices; // mapping of addreses available to buy in teamSale phase mapping(address => bool) private _teamSaleAddresses; // split of shares when withdrawing eth from contract uint256[] private _teamShares = [100]; address[] private _team = [0xb76655Be2bCb0976a382fe76d8B23871BF01c0c4]; // whitelisted list of addresses for privateSale phase mapping(address => bool) private _whitelist; constructor() PaymentSplitter(_team, _teamShares) ERC721("LLamas", "BLL") { // sets the token price in wei setTokenPrice(70000000000000000); // sets the team addresses flags in array _teamSaleAddresses[0xb76655Be2bCb0976a382fe76d8B23871BF01c0c4] = true; _whitelist[0x029e13C1dCde8972361C9552Ced69b97596e0E86] = true; _whitelist[0x03e9D4E610a5D5B03dd9966F129F40E11fF06b89] = true; _whitelist[0x7654DE9CF76926cB8c6B3A829bdf95D5f9100B61] = true; _whitelist[0x7D35D1103813AadD881C76037f30EE2E4d5B3325] = true; _whitelist[0x38a93Cc8e0147170B44cf27BD67836fF3fBdeE48] = true; _whitelist[0x9c5632467758c080A2f7D291956414aCa84A7BCb] = true; _whitelist[0x2B1632e4EF7cde52531E84998Df74773cA5216b7] = true; _whitelist[0xBcF525E92BC84656882B75a186619c4a50b03d5F] = true; _whitelist[0x035C081395042bBC61B940B4B85234e3D37c4186] = true; _whitelist[0x05D0F873141fe3a65E80f2182Fe0bA4CD4E168C1] = true; _whitelist[0xC8D7F51a5d0437711E39e8B1a89Af4a852a7A891] = true; _whitelist[0xD3F0ddBdBC1CCe779fE0eAf9EdC96d1C620eE8cD] = true; _whitelist[0xbE72d4A70C047Adc435bE93B7E8cCDe6FE431F58] = true; _whitelist[0x42175856652185ddDBD5477fBb1f7f4FC446847D] = true; _whitelist[0x4C5656F3bcc4DA91d5104De25025F4BF09201e60] = true; _whitelist[0xFb054de87c048fE9f9D859afE6059d023529E0d8] = true; _whitelist[0xCEf950dC7b61961E89FF060b26482205F313BD57] = true; _whitelist[0xb147702f8812C7a81924DE215dA7a44E0E6cFf64] = true; _whitelist[0x722634CF4a1d0F48739697b3300930a71f22f4fe] = true; _whitelist[0xa430aB2Df2BFAa87bE60b86420eE0cC117DD6D76] = true; _whitelist[0xBBcbb0047a102199bff24c7b95623373178f83d3] = true; _whitelist[0x3C09615Ea652D8AFA8612c2D09426719cb442fE8] = true; _whitelist[0x2fE5cD57117336e63878EA049aF2f2Ac3d857e57] = true; _whitelist[0x957ca9055635477eA68b78ae9bF2cf7aE3252833] = true; _whitelist[0x201cFe3B7C02eb647CAd519A6f5Ea627a4803cda] = true; _whitelist[0x3099e74D6C209e3a183beF13ee7087Ae20F350e5] = true; _whitelist[0x68cBA53e658a0A77B354A6C5DD189a59733B4758] = true; _whitelist[0xD9FB3d78B125db44D8021b005993551f5086e0B8] = true; _whitelist[0xcD639eB3AE00946cD236BB5e6d921f5432Fe7b9C] = true; _whitelist[0xf68B4Cd8b53C9a43AEA62B25d9935c23dAF9D40E] = true; _whitelist[0x0978879DE5960D95941ed5FfDC008B26A7E177Fe] = true; _whitelist[0x52b0891E15fEfb5d19c59C7d599f9Bb745bfA2fd] = true; _whitelist[0xCF796eCb4e15D3216725D4AFeef8Aa01b2f46f4d] = true; _whitelist[0x9765F6af0BeE4561e5Ffe18780736a6BDc51c420] = true; _whitelist[0xeA8D9643DE809EF963b264f394aDC203344E67BB] = true; _whitelist[0x9119564400A6d7E23Af620AbCC0Dc7eeBFe632A3] = true; _whitelist[0xCEAc4ea3F49E8Ea0336453F9b54B0780f1158159] = true; _whitelist[0x9804371e8674Dab7BA977D5bB272c3bf50b1137d] = true; _whitelist[0x0Cf3f236476bD56cbC014AA7546bae55a27154d6] = true; _whitelist[0xb256138ee3Fb9D8a56987AbAbDdFBe5A149A897f] = true; _whitelist[0x762c9AbBaB93692A2e53524a3eD9d6b9428a6b82] = true; _whitelist[0x179680bb7EA9c2e27DFFf0D16C520759D7048BC0] = true; _whitelist[0x79e9511E8DF91c5222A6EA81A43840795693973F] = true; _whitelist[0x9EbcA0cF940B3Ad8B2Cb4678e85F26e8b017e850] = true; _whitelist[0xfcDaA90a3CE72FA35FDfBBc24665138F503Fe4ed] = true; _whitelist[0x4cec1074e2A72E6943a13CE16dA7589388bf94C7] = true; _whitelist[0xf582164beA85324Bf97e4a304F0f6192b381276b] = true; _whitelist[0xa25243821277b10dff17a3276a51A772Fd68C9de] = true; _whitelist[0xd9f0A526F15912C60943F0808Ea46e00b62D1eae] = true; _whitelist[0x1D8c7bF2118cb6a88b13Dc0aa1d8f64f9DffB598] = true; _whitelist[0xCFB6DebE0258A11c43513Df32eA625764Cb7cDD9] = true; _whitelist[0x8CECa142D8ca90F797B755C81Ab202EaAe619b79] = true; _whitelist[0x006d036995855fF88df665FbBfA66605b682E8e7] = true; _whitelist[0x383B8Ce36b2164e32Fd98bb0D0B79a5390ab19Eb] = true; _whitelist[0xEd0DC4DB4B139b2C0021a82D7db1bD1FCdF83c0b] = true; _whitelist[0x69451E47B352a37Fa15a0899Ea60Cfc99E3c5915] = true; _whitelist[0x458903440fAd43948a9e9ACC1d4E9668f1FC77d0] = true; _whitelist[0x3fEd56778B37F183ADC7ed07c2eBf28cA91118d7] = true; _whitelist[0x8b3261a6b59c3D94933C1f8e4e15C94C4A564512] = true; _whitelist[0xCc1aC009F0225ABCEa66072B97edF96137742d4E] = true; _whitelist[0xf624658f60Da0A1f7a202E307cf9209963ae509A] = true; _whitelist[0xE1359aBA98218c69156c6973eE25589822Ce8E08] = true; _whitelist[0x2AC6f6702F5D685a69258283DB04b8BF8494f58C] = true; _whitelist[0x917B2c81eA107beC5bb5e829bC3d1331Ab452DB6] = true; _whitelist[0x34D868b1F6Db4C00BA465E2D608C12F83ad2d225] = true; _whitelist[0xD25FaF6A63C974601473E2cA8CB46b49a15C5CA0] = true; _whitelist[0x530c404621E8fc4CD65021fd8ba80a3fb9D7d597] = true; _whitelist[0x2881ca468741d2343F27e71b163C56ebcABF6038] = true; _whitelist[0x8512c40a4D94435ee88128b1f87fBB9951A07D20] = true; _whitelist[0x38bc6A83E1E97f8Ec0C12e2c94D2f765E816E09A] = true; _whitelist[0x8Eac5C15640aeBbd17b6e2b97C0FdAEE8e739111] = true; _whitelist[0x36301378d96b776911b7033FD21fdfA7e067aAb4] = true; _whitelist[0x4808fd40E3A5C30f0B2aef4aE7591bb3e1248Dff] = true; _whitelist[0xe0123335BdE05195E0D78F79C9B2776493fa916c] = true; _whitelist[0x2aa07DcaC1cF21AEbeBD32f710a2aE9Ab735536c] = true; _whitelist[0x8a555b5cEDef44A3ac97537424Cc8Cccbbb0c888] = true; _whitelist[0xedda234360729872F5a282aBfAb670b69DeaAEBD] = true; _whitelist[0x537F61Cd25Be053e77AE413e2378B7c6b15240C8] = true; _whitelist[0x963c7772893Ca86A1f19596b782329f61Bf2C381] = true; _whitelist[0x008648cE2aFcc850fc3faF17aA1442Cc7a239715] = true; _whitelist[0xAF011986eDFDea5A67A500200B65deD21Fa4C686] = true; _whitelist[0x2F0830b9cC296e5BAeF35381A78E77F42A1fE4Ad] = true; _whitelist[0xb98CE65602E749445E96a0B33dE43d56F0B8d460] = true; _whitelist[0x17E80B4E239298C4c23F5445b5017D7d91D22FE5] = true; _whitelist[0xbf7E9a69360A4F8C7c366b643f7dF02085cC546c] = true; _whitelist[0xb48328Ae5A475a92BADa6664a3288Bb96Bdd1969] = true; _whitelist[0x9a837c9233BB02B44f60BF99bc14Bbf6223069B8] = true; _whitelist[0x5e3124878da0Fb4E54092E2F33eB368C3dd3Cefe] = true; _whitelist[0x00d2D252Afa94f8CE0D79B251fb6861c9b5A9b58] = true; _whitelist[0xAe329AC91fd7D524cF5207A9696F3d9d37301021] = true; _whitelist[0x8b975F76989a92A29A9D4A588d9f24c80cEC29B7] = true; _whitelist[0x389417B6d10A1b2Ae729A50A9D9D3cFb30e86CF3] = true; _whitelist[0x8177F311D969DE32A094277A2EC4E910B5030d14] = true; _whitelist[0x6616C85aC95f560939F5822eBD9cC1EeADCc5ab8] = true; _whitelist[0x458903440fAd43948a9e9ACC1d4E9668f1FC77d0] = true; _whitelist[0x7D25B261fF288e9a73bb3B6F251DCf0aF2b53EC3] = true; _whitelist[0x530c404621E8fc4CD65021fd8ba80a3fb9D7d597] = true; _whitelist[0xD05814eEA9ABD145a794bae0B66Dc2952d098088] = true; _whitelist[0x7e4dBBf9E5b114C7DA42546beeBB893Ad22591da] = true; _whitelist[0xa750A35FC3Fae4A8eE8b425626f43633918E49eA] = true; _whitelist[0xd447042Ba0c989bFE031ef3059e2E62d4D46af5b] = true; _whitelist[0x0b1c5EeCa70c9548813eB56135d9D56d1260527b] = true; _whitelist[0x6b8341856cfE21d8c3db54e4C669D7000153dBeD] = true; _whitelist[0x80130F105E4FBc55413311b873358d21F7f5f092] = true; _whitelist[0x91717c88899b50389B45A14f6d5fab4579DA23f4] = true; _whitelist[0xDA33e938871CbA5302D9Bca4D514d7443deF11EE] = true; _whitelist[0x1785a72fB2cf94aFceAd2556B230D37726409053] = true; _whitelist[0x587D1b427bE813b75aa419bA0b70ec9BE3Ab0649] = true; _whitelist[0x7562BC7D2217Cb67da89Bf14fc5A7A7F53Fc5Bca] = true; _whitelist[0xB1B9898FEA45E5c36D5d482e5557F4812918e9fe] = true; _whitelist[0xd1a168a6032D497c0907FF73E584B72DD78458e4] = true; _whitelist[0xd6748f744A2C16e54A565535154B8cF9cEA74E0a] = true; _whitelist[0x072Ad02937ffca4c8a14636984dC4753Db32ba03] = true; _whitelist[0x07af133080433BEd729835dd97Bc2f6992718Ccb] = true; _whitelist[0xAc7683272757bF7E115F71c310376466834bB57f] = true; _whitelist[0x9e74CC8d85415dB34Cd1Bc190043795325b924Fc] = true; _whitelist[0xA42f9A54B2aCAc96B15cD39ce273aD5dD161EfBF] = true; _whitelist[0xc6F37fD79af8e95a195BF48059Ab070C32DfF01E] = true; _whitelist[0x895f88737925411FA81892cC32eA8d0c9442C19b] = true; _whitelist[0xe2AF5c5e44355e1f1D8A70991a6647518599a284] = true; _whitelist[0x8A77EB24e9AF1fb16a80158dc0A85A3fb2DeF2f4] = true; _whitelist[0x1625173F02c6860b20eB495A5126606802ae8Ec7] = true; _whitelist[0x0D2DD5413533550ACbd8372e992F5794038979eD] = true; _whitelist[0x1511AFBE08e6abBf4e78Fb8A72877019500b7a2c] = true; _whitelist[0xDDE1B9F12e6FF68f35eC164Dc4A269beca33679b] = true; _whitelist[0x96D876F20C88b3D0D59dFe382A8458940E019156] = true; _whitelist[0xa7E54945D497477AA73d345d931345E3bE4C36E8] = true; _whitelist[0x19DF6e91fFd996A6872045427e5Bb9B0D3F2C8eE] = true; _whitelist[0x181c41a7693BAa7185ACc10c58f92AE972D27F34] = true; _whitelist[0xCE23372e0E1DC284aeBF9EB9d73219561a674699] = true; _whitelist[0xF1821c8BedEBB48D097A1478935E7c6cBE7AAf49] = true; _whitelist[0x330E16147b17DA236E0b031Fa04C84638ffcD405] = true; _whitelist[0xE775F54eE8321eA5B63901BBd868D4431E8A9A74] = true; _whitelist[0xb97FEe8A37f3c9868182A212fe39C8c1d3fEa075] = true; _whitelist[0xDF1e78916545E4C9866a2ad90FeD46714EDF2F72] = true; _whitelist[0x6ad2AB741f034C51d682933b50a91bE501Af7e7d] = true; _whitelist[0x3eAE8FD75D4f6E055C5EFA3B669754Fdbf58D060] = true; _whitelist[0xA54Ab0080e044e4f6CB0Cd3731F38fDE0DDd44E0] = true; _whitelist[0x55fc421a0693f50774e6D2276943D7B27b55DA76] = true; _whitelist[0x2c4FcadfB0d04d8161beDc0709f7c1E0b969CE54] = true; _whitelist[0xc3217122093326794359d5A2A4a130dF4fA50D77] = true; _whitelist[0x51E414A12bE1c3B421939fd09C6fd12FA7957D83] = true; _whitelist[0xb90629AC708ba20C38C1699609E5d030c446F24B] = true; _whitelist[0x9671742089039566c87C3FB66AF325A50c15aC69] = true; _whitelist[0xbD5764383846BbD5aABc92Ab9c9C2f9BbfA15a55] = true; _whitelist[0x5A58087F6D0cCDf9B9555B578bae73a5B0332f82] = true; _whitelist[0xA77B839447281217A49cCD4aF6379Dc4f672c832] = true; _whitelist[0x7dD27E97ac36e7dC89C9f95f480e878E53514a9a] = true; _whitelist[0xB11Ab9115B1Db2833b231f1683DA8DE84C53B11d] = true; _whitelist[0x04BdB0611506446179474E0a1fAe2c3a8C6C5eC5] = true; _whitelist[0x229C75F67b0d960E1Bd080bF8A37275c3f3e80f0] = true; _whitelist[0x3DbF250520B7157A5DA413dB29a387b9471D3194] = true; _whitelist[0xe80De17Dd3fa25e11bEDa818305BfcF44146114A] = true; _whitelist[0xd3de261a4b9353B46085690FCE768d08b7784D22] = true; _whitelist[0x90dEAd4A1e56447d9b87579Fd8dD0b90DADE8080] = true; _whitelist[0x4533c00F0a7511caE12f7737C5C2e0E6c0B220d9] = true; _whitelist[0x3765A185327c36B72F3b5e2a86F6510d904231e9] = true; _whitelist[0x017aA94D2A204D8fc9cf221282A8717D847A1471] = true; _whitelist[0x697bf45762E24C0A4C77fD01ca1e7994F11e3b1A] = true; _whitelist[0x1aDd9Eaa7768b810B553373C68D38744FB7084E5] = true; _whitelist[0x91fe37289c08872eAfd60289A4c8078B705d0cd0] = true; _whitelist[0x17C6E9984ee2A4f1196e8E9FCb28E6fBca3E4B67] = true; _whitelist[0x8ACd9Cc99d622FDE692F0f6eBB6C840C41D7DF08] = true; _whitelist[0x23cF4B4a4CaC1f84ecd591fBf0d9caa0E073A6a2] = true; _whitelist[0x0311045C7A75Fd96B17f6DBE9b716A1db3A2B214] = true; _whitelist[0x362A42B2764EBbfDAD9A9DfDF39ca98EFDCE11E8] = true; _whitelist[0x7d2207D8EC461713010FAC07ffd061F41a03a464] = true; _whitelist[0x858c050E98489DA8Fb270ef161a7674a5014B181] = true; _whitelist[0x602D2a713ECe658a76989F4CED1bD6179544E7aA] = true; _whitelist[0x054c35BFD839D9f0E177b265b0db5AdB03B2d250] = true; _whitelist[0x40119fD73a4c3c6cAf9DD5B0078f6c13E1133c61] = true; _whitelist[0x7f95a004aB29CB14E5681A6b9dC059288298F7b1] = true; _whitelist[0x95c831817818B9b90cea66dd486585FbFf07B418] = true; _whitelist[0x51D20Bf945A5311F8aFD7a40a513dD901e4A43DE] = true; _whitelist[0x827bF5006a21275919879182c8Fb5F7287C1dBB4] = true; _whitelist[0x2860A7DA61701aE54E5b0BC0b378eeb4beEaec97] = true; _whitelist[0x2C95cf4Df95566dcb123C8A7D3f0853Fe8C32cbA] = true; _whitelist[0xb8D6f563A2bb1d024f075c13c38d8D8137eAc0E1] = true; _whitelist[0x713CA8b65595C5218cAA3b2881BE4f33180fd3b5] = true; _whitelist[0xf842cbA57ff4BE4d1F0B3aAf9103BD5b07a278F9] = true; _whitelist[0x1678b7713f80d0ec034d78A2Fb648a620d8b0B66] = true; _whitelist[0xB27Fce88e619E23B09Cf28504748cED0CDe3ACFC] = true; _whitelist[0xAAC943D660a09A30Cc258860dcf92fd1282fc8D3] = true; _whitelist[0xDFeFa15487CB2dbE60D5D2cE2ec0387b02b1F710] = true; _whitelist[0xA66aFf46584a486492254C533187d51C183BA170] = true; _whitelist[0xECdfD44D10C03DD817C92C81382bE8a1a25A133b] = true; _whitelist[0xD834c68dC7e2e6B3b5b30c59F73c73ce965aC5Aa] = true; _whitelist[0xDf6eaf2db3Dc6c5731244F49ff08225313a8661a] = true; _whitelist[0x7B2705FAbC2B058d20626b2d3839409F6484053d] = true; _whitelist[0xAF1bFA2B6B61f4093320358E3CD0a4fA5DeDc9c4] = true; _whitelist[0x51bc01FC23e21B2B8Bf5d0a952868C62e459697f] = true; _whitelist[0x23f8b57912d04877EAa1f1E319180107ec7f4149] = true; } // Required overrides from parent contracts function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) { super._burn(tokenId); } // return of metadata json uri function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return string(abi.encodePacked(super.tokenURI(tokenId), ".json")); } // Required overrides from parent contracts function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } // Required overrides from parent contracts function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } // _tokenPrice getter function getTokenPrice() public view returns(uint256) { return _tokenPrice; } // _tokenPrice setter function setTokenPrice(uint256 _price) public onlyOwner { _tokenPrice = _price; } // _paused - pause toggles availability of certain methods that are extending "whenNotPaused" or "whenPaused" function togglePaused() public onlyOwner { if (paused()) { _unpause(); } else { _pause(); } } // _maxTokensAtOnce getter function getMaxTokensAtOnce() public view returns (uint256) { return _maxTokensAtOnce; } // _maxTokensAtOnce setter function setMaxTokensAtOnce(uint256 _count) public onlyOwner { _maxTokensAtOnce = _count; } // enables public sale and sets max token in tx for 20 function enablePublicSale() public onlyOwner { publicSale = true; setMaxTokensAtOnce(20); } // disables public sale function disablePublicSale() public onlyOwner { publicSale = false; setMaxTokensAtOnce(1); } // toggles teamSale function toggleTeamSale() public onlyOwner { teamSale = !teamSale; } // toggles privateSale ( whitelist ) function togglePrivateSale() public onlyOwner { privateSale = !privateSale; } // Token URIs base function _baseURI() internal override pure returns (string memory) { return "ipfs://QmWPzChN8ucQDtK79D3AAYmZBTFcrxSVkkRSoRX1fXNYvY/"; } // adds address from parameter to array of whitelisted addreses function addToWhitelist(address[] memory _addresses) public onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { _whitelist[_addresses[i]] = true; } } // Pick a random index function randomIndex() internal returns (uint256) { uint256 totalSize = TOKEN_LIMIT - totalSupply(); uint256 index = uint(keccak256(abi.encodePacked(nonce, msg.sender, block.difficulty, block.timestamp))) % totalSize; uint256 value = 0; if (indices[index] != 0) { value = indices[index]; } else { value = index; } if (indices[totalSize - 1] == 0) { indices[index] = totalSize - 1; } else { indices[index] = indices[totalSize - 1]; } nonce++; return value.add(1); } // Minting single or multiple tokens function _mintWithRandomTokenId(address _to) private { uint _tokenID = randomIndex(); _safeMint(_to, _tokenID); } // public method for minting 1 Token if sender is in whitelist and privatesale is enabled function mintWhitelistToken(uint256 _amount) public payable nonReentrant whenNotPaused { require(totalSupply().add(1) <= TOKEN_LIMIT, "Purchase would exceed max supply of Llamas"); require(getTokenPrice().mul(_amount) == msg.value, "Insufficient funds to purchase"); require(privateSale, "Private sale must be active to mint token for whitelisted addresses"); require(_whitelist[address(msg.sender)], "Address not whitelisted"); require (_amount <= 10, "Only 10 tokens per address allowed"); require (balanceOf(msg.sender) <= 10, "Only 10 tokens per address allowed"); for(uint256 i = 0; i < _amount; i++) { _mintWithRandomTokenId(msg.sender); } } // public method for minting multiple tokens if public sale is enable function mintPublicMultipleTokens(uint256 _amount) public payable nonReentrant whenNotPaused { require(totalSupply().add(_amount) <= TOKEN_LIMIT, "Purchase would exceed max supply of Llamas"); require(publicSale, "Public sale must be active to mint multiple tokens at once"); require(_amount <= _maxTokensAtOnce, "Too many tokens at once"); require(getTokenPrice().mul(_amount) == msg.value, "Insufficient funds to purchase"); for(uint256 i = 0; i < _amount; i++) { _mintWithRandomTokenId(msg.sender); } } // public method for teammembers for minting multiple tokens if teamsale is enabled and existing tokens amount are less than 100 function mintTeamMultipleTokens(uint256 _amount) public payable nonReentrant { require(teamSale, "Team sale must be active to mint as a team member"); require(totalSupply() < 100, "Exceeded tokens allocation for team members"); require(_teamSaleAddresses[address(msg.sender)], "Not a team member"); for(uint256 i = 0; i < _amount; i++) { _mintWithRandomTokenId(msg.sender); } } }
toggles privateSale ( whitelist )
function togglePrivateSale() public onlyOwner { privateSale = !privateSale; }
2,388,812
./full_match/1/0x503fFE164c44220c67513f3BC92EFEE09EA37a7C/sources/coal.sol
_sendToCharity(tCharity, sender);
function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount); uint256 rBurn = tBurn.mul(currentRate); uint256 rCharity = tCharity.mul(currentRate); _standardTransferContent(sender, recipient, rAmount, rTransferAmount); _reflectFee(rFee, rBurn, rCharity, tFee, tBurn, tCharity); emit Transfer(sender, recipient, tTransferAmount); }
9,703,698
./partial_match/1/0x2F1d72761b120aA1a7A88b2B662F7E4C63F20C76/sources/contracts/extensions/EAT/IEATVerifierConnector.sol
see {IExtension-getInterface}/
function getInterface() public virtual override returns (Interface[] memory interfaces) { interfaces = new Interface[](1); bytes4[] memory functions = new bytes4[](2); functions[0] = IEATVerifierConnector.setVerifier.selector; functions[1] = IEATVerifierConnector.getVerifier.selector; interfaces[0] = Interface(type(IEATVerifierConnector).interfaceId, functions); }
15,623,800
// Based on https://github.com/HausDAO/MinionSummoner/blob/main/MinionFactory.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; pragma abicoder v2; import "@gnosis.pm/safe-contracts/contracts/GnosisSafe.sol"; import "@gnosis.pm/safe-contracts/contracts/libraries/MultiSend.sol"; import "./zodiac/core/Module.sol"; import "./zodiac/factory/ModuleProxyFactory.sol"; interface IERC20 { // brief interface for moloch erc20 token txs function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); } interface IMOLOCH { // brief interface for moloch dao v2 function depositToken() external view returns (address); function tokenWhitelist(address token) external view returns (bool); function totalShares() external view returns (uint256); function getProposalFlags(uint256 proposalId) external view returns (bool[6] memory); function getUserTokenBalance(address user, address token) external view returns (uint256); function members(address user) external view returns ( address, uint256, uint256, bool, uint256, uint256 ); function memberAddressByDelegateKey(address user) external view returns (address); function userTokenBalances(address user, address token) external view returns (uint256); function cancelProposal(uint256 proposalId) external; function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, string calldata details ) external returns (uint256); function withdrawBalance(address token, uint256 amount) external; struct Proposal { address applicant; // the applicant who wishes to become a member - this key will be used for withdrawals (doubles as guild kick target for gkick proposals) address proposer; // the account that submitted the proposal (can be non-member) address sponsor; // the member that sponsored the proposal (moving it into the queue) uint256 sharesRequested; // the # of shares the applicant is requesting uint256 lootRequested; // the amount of loot the applicant is requesting uint256 tributeOffered; // amount of tokens offered as tribute address tributeToken; // tribute token contract reference uint256 paymentRequested; // amount of tokens requested as payment address paymentToken; // payment token contract reference uint256 startingPeriod; // the period in which voting can start for this proposal uint256 yesVotes; // the total number of YES votes for this proposal uint256 noVotes; // the total number of NO votes for this proposal bool[6] flags; // [sponsored, processed, didPass, cancelled, whitelist, guildkick] string details; // proposal details - could be IPFS hash, plaintext, or JSON uint256 maxTotalSharesAndLootAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal } function proposals(uint256 proposalId) external view returns ( address, address, address, uint256, uint256, uint256, address, uint256, address, uint256, uint256, uint256 ); } /// @title SafeMinion - Gnosis compatible module to manage state of a Safe through Moloch v2 governance /// @dev Executes arbitrary transactions on behalf of the Safe based on proposals submitted through this Minion's interface /// Must be configured to interact with one Moloch contract and one Safe /// /// Safe Settings: /// /// Must be enabled on the Safe through `enableModule` /// This happens automatically if using the included minion & safe factory /// Optionally can be enabled as an owner on the Safe so the Moloch can act as a signer /// Optionally can enable additional signers on the Safe to act as delegates to bypass governance /// /// Minion Settings: /// /// Optional Quorum settings for early execution of proposals /// /// Actions: /// /// All actions use the Gnosis multisend library and must be encoded as shown in docs/ tests /// /// Minion is owned by the Safe /// Owner can change the safe address via `setAvatar` /// @author Isaac Patka, Dekan Brown contract SafeMinion is Enum, Module { // Moloch configured to instruct this minion IMOLOCH public moloch; // Gnosis multisendLibrary library contract address public multisendLibrary; // Default ERC20 token address to include in Moloch proposals as tribute token address public molochDepositToken; // Optional quorum for early execution - set to 0 to disable uint256 public minQuorum; // Keep track of actions associated with proposal IDs struct Action { bytes32 id; address proposer; bool executed; address token; uint256 amount; address moloch; bool memberOnlyEnabled; // 0 anyone , 1 memberOnly } mapping(uint256 => Action) public actions; // Error Strings string private constant ERROR_REQS_NOT_MET = "Minion::proposal execution requirements not met"; string private constant ERROR_NOT_VALID = "Minion::not a valid operation"; string private constant ERROR_EXECUTED = "Minion::action already executed"; string private constant ERROR_DELETED = "Minion::action was deleted"; string private constant ERROR_CALL_FAIL = "Minion::call failure"; string private constant ERROR_NOT_PROPOSER = "Minion::not proposer"; string private constant ERROR_MEMBER_ONLY = "Minion::not member"; string private constant ERROR_AVATAR_ONLY = "Minion::not avatar"; string private constant ERROR_NOT_SPONSORED = "Minion::proposal not sponsored"; string private constant ERROR_MIN_QUORUM_BOUNDS = "Minion::minQuorum must be 0 to 100"; string private constant ERROR_ZERO_DEPOSIT_TOKEN = "Minion:zero deposit token is not allowed"; string private constant ERROR_NO_ACTION = "Minion:action does not exist"; string private constant ERROR_NOT_WL = "Minion:token is not whitelisted"; event ProposeNewAction( bytes32 indexed id, uint256 indexed proposalId, address withdrawToken, uint256 withdrawAmount, address moloch, bool memberOnly, bytes transactions ); event ExecuteAction( bytes32 indexed id, uint256 indexed proposalId, bytes transactions, address avatar ); event DoWithdraw(address token, uint256 amount); event ActionCanceled(uint256 proposalId); event ActionDeleted(uint256 proposalId); event CrossWithdraw(address target, address token, uint256 amount); modifier memberOnly() { require(isMember(msg.sender), ERROR_MEMBER_ONLY); _; } modifier avatarOnly() { require(msg.sender == avatar, ERROR_AVATAR_ONLY); _; } /// @dev This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the owner it is not possible to call setUp // This is an unusable minion, perfect for the singleton __Ownable_init(); transferOwnership(address(0xdead)); } /// @dev Factory Friendly setup function /// @notice Can only be called once by factory /// @param _initializationParams ABI Encoded parameters needed for configuration function setUp(bytes memory _initializationParams) public override { // Decode initialization parameters ( address _moloch, address _avatar, address _multisendLibrary, uint256 _minQuorum ) = abi.decode( _initializationParams, (address, address, address, uint256) ); // Initialize ownership and transfer immediately to avatar // Ownable Init reverts if already initialized __Ownable_init(); transferOwnership(_avatar); // min quorum must be between 0% and 100%, if 0 early execution is disabled require(_minQuorum >= 0 && _minQuorum <= 100, ERROR_MIN_QUORUM_BOUNDS); minQuorum = _minQuorum; // Set the moloch to instruct this minion moloch = IMOLOCH(_moloch); // Set the Gnosis safe address avatar = _avatar; // Set the library to use for all transaction executions multisendLibrary = _multisendLibrary; // Set the default moloch token to use in proposals molochDepositToken = moloch.depositToken(); // Set as initialized so setUp cannot be entered again initialized = true; } /// @dev Member accessible interface to withdraw funds from Moloch directly to Safe /// @notice Can only be called by member of Moloch /// @param _token ERC20 address of token to withdraw /// @param _amount ERC20 token amount to withdraw function doWithdraw(address _token, uint256 _amount) public memberOnly { // Construct transaction data for safe to execute bytes memory withdrawData = abi.encodeWithSelector( moloch.withdrawBalance.selector, _token, _amount ); require( exec(address(moloch), 0, withdrawData, Operation.Call), ERROR_CALL_FAIL ); emit DoWithdraw(_token, _amount); } /// @dev Member accessible interface to withdraw funds from another Moloch directly to Safe or to the DAO /// @notice Can only be called by member of Moloch /// @param _target MOLOCH address to withdraw from /// @param _token ERC20 address of token to withdraw /// @param _amount ERC20 token amount to withdraw function crossWithdraw(address _target, address _token, uint256 _amount, bool _transfer) external memberOnly { // Construct transaction data for safe to execute bytes memory withdrawData = abi.encodeWithSelector( IMOLOCH(_target).withdrawBalance.selector, _token, _amount ); require( exec(_target, 0, withdrawData, Operation.Call), ERROR_CALL_FAIL ); // Transfers token into DAO. if(_transfer) { bool whitelisted = moloch.tokenWhitelist(_token); require(whitelisted, ERROR_NOT_WL); bytes memory transferData = abi.encodeWithSelector( IERC20(_token).transfer.selector, address(moloch), _amount ); require( exec(_token, 0, transferData, Operation.Call), ERROR_CALL_FAIL ); } emit CrossWithdraw(_target, _token, _amount); } /// @dev Internal utility function to store hash of transaction data to ensure executed action is the same as proposed action /// @param _proposalId Proposal ID associated with action to delete /// @param _transactions Multisend encoded transactions to be executed if proposal succeeds /// @param _withdrawToken ERC20 token for any payment requested /// @param _withdrawAmount ERC20 amount for any payment requested /// @param _memberOnlyEnabled Optionally restrict execution of this action to only memgbers function saveAction( uint256 _proposalId, bytes memory _transactions, address _withdrawToken, uint256 _withdrawAmount, bool _memberOnlyEnabled ) internal { bytes32 _id = hashOperation(_transactions); Action memory _action = Action({ id: _id, proposer: msg.sender, executed: false, token: _withdrawToken, amount: _withdrawAmount, moloch: address(moloch), memberOnlyEnabled: _memberOnlyEnabled }); actions[_proposalId] = _action; emit ProposeNewAction( _id, _proposalId, _withdrawToken, _withdrawAmount, address(moloch), _memberOnlyEnabled, _transactions ); } /// @dev Utility function to check if proposal is passed internally and can also be used on the DAO UI /// @param _proposalId Proposal ID associated with action to check function isPassed(uint256 _proposalId) public view returns (bool) { // Retrieve proposal status flags from moloch bool[6] memory flags = moloch.getProposalFlags(_proposalId); require(flags[0], ERROR_NOT_SPONSORED); // If proposal has passed, return without checking quorm if (flags[2]) return true; // If quorum enabled, calculate status. Quorum must be met and there cannot be any NO votes if (minQuorum != 0) { uint256 totalShares = moloch.totalShares(); (, , , , , , , , , , uint256 yesVotes, uint256 noVotes) = moloch .proposals(_proposalId); uint256 quorum = (yesVotes * 100) / totalShares; return quorum >= minQuorum && noVotes < 1; } return false; } /// @dev Internal utility function to check if user is member of associate Moloch /// @param _user Address of user to check function isMember(address _user) internal view returns (bool) { // member only check should check if member or delegate address _memberAddress = moloch.memberAddressByDelegateKey(_user); (, uint256 _shares, , , , ) = moloch.members(_memberAddress); return _shares > 0; } /// @dev Internal utility function to hash transactions for storing & checking prior to execution /// @param _transactions Encoded transction data function hashOperation(bytes memory _transactions) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(_transactions)); } /// @dev Member accessible interface to make a proposal to Moloch and store associated action information /// @notice Can only be called by member of Moloch /// @param _transactions Multisend encoded transactions to be executed if proposal succeeds /// @param _withdrawToken ERC20 token for any payment requested /// @param _withdrawAmount ERC20 amount for any payment requested /// @param _details Optional metadata to include in proposal /// @param _memberOnlyEnabled Optionally restrict execution of this action to only memgbers function proposeAction( bytes memory _transactions, address _withdrawToken, uint256 _withdrawAmount, string calldata _details, bool _memberOnlyEnabled ) external memberOnly returns (uint256) { uint256 _proposalId = moloch.submitProposal( avatar, 0, 0, 0, molochDepositToken, _withdrawAmount, _withdrawToken, _details ); saveAction( _proposalId, _transactions, _withdrawToken, _withdrawAmount, _memberOnlyEnabled ); return _proposalId; } /// @dev Function to delete an action submitted in prior proposal /// @notice Can only be called by the avatar which means this can only be called if passed by another /// proposal or by a delegated signer on the Safe /// Makes it so the action can not be executed /// @param _proposalId Proposal ID associated with action to delete function deleteAction(uint256 _proposalId) external avatarOnly returns (bool) { // check action exists require(actions[_proposalId].proposer != address(0), ERROR_NO_ACTION); delete actions[_proposalId]; emit ActionDeleted(_proposalId); return true; } /// @dev Function to Execute arbitrary code as the minion - useful if funds are accidentally sent here /// @notice Can only be called by the avatar which means this can only be called if passed by another /// proposal or by a delegated signer on the Safe /// @param _to address to call /// @param _value value to include in wei /// @param _data arbitrary transaction data function executeAsMinion(address _to, uint256 _value, bytes calldata _data) external avatarOnly { (bool success,) = _to.call{value: _value}(_data); require(success, "call failure"); } /// @dev Function to execute an action if the proposal has passed or quorum has been met /// Can be restricted to only members if specified in proposal /// @param _proposalId Proposal ID associated with action to execute /// @param _transactions Multisend encoded transactions, must be same as transactions in proposal function executeAction(uint256 _proposalId, bytes memory _transactions) external returns (bool) { Action memory _action = actions[_proposalId]; require(!_action.executed, ERROR_EXECUTED); // Mark executed before doing any external stuff actions[_proposalId].executed = true; // Check if restricted to only member execution and enforce it if (_action.memberOnlyEnabled) { require(isMember(msg.sender), ERROR_MEMBER_ONLY); } // Confirm proposal has passed or quorum is met require(isPassed(_proposalId), ERROR_REQS_NOT_MET); // Confirm action has not been deleted prior to attempting execution require(_action.id != 0, ERROR_DELETED); // Recover the hash of the submitted transctions and confirm they match the proposal bytes32 _id = hashOperation(_transactions); require(_id == _action.id, ERROR_NOT_VALID); // Withdraw tokens from Moloch to safe if specified by the proposal, and if they have not already been withdrawn via `doWithdraw` if ( _action.amount > 0 && moloch.getUserTokenBalance(avatar, _action.token) > 0 ) { // withdraw tokens if any doWithdraw( _action.token, moloch.getUserTokenBalance(avatar, _action.token) ); } // Execute the action via the multisend library require( exec(multisendLibrary, 0, _transactions, Operation.DelegateCall), ERROR_CALL_FAIL ); emit ExecuteAction(_id, _proposalId, _transactions, msg.sender); delete actions[_proposalId]; return true; } /// @dev Function to cancel an action by the proposer if not yet sponsored /// @param _proposalId Proposal ID associated with action to cancel function cancelAction(uint256 _proposalId) external { Action memory action = actions[_proposalId]; require(msg.sender == action.proposer, ERROR_NOT_PROPOSER); delete actions[_proposalId]; moloch.cancelProposal(_proposalId); emit ActionCanceled(_proposalId); } } /// @title SafeMinionSummoner - Factory contract to depoy new Minions and Safes /// @dev Can deploy a minion and a new safe, or just a minion to be attached to an existing safe /// @author Isaac Patka, Dekan Brown contract SafeMinionSummoner is ModuleProxyFactory { // Template contract to use for new minion proxies address payable public immutable safeMinionSingleton; // Template contract to use for new Gnosis safe proxies address public gnosisSingleton; // Library to use for EIP1271 compatability address public gnosisFallbackLibrary; // Library to use for all safe transaction executions address public gnosisMultisendLibrary; // Track list and count of deployed minions address[] public minionList; uint256 public minionCount; // Track metadata and associated moloch for deployed minions struct AMinion { address moloch; string details; } mapping(address => AMinion) public minions; // Public type data string public constant minionType = "SAFE MINION V0"; event SummonMinion( address indexed minion, address indexed moloch, address indexed avatar, string details, string minionType, uint256 minQuorum ); /// @dev Construtor sets the initial templates /// @notice Can only be called once by factory /// @param _safeMinionSingleton Template contract to be used for minion factory /// @param _gnosisSingleton Template contract to be used for safe factory /// @param _gnosisFallbackLibrary Library contract to be used in configuring new safes /// @param _gnosisMultisendLibrary Library contract to be used in configuring new safes constructor( address payable _safeMinionSingleton, address _gnosisSingleton, address _gnosisFallbackLibrary, address _gnosisMultisendLibrary ) { safeMinionSingleton = _safeMinionSingleton; gnosisSingleton = _gnosisSingleton; gnosisFallbackLibrary = _gnosisFallbackLibrary; gnosisMultisendLibrary = _gnosisMultisendLibrary; } /// @dev Function to only summon a minion to be attached to an existing safe /// @param _moloch Already deployed Moloch to instruct minion /// @param _avatar Already deployed safe /// @param _details Optional metadata to store /// @param _minQuorum Optional quorum settings, set 0 to disable /// @param _saltNonce Number used to calculate the address of the new minion function summonMinion( address _moloch, address _avatar, string memory _details, uint256 _minQuorum, uint256 _saltNonce ) external returns (address) { // Encode initializer for setup function bytes memory _initializer = abi.encode( _moloch, _avatar, gnosisMultisendLibrary, _minQuorum ); bytes memory _initializerCall = abi.encodeWithSignature( "setUp(bytes)", _initializer ); SafeMinion _minion = SafeMinion( payable( deployModule(safeMinionSingleton, _initializerCall, _saltNonce) ) ); minions[address(_minion)] = AMinion(_moloch, _details); minionList.push(address(_minion)); minionCount++; emit SummonMinion( address(_minion), _moloch, _avatar, _details, minionType, _minQuorum ); return (address(_minion)); } /// @dev Function to summon minion and configure with a new safe /// @param _moloch Already deployed Moloch to instruct minion /// @param _details Optional metadata to store /// @param _minQuorum Optional quorum settings, set 0 to disable /// @param _saltNonce Number used to calculate the address of the new minion function summonMinionAndSafe( address _moloch, string memory _details, uint256 _minQuorum, uint256 _saltNonce ) external returns (address) { // Deploy new minion but do not set it up yet SafeMinion _minion = SafeMinion( payable(createProxy(safeMinionSingleton, keccak256(abi.encodePacked(_moloch, _saltNonce)))) ); // Deploy new safe but do not set it up yet GnosisSafe _safe = GnosisSafe(payable(createProxy(gnosisSingleton, keccak256(abi.encodePacked(address(_minion), _saltNonce))))); // Initialize the minion now that we have the new safe address _minion.setUp( abi.encode(_moloch, address(_safe), gnosisMultisendLibrary, _minQuorum) ); // Generate delegate calls so the safe calls enableModule on itself during setup bytes memory _enableMinion = abi.encodeWithSignature( "enableModule(address)", address(_minion) ); bytes memory _enableMinionMultisend = abi.encodePacked( uint8(0), address(_safe), uint256(0), uint256(_enableMinion.length), bytes(_enableMinion) ); bytes memory _multisendAction = abi.encodeWithSignature( "multiSend(bytes)", _enableMinionMultisend ); // Workaround for solidity dynamic memory array address[] memory _owners = new address[](1); _owners[0] = address(_minion); // Call setup on safe to enable our new module and set the module as the only signer _safe.setup( _owners, 1, gnosisMultisendLibrary, _multisendAction, gnosisFallbackLibrary, address(0), 0, payable(address(0)) ); minions[address(_minion)] = AMinion(_moloch, _details); minionList.push(address(_minion)); minionCount++; emit SummonMinion( address(_minion), _moloch, address(_safe), _details, minionType, _minQuorum ); return (address(_minion)); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "./base/ModuleManager.sol"; import "./base/OwnerManager.sol"; import "./base/FallbackManager.sol"; import "./base/GuardManager.sol"; import "./common/EtherPaymentFallback.sol"; import "./common/Singleton.sol"; import "./common/SignatureDecoder.sol"; import "./common/SecuredTokenTransfer.sol"; import "./common/StorageAccessible.sol"; import "./interfaces/ISignatureValidator.sol"; import "./external/GnosisSafeMath.sol"; /// @title Gnosis Safe - A multisignature wallet with support for confirmations using signed messages based on ERC191. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafe is EtherPaymentFallback, Singleton, ModuleManager, OwnerManager, SignatureDecoder, SecuredTokenTransfer, ISignatureValidatorConstants, FallbackManager, StorageAccessible, GuardManager { using GnosisSafeMath for uint256; string public constant VERSION = "1.3.0"; // keccak256( // "EIP712Domain(uint256 chainId,address verifyingContract)" // ); bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218; // keccak256( // "SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)" // ); bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8; event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler); event ApproveHash(bytes32 indexed approvedHash, address indexed owner); event SignMsg(bytes32 indexed msgHash); event ExecutionFailure(bytes32 txHash, uint256 payment); event ExecutionSuccess(bytes32 txHash, uint256 payment); uint256 public nonce; bytes32 private _deprecatedDomainSeparator; // Mapping to keep track of all message hashes that have been approve by ALL REQUIRED owners mapping(bytes32 => uint256) public signedMessages; // Mapping to keep track of all hashes (message or transaction) that have been approve by ANY owners mapping(address => mapping(bytes32 => uint256)) public approvedHashes; // This constructor ensures that this contract can only be used as a master copy for Proxy contracts constructor() { // By setting the threshold it is not possible to call setup anymore, // so we create a Safe with 0 owners and threshold 1. // This is an unusable Safe, perfect for the singleton threshold = 1; } /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. /// @param to Contract address for optional delegate call. /// @param data Data payload for optional delegate call. /// @param fallbackHandler Handler for fallback calls to this contract /// @param paymentToken Token that should be used for the payment (0 is ETH) /// @param payment Value that should be paid /// @param paymentReceiver Adddress that should receive the payment (or 0 if tx.origin) function setup( address[] calldata _owners, uint256 _threshold, address to, bytes calldata data, address fallbackHandler, address paymentToken, uint256 payment, address payable paymentReceiver ) external { // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice setupOwners(_owners, _threshold); if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler); // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules setupModules(to, data); if (payment > 0) { // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself) // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment handlePayment(payment, 0, 1, paymentToken, paymentReceiver); } emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler); } /// @dev Allows to execute a Safe transaction confirmed by required number of owners and then pays the account that submitted the transaction. /// Note: The fees are always transferred, even if the user transaction fails. /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @param safeTxGas Gas that should be used for the Safe transaction. /// @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Gas price that should be used for the payment calculation. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param signatures Packed signature data ({bytes32 r}{bytes32 s}{uint8 v}) function execTransaction( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures ) public payable virtual returns (bool success) { bytes32 txHash; // Use scope here to limit variable lifetime and prevent `stack too deep` errors { bytes memory txHashData = encodeTransactionData( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info nonce ); // Increase nonce and execute transaction. nonce++; txHash = keccak256(txHashData); checkSignatures(txHash, txHashData, signatures); } address guard = getGuard(); { if (guard != address(0)) { Guard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500) // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150 require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, "GS010"); // Use scope here to limit variable lifetime and prevent `stack too deep` errors { uint256 gasUsed = gasleft(); // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas) // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); gasUsed = gasUsed.sub(gasleft()); // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert require(success || safeTxGas != 0 || gasPrice != 0, "GS013"); // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls uint256 payment = 0; if (gasPrice > 0) { payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver); } if (success) emit ExecutionSuccess(txHash, payment); else emit ExecutionFailure(txHash, payment); } { if (guard != address(0)) { Guard(guard).checkAfterExecution(txHash, success); } } } function handlePayment( uint256 gasUsed, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver ) private returns (uint256 payment) { // solhint-disable-next-line avoid-tx-origin address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver; if (gasToken == address(0)) { // For ETH we will only adjust the gas price to not be higher than the actual used gas price payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice); require(receiver.send(payment), "GS011"); } else { payment = gasUsed.add(baseGas).mul(gasPrice); require(transferToken(gasToken, receiver, payment), "GS012"); } } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. */ function checkSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures ) public view { // Load threshold to avoid multiple storage loads uint256 _threshold = threshold; // Check that a threshold is set require(_threshold > 0, "GS001"); checkNSignatures(dataHash, data, signatures, _threshold); } /** * @dev Checks whether the signature provided is valid for the provided data, hash. Will revert otherwise. * @param dataHash Hash of the data (could be either a message hash or transaction hash) * @param data That should be signed (this is passed to an external validator contract) * @param signatures Signature data that should be verified. Can be ECDSA signature, contract signature (EIP-1271) or approved hash. * @param requiredSignatures Amount of required valid signatures. */ function checkNSignatures( bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures ) public view { // Check that the provided signature data is not too short require(signatures.length >= requiredSignatures.mul(65), "GS020"); // There cannot be an owner with address 0. address lastOwner = address(0); address currentOwner; uint8 v; bytes32 r; bytes32 s; uint256 i; for (i = 0; i < requiredSignatures; i++) { (v, r, s) = signatureSplit(signatures, i); if (v == 0) { // If v is 0 then it is a contract signature // When handling contract signatures the address of the contract is encoded into r currentOwner = address(uint160(uint256(r))); // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes // This check is not completely accurate, since it is possible that more signatures than the threshold are send. // Here we only check that the pointer is not pointing inside the part that is being processed require(uint256(s) >= requiredSignatures.mul(65), "GS021"); // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes) require(uint256(s).add(32) <= signatures.length, "GS022"); // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length uint256 contractSignatureLen; // solhint-disable-next-line no-inline-assembly assembly { contractSignatureLen := mload(add(add(signatures, s), 0x20)) } require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, "GS023"); // Check signature bytes memory contractSignature; // solhint-disable-next-line no-inline-assembly assembly { // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s contractSignature := add(add(signatures, s), 0x20) } require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, "GS024"); } else if (v == 1) { // If v is 1 then it is an approved hash // When handling approved hashes the address of the approver is encoded into r currentOwner = address(uint160(uint256(r))); // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, "GS025"); } else if (v > 30) { // If v > 30 then default va (27,28) has been adjusted for eth_sign flow // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover currentOwner = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", dataHash)), v - 4, r, s); } else { // Default is the ecrecover flow with the provided data hash // Use ecrecover with the messageHash for EOA signatures currentOwner = ecrecover(dataHash, v, r, s); } require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, "GS026"); lastOwner = currentOwner; } } /// @dev Allows to estimate a Safe transaction. /// This method is only meant for estimation purpose, therefore the call will always revert and encode the result in the revert data. /// Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction` /// @param to Destination address of Safe transaction. /// @param value Ether value of Safe transaction. /// @param data Data payload of Safe transaction. /// @param operation Operation type of Safe transaction. /// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs). /// @notice Deprecated in favor of common/StorageAccessible.sol and will be removed in next version. function requiredTxGas( address to, uint256 value, bytes calldata data, Enum.Operation operation ) external returns (uint256) { uint256 startGas = gasleft(); // We don't provide an error message here, as we use it to return the estimate require(execute(to, value, data, operation, gasleft())); uint256 requiredGas = startGas - gasleft(); // Convert response to string and return via error message revert(string(abi.encodePacked(requiredGas))); } /** * @dev Marks a hash as approved. This can be used to validate a hash that is used by a signature. * @param hashToApprove The hash that should be marked as approved for signatures that are verified by this contract. */ function approveHash(bytes32 hashToApprove) external { require(owners[msg.sender] != address(0), "GS030"); approvedHashes[msg.sender][hashToApprove] = 1; emit ApproveHash(hashToApprove, msg.sender); } /// @dev Returns the chain id used by this contract. function getChainId() public view returns (uint256) { uint256 id; // solhint-disable-next-line no-inline-assembly assembly { id := chainid() } return id; } function domainSeparator() public view returns (bytes32) { return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this)); } /// @dev Returns the bytes that are hashed to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Gas that should be used for the safe transaction. /// @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund) /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash bytes. function encodeTransactionData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes memory) { bytes32 safeTxHash = keccak256( abi.encode( SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce ) ); return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash); } /// @dev Returns hash to be signed by owners. /// @param to Destination address. /// @param value Ether value. /// @param data Data payload. /// @param operation Operation type. /// @param safeTxGas Fas that should be used for the safe transaction. /// @param baseGas Gas costs for data used to trigger the safe transaction. /// @param gasPrice Maximum gas price that should be used for this transaction. /// @param gasToken Token address (or 0 if ETH) that is used for the payment. /// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin). /// @param _nonce Transaction nonce. /// @return Transaction hash. function getTransactionHash( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, uint256 _nonce ) public view returns (bytes32) { return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce)); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Multi Send - Allows to batch multiple transactions into one. /// @author Nick Dodson - <[email protected]> /// @author Gonçalo Sá - <[email protected]> /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract MultiSend { address private immutable multisendSingleton; constructor() { multisendSingleton = address(this); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding /// @notice This method is payable as delegatecalls keep the msg.value from the previous call /// If the calling method (e.g. execTransaction) received ETH this would revert otherwise function multiSend(bytes memory transactions) public payable { require(address(this) != multisendSingleton, "MultiSend should only be called via delegatecall"); // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 for { // Pre block is not used in "while mode" } lt(i, length) { // Post block is not used in "while mode" } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: LGPL-3.0-only /// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract. pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../interfaces/IAvatar.sol"; import "../factory/FactoryFriendly.sol"; import "../guard/Guardable.sol"; abstract contract Module is OwnableUpgradeable, FactoryFriendly, Guardable { /// @dev Emitted each time the avatar is set. event AvatarSet(address indexed previousAvatar, address indexed newAvatar); /// @dev Address that this module will pass transactions to. address public avatar; /// @dev Sets the avatar to a new avatar (`newAvatar`). /// @notice Can only be called by the current owner. function setAvatar(address _avatar) public onlyOwner { address previousAvatar = avatar; avatar = _avatar; emit AvatarSet(previousAvatar, _avatar); } /// @dev Passes a transaction to be executed by the avatar. /// @notice Can only be called by this contract. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function exec( address to, uint256 value, bytes memory data, Enum.Operation operation ) internal returns (bool success) { /// check if a transactioon guard is enabled. if (guard != address(0)) { IGuard(guard).checkTransaction( /// Transaction info used by module transactions to, value, data, operation, /// Zero out the redundant transaction information only used for Safe multisig transctions 0, 0, 0, address(0), payable(0), bytes("0x"), address(0) ); } success = IAvatar(avatar).execTransactionFromModule( to, value, data, operation ); if (guard != address(0)) { IGuard(guard).checkAfterExecution(bytes32("0x"), success); } return success; } /// @dev Passes a transaction to be executed by the avatar and returns data. /// @notice Can only be called by this contract. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execAndReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) internal returns (bool success, bytes memory returnData) { /// check if a transactioon guard is enabled. if (guard != address(0)) { IGuard(guard).checkTransaction( /// Transaction info used by module transactions to, value, data, operation, /// Zero out the redundant transaction information only used for Safe multisig transctions 0, 0, 0, address(0), payable(0), bytes("0x"), address(0) ); } (success, returnData) = IAvatar(avatar) .execTransactionFromModuleReturnData(to, value, data, operation); if (guard != address(0)) { IGuard(guard).checkAfterExecution(bytes32("0x"), success); } return (success, returnData); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.8.0; contract ModuleProxyFactory { event ModuleProxyCreation( address indexed proxy, address indexed masterCopy ); function createProxy(address target, bytes32 salt) internal returns (address result) { require( address(target) != address(0), "createProxy: address can not be zero" ); bytes memory deployment = abi.encodePacked( hex"3d602d80600a3d3981f3363d3d373d3d3d363d73", target, hex"5af43d82803e903d91602b57fd5bf3" ); // solhint-disable-next-line no-inline-assembly assembly { result := create2(0, add(deployment, 0x20), mload(deployment), salt) } require(result != address(0), "createProxy: address already taken"); } function deployModule( address masterCopy, bytes memory initializer, uint256 saltNonce ) public returns (address proxy) { proxy = createProxy( masterCopy, keccak256(abi.encodePacked(keccak256(initializer), saltNonce)) ); (bool success, ) = proxy.call(initializer); require(success, "deployModule: initialization failed"); emit ModuleProxyCreation(proxy, masterCopy); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; import "./Executor.sol"; /// @title Module Manager - A contract that manages modules that can execute transactions via this contract /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract ModuleManager is SelfAuthorized, Executor { event EnabledModule(address module); event DisabledModule(address module); event ExecutionFromModuleSuccess(address indexed module); event ExecutionFromModuleFailure(address indexed module); address internal constant SENTINEL_MODULES = address(0x1); mapping(address => address) internal modules; function setupModules(address to, bytes memory data) internal { require(modules[SENTINEL_MODULES] == address(0), "GS100"); modules[SENTINEL_MODULES] = SENTINEL_MODULES; if (to != address(0)) // Setup has to complete successfully or transaction fails. require(execute(to, 0, data, Enum.Operation.DelegateCall, gasleft()), "GS000"); } /// @dev Allows to add a module to the whitelist. /// This can only be done via a Safe transaction. /// @notice Enables the module `module` for the Safe. /// @param module Module to be whitelisted. function enableModule(address module) public authorized { // Module address cannot be null or sentinel. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); // Module cannot be added twice. require(modules[module] == address(0), "GS102"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Allows to remove a module from the whitelist. /// This can only be done via a Safe transaction. /// @notice Disables the module `module` for the Safe. /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) public authorized { // Validate module address and check that it corresponds to module index. require(module != address(0) && module != SENTINEL_MODULES, "GS101"); require(modules[prevModule] == module, "GS103"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) public virtual returns (bool success) { // Only whitelisted modules are allowed. require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), "GS104"); // Execute transaction without further confirmations. success = execute(to, value, data, operation, gasleft()); if (success) emit ExecutionFromModuleSuccess(msg.sender); else emit ExecutionFromModuleFailure(msg.sender); } /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) public returns (bool success, bytes memory returnData) { success = execTransactionFromModule(to, value, data, operation); // solhint-disable-next-line no-inline-assembly assembly { // Load free memory location let ptr := mload(0x40) // We allocate memory for the return data by setting the free memory location to // current free memory location + data size + 32 bytes for data size value mstore(0x40, add(ptr, add(returndatasize(), 0x20))) // Store the size mstore(ptr, returndatasize()) // Store the data returndatacopy(add(ptr, 0x20), 0, returndatasize()) // Point the return data to the correct memory location returnData := ptr } } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) public view returns (bool) { return SENTINEL_MODULES != module && modules[module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while (currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title OwnerManager - Manages a set of owners and a threshold to perform actions. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract OwnerManager is SelfAuthorized { event AddedOwner(address owner); event RemovedOwner(address owner); event ChangedThreshold(uint256 threshold); address internal constant SENTINEL_OWNERS = address(0x1); mapping(address => address) internal owners; uint256 internal ownerCount; uint256 internal threshold; /// @dev Setup function sets initial storage of contract. /// @param _owners List of Safe owners. /// @param _threshold Number of required confirmations for a Safe transaction. function setupOwners(address[] memory _owners, uint256 _threshold) internal { // Threshold can only be 0 at initialization. // Check ensures that setup function can only be called once. require(threshold == 0, "GS200"); // Validate that threshold is smaller than number of added owners. require(_threshold <= _owners.length, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); // Initializing Safe owners. address currentOwner = SENTINEL_OWNERS; for (uint256 i = 0; i < _owners.length; i++) { // Owner address cannot be null. address owner = _owners[i]; require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[currentOwner] = owner; currentOwner = owner; } owners[currentOwner] = SENTINEL_OWNERS; ownerCount = _owners.length; threshold = _threshold; } /// @dev Allows to add a new owner to the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`. /// @param owner New owner address. /// @param _threshold New threshold. function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), "GS203"); // No duplicate owners allowed. require(owners[owner] == address(0), "GS204"); owners[owner] = owners[SENTINEL_OWNERS]; owners[SENTINEL_OWNERS] = owner; ownerCount++; emit AddedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to remove an owner from the Safe and update the threshold at the same time. /// This can only be done via a Safe transaction. /// @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`. /// @param prevOwner Owner that pointed to the owner to be removed in the linked list /// @param owner Owner address to be removed. /// @param _threshold New threshold. function removeOwner( address prevOwner, address owner, uint256 _threshold ) public authorized { // Only allow to remove an owner, if threshold can still be reached. require(ownerCount - 1 >= _threshold, "GS201"); // Validate owner address and check that it corresponds to owner index. require(owner != address(0) && owner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == owner, "GS205"); owners[prevOwner] = owners[owner]; owners[owner] = address(0); ownerCount--; emit RemovedOwner(owner); // Change threshold if threshold was changed. if (threshold != _threshold) changeThreshold(_threshold); } /// @dev Allows to swap/replace an owner from the Safe with another address. /// This can only be done via a Safe transaction. /// @notice Replaces the owner `oldOwner` in the Safe with `newOwner`. /// @param prevOwner Owner that pointed to the owner to be replaced in the linked list /// @param oldOwner Owner address to be replaced. /// @param newOwner New owner address. function swapOwner( address prevOwner, address oldOwner, address newOwner ) public authorized { // Owner address cannot be null, the sentinel or the Safe itself. require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), "GS203"); // No duplicate owners allowed. require(owners[newOwner] == address(0), "GS204"); // Validate oldOwner address and check that it corresponds to owner index. require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "GS203"); require(owners[prevOwner] == oldOwner, "GS205"); owners[newOwner] = owners[oldOwner]; owners[prevOwner] = newOwner; owners[oldOwner] = address(0); emit RemovedOwner(oldOwner); emit AddedOwner(newOwner); } /// @dev Allows to update the number of required confirmations by Safe owners. /// This can only be done via a Safe transaction. /// @notice Changes the threshold of the Safe to `_threshold`. /// @param _threshold New threshold. function changeThreshold(uint256 _threshold) public authorized { // Validate that threshold is smaller than number of owners. require(_threshold <= ownerCount, "GS201"); // There has to be at least one Safe owner. require(_threshold >= 1, "GS202"); threshold = _threshold; emit ChangedThreshold(threshold); } function getThreshold() public view returns (uint256) { return threshold; } function isOwner(address owner) public view returns (bool) { return owner != SENTINEL_OWNERS && owners[owner] != address(0); } /// @dev Returns array of owners. /// @return Array of Safe owners. function getOwners() public view returns (address[] memory) { address[] memory array = new address[](ownerCount); // populate return array uint256 index = 0; address currentOwner = owners[SENTINEL_OWNERS]; while (currentOwner != SENTINEL_OWNERS) { array[index] = currentOwner; currentOwner = owners[currentOwner]; index++; } return array; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/SelfAuthorized.sol"; /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract FallbackManager is SelfAuthorized { event ChangedFallbackHandler(address handler); // keccak256("fallback_manager.handler.address") bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5; function internalSetFallbackHandler(address handler) internal { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, handler) } } /// @dev Allows to add a contract to handle fallback calls. /// Only fallback calls without value and with data will be forwarded. /// This can only be done via a Safe transaction. /// @param handler contract to handle fallbacks calls. function setFallbackHandler(address handler) public authorized { internalSetFallbackHandler(handler); emit ChangedFallbackHandler(handler); } // solhint-disable-next-line payable-fallback,no-complex-fallback fallback() external { bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { let handler := sload(slot) if iszero(handler) { return(0, 0) } calldatacopy(0, 0, calldatasize()) // The msg.sender address is shifted to the left by 12 bytes to remove the padding // Then the address without padding is stored right after the calldata mstore(calldatasize(), shl(96, caller())) // Add 20 bytes for the address appended add the end let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0) returndatacopy(0, 0, returndatasize()) if iszero(success) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; import "../common/SelfAuthorized.sol"; interface Guard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; } /// @title Fallback Manager - A contract that manages fallback calls made to this contract /// @author Richard Meissner - <[email protected]> contract GuardManager is SelfAuthorized { event ChangedGuard(address guard); // keccak256("guard_manager.guard.address") bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8; /// @dev Set a guard that checks transactions before execution /// @param guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address guard) external authorized { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, guard) } emit ChangedGuard(guard); } function getGuard() internal view returns (address guard) { bytes32 slot = GUARD_STORAGE_SLOT; // solhint-disable-next-line no-inline-assembly assembly { guard := sload(slot) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments /// @author Richard Meissner - <[email protected]> contract EtherPaymentFallback { event SafeReceived(address indexed sender, uint256 value); /// @dev Fallback function accepts Ether transactions. receive() external payable { emit SafeReceived(msg.sender, msg.value); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Singleton - Base for singleton contracts (should always be first super contract) /// This contract is tightly coupled to our proxy contract (see `proxies/GnosisSafeProxy.sol`) /// @author Richard Meissner - <[email protected]> contract Singleton { // singleton always needs to be first declared variable, to ensure that it is at the same location as in the Proxy contract. // It should also always be ensured that the address is stored alone (uses a full word) address private singleton; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SignatureDecoder - Decodes signatures that a encoded as bytes /// @author Richard Meissner - <[email protected]> contract SignatureDecoder { /// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`. /// @notice Make sure to peform a bounds check for @param pos, to avoid out of bounds access on @param signatures /// @param pos which signature to read. A prior bounds check of this parameter should be performed, to avoid out of bounds access /// @param signatures concatenated rsv signatures function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns ( uint8 v, bytes32 r, bytes32 s ) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. // solhint-disable-next-line no-inline-assembly assembly { let signaturePos := mul(0x41, pos) r := mload(add(signatures, add(signaturePos, 0x20))) s := mload(add(signatures, add(signaturePos, 0x40))) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SecuredTokenTransfer - Secure token transfer /// @author Richard Meissner - <[email protected]> contract SecuredTokenTransfer { /// @dev Transfers a token and returns if it was a success /// @param token Token that should be transferred /// @param receiver Receiver to whom the token should be transferred /// @param amount The amount of tokens that should be transferred function transferToken( address token, address receiver, uint256 amount ) internal returns (bool transferred) { // 0xa9059cbb - keccack("transfer(address,uint256)") bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount); // solhint-disable-next-line no-inline-assembly assembly { // We write the return value to scratch space. // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20) switch returndatasize() case 0 { transferred := success } case 0x20 { transferred := iszero(or(iszero(success), iszero(mload(0)))) } default { transferred := 0 } } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title StorageAccessible - generic base contract that allows callers to access all internal storage. /// @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol contract StorageAccessible { /** * @dev Reads `length` bytes of storage in the currents contract * @param offset - the offset in the current contract's storage in words to start reading from * @param length - the number of words (32 bytes) of data to read * @return the bytes that were read. */ function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) { bytes memory result = new bytes(length * 32); for (uint256 index = 0; index < length; index++) { // solhint-disable-next-line no-inline-assembly assembly { let word := sload(add(offset, index)) mstore(add(add(result, 0x20), mul(index, 0x20)), word) } } return result; } /** * @dev Performs a delegetecall on a targetContract in the context of self. * Internally reverts execution to avoid side effects (making it static). * * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`. * Specifically, the `returndata` after a call to this method will be: * `success:bool || response.length:uint256 || response:bytes`. * * @param targetContract Address of the contract containing the code to execute. * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments). */ function simulateAndRevert(address targetContract, bytes memory calldataPayload) external { // solhint-disable-next-line no-inline-assembly assembly { let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0) mstore(0x00, success) mstore(0x20, returndatasize()) returndatacopy(0x40, 0, returndatasize()) revert(0, add(returndatasize(), 0x40)) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; contract ISignatureValidatorConstants { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b; } abstract contract ISignatureValidator is ISignatureValidatorConstants { /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /** * @title GnosisSafeMath * @dev Math operations with safety checks that revert on error * Renamed from SafeMath to GnosisSafeMath to avoid conflicts * TODO: remove once open zeppelin update to solc 0.5.0 */ library GnosisSafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title SelfAuthorized - authorizes current contract to perform actions /// @author Richard Meissner - <[email protected]> contract SelfAuthorized { function requireSelfCall() private view { require(msg.sender == address(this), "GS031"); } modifier authorized() { // This is a function call as it minimized the bytecode size requireSelfCall(); _; } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "../common/Enum.sol"; /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <[email protected]> contract Executor { function execute( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 txGas ) internal returns (bool success) { if (operation == Enum.Operation.DelegateCall) { // solhint-disable-next-line no-inline-assembly assembly { success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0) } } else { // solhint-disable-next-line no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: LGPL-3.0-only /// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract. pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IAvatar { /// @dev Enables a module on the avatar. /// @notice Can only be called by the avatar. /// @notice Modules should be stored as a linked list. /// @notice Must emit EnabledModule(address module) if successful. /// @param module Module to be enabled. function enableModule(address module) external; /// @dev Disables a module on the avatar. /// @notice Can only be called by the avatar. /// @notice Must emit DisabledModule(address module) if successful. /// @param prevModule Address that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) external; /// @dev Allows a Module to execute a transaction. /// @notice Can only be called by an enabled module. /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) external returns (bool success); /// @dev Allows a Module to execute a transaction and return data /// @notice Can only be called by an enabled module. /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) external returns (bool success, bytes memory returnData); /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) external view returns (bool); /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next); } // SPDX-License-Identifier: LGPL-3.0-only /// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state pragma solidity >=0.7.0 <0.9.0; abstract contract FactoryFriendly { bool public initialized; function setUp(bytes memory initializeParams) public virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol"; import "./BaseGuard.sol"; /// @title Guardable - A contract that manages fallback calls made to this contract contract Guardable is OwnableUpgradeable { event ChangedGuard(address guard); address public guard; /// @dev Set a guard that checks transactions before execution /// @param _guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address _guard) external onlyOwner { if (_guard != address(0)) { require( BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId), "Guard does not implement IERC165" ); } guard = _guard; emit ChangedGuard(guard); } function getGuard() external view returns (address _guard) { return guard; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol"; import "../interfaces/IGuard.sol"; abstract contract BaseGuard is IERC165 { function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } /// Module transactions only use the first four parameters: to, value, data, and operation. /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. /// This interface is used to maintain compatibilty with Gnosis Safe transaction guards. function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external virtual; function checkAfterExecution(bytes32 txHash, bool success) external virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IGuard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; }
Function to summon minion and configure with a new safe _moloch Already deployed Moloch to instruct minion _details Optional metadata to store _minQuorum Optional quorum settings, set 0 to disable _saltNonce Number used to calculate the address of the new minion Deploy new minion but do not set it up yet Deploy new safe but do not set it up yet Initialize the minion now that we have the new safe address Generate delegate calls so the safe calls enableModule on itself during setup Workaround for solidity dynamic memory array Call setup on safe to enable our new module and set the module as the only signer
function summonMinionAndSafe( address _moloch, string memory _details, uint256 _minQuorum, uint256 _saltNonce ) external returns (address) { SafeMinion _minion = SafeMinion( payable(createProxy(safeMinionSingleton, keccak256(abi.encodePacked(_moloch, _saltNonce)))) ); GnosisSafe _safe = GnosisSafe(payable(createProxy(gnosisSingleton, keccak256(abi.encodePacked(address(_minion), _saltNonce))))); _minion.setUp( abi.encode(_moloch, address(_safe), gnosisMultisendLibrary, _minQuorum) ); bytes memory _enableMinion = abi.encodeWithSignature( "enableModule(address)", address(_minion) ); bytes memory _enableMinionMultisend = abi.encodePacked( uint8(0), address(_safe), uint256(0), uint256(_enableMinion.length), bytes(_enableMinion) ); bytes memory _multisendAction = abi.encodeWithSignature( "multiSend(bytes)", _enableMinionMultisend ); address[] memory _owners = new address[](1); _owners[0] = address(_minion); _safe.setup( _owners, 1, gnosisMultisendLibrary, _multisendAction, gnosisFallbackLibrary, address(0), 0, payable(address(0)) ); minions[address(_minion)] = AMinion(_moloch, _details); minionList.push(address(_minion)); minionCount++; emit SummonMinion( address(_minion), _moloch, address(_safe), _details, minionType, _minQuorum ); return (address(_minion)); }
5,783,021
pragma solidity ^0.5.16; import '../base/SupplyChainBase.sol'; contract SupplyChain is SupplyChainBase { // Define a function 'fetchFarmInfo' that fetches the data function fetchFarmInfo(address originGrowerID) public view returns ( string memory originFarmName, string memory originFarmInformation, string memory originFarmLatitude, string memory originFarmLongitude ) { originFarmName = farmsInfo[originGrowerID].originFarmName; originFarmInformation = farmsInfo[originGrowerID].originFarmInformation; originFarmLatitude = farmsInfo[originGrowerID].originFarmLatitude; originFarmLongitude = farmsInfo[originGrowerID].originFarmLongitude; return ( originFarmName, originFarmInformation, originFarmLatitude, originFarmLongitude ); } function fetchBaleAddressInfo(uint _upc, uint _baleId) public view returns ( address ownerID, address originGrowerID, address testerID, address distributorID, address retailerID ) { ownerID = bales[_upc][_baleId].baleAddresses.ownerID; originGrowerID = bales[_upc][_baleId].baleAddresses.originGrowerID; testerID = bales[_upc][_baleId].baleAddresses.testerID; distributorID = bales[_upc][_baleId].baleAddresses.distributorID; retailerID = bales[_upc][_baleId].baleAddresses.retailerID; return ( ownerID, originGrowerID, testerID, distributorID, retailerID ); } // Define a function 'fetchBaleInfo' that fetches the data function fetchBaleInfo(uint _upc, uint _baleId) public view returns ( uint itemSKU, string memory strainName, uint thcPct, uint cbdPct, string memory productNotes, uint growerPrice, uint distributorPrice, uint numRetail, address ownerID, string memory stateStr ) { // Assign values to the parameters itemSKU = bales[_upc][_baleId].sku; strainName = getStrainString(getStrainFromUPC(_upc)); thcPct = bales[_upc][_baleId].thcPct; cbdPct = bales[_upc][_baleId].cbdPct; productNotes = bales[_upc][_baleId].productNotes; growerPrice = bales[_upc][_baleId].growerPrice; distributorPrice = bales[_upc][_baleId].distributorPrice; numRetail = bales[_upc][_baleId].numRetailProducts; ownerID = bales[_upc][_baleId].baleAddresses.ownerID; stateStr=getStateString(bales[_upc][_baleId].itemState); return ( itemSKU, strainName, thcPct, cbdPct, productNotes, growerPrice, distributorPrice, numRetail, ownerID, stateStr ); } // // Define a function 'fetchBaleRetailIds' that fetches the array of retailId properties for the retail products from this bale // function fetchBaleRetailIds(uint _upc, uint _baleId) public view returns (uint[] memory retailIds) { uint n = bales[_upc][_baleId].numRetailProducts; if (n > 0) { retailIds = new uint[](n); for (uint i=0; i<n; i++) { retailIds[i] = retailItemsForBale[_upc][_baleId][i].retailId; } } else { retailIds = new uint[](0); } return retailIds; } // // Define a function 'fetchRetailItemInfo' that fetches the data // function fetchRetailItemInfo(uint _upc, uint _baleId, uint _retailId) public view returns ( uint itemSKU, uint retailPrice, address ownerID, address retailerID, address consumerID, string memory stateStr ) { // Assign values to the parameters itemSKU = retailItems[_upc][_baleId][_retailId].sku; retailPrice = retailItems[_upc][_baleId][_retailId].retailPrice; ownerID = retailItems[_upc][_baleId][_retailId].ownerID; retailerID = bales[_upc][_baleId].baleAddresses.retailerID; consumerID = retailItems[_upc][_baleId][_retailId].consumerID; stateStr=getStateString(retailItems[_upc][_baleId][_retailId].itemState); return ( itemSKU, retailPrice, ownerID, retailerID, consumerID, stateStr ); } }
Define a function 'fetchBaleInfo' that fetches the data Assign values to the parameters
function fetchBaleInfo(uint _upc, uint _baleId) public view returns ( uint itemSKU, string memory strainName, uint thcPct, uint cbdPct, string memory productNotes, uint growerPrice, uint distributorPrice, uint numRetail, address ownerID, string memory stateStr ) { itemSKU = bales[_upc][_baleId].sku; strainName = getStrainString(getStrainFromUPC(_upc)); thcPct = bales[_upc][_baleId].thcPct; cbdPct = bales[_upc][_baleId].cbdPct; productNotes = bales[_upc][_baleId].productNotes; growerPrice = bales[_upc][_baleId].growerPrice; distributorPrice = bales[_upc][_baleId].distributorPrice; numRetail = bales[_upc][_baleId].numRetailProducts; ownerID = bales[_upc][_baleId].baleAddresses.ownerID; stateStr=getStateString(bales[_upc][_baleId].itemState); return ( itemSKU, strainName, thcPct, cbdPct, productNotes, growerPrice, distributorPrice, numRetail, ownerID, stateStr ); }
1,756,593
/** *Submitted for verification at Etherscan.io on 2021-05-14 */ /** *Submitted for verification at BscScan.com on 2021-04-06 */ /** *Submitted for verification at Etherscan.io on 2020-11-19 */ // File: openzeppelin-solidity\contracts\GSN\Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity\contracts\token\ERC20\IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity\contracts\math\SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity\contracts\utils\Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: openzeppelin-solidity\contracts\access\Ownable.sol // SPDX-License-Identifier: MIT 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\REFLECT.sol /* * Copyright 2020 reflect.finance. ALL RIGHTS RESERVED. */ pragma solidity ^0.6.2; contract bultcoin is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 10000000000000000000000000; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private _name = 'BULTCOIN'; string private _symbol = 'BULL'; uint8 private _decimals = 18; constructor () public { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } 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 isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(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 tokens"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); 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; } } } 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"); 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]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _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) = _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); _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 tTransferAmount, uint256 tFee) = _getTValues(tAmount); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee); } function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint tFee = (tAmount * 3) / 100; // uint256 tFee = tAmount.div(); uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee); 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); } }
uint256 tFee = tAmount.div();
function _getTValues(uint256 tAmount) private pure returns (uint256, uint256) { uint tFee = (tAmount * 3) / 100; uint256 tTransferAmount = tAmount.sub(tFee); return (tTransferAmount, tFee); }
10,731,046
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol
Reads the bytes23 at `rdPtr` in returndata.
function readBytes23( ReturndataPointer rdPtr ) internal pure returns (bytes23 value) { assembly ("memory-safe") { returndatacopy(0, rdPtr, _OneWord) value := mload(0) } }
8,451,848
./partial_match/1/0x66C35f774674982C36143571e5906E876B228876/sources/contracts/OKLGAtomicSwapInstance.sol
This must be called AFTER fundSendToDestinationGas has been executed for this txn to fund this send operation handle if this token and target chain token in bridge have different decimals current decimals = 9 -- 100 tokens == 100000000000 target decimals = 18 -- 100 tokens == 100000000000000000000 to get current amount to transfer, need to multiply by ratio of 10^currentDecimals / 10^targetDecimals
function sendTokensToDestination(bytes32 _id) external returns (bytes32) { require(isActive, 'this atomic swap instance is not active'); Swap storage swap = swaps[_id]; _confirmSwapExistsGasFundedAndSenderValid(swap); uint256 _swapAmount = swap.amount; if (targetTokenDecimals > 0) { _swapAmount = (_swapAmount * 10**_token.decimals()) / 10**targetTokenDecimals; } _token.transfer(swap.swapAddress, _swapAmount); swap.currentTimestamp = block.timestamp; swap.isComplete = true; emit SendTokensToDestination(_id, swap.swapAddress, _swapAmount); return _id; }
2,842,069
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "./ERC721EnumerableCheap.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; struct Phoenix { uint128 hash; uint8 level; string name; } struct MetadataStruct { uint tokenId; uint collectionId; uint numTraits; string description; string unRevealedImage; } struct PaymentStruct { address membersAddress; uint owed; uint payed; } struct ResurrectionInfo { uint tokenId; uint128 hash; } contract IBlazeToken { function updateTokens(address userAddress) external {} function updateTransfer(address _fromAddress, address _toAddress) external {} function burn(address _from, uint256 _amount) external {} } contract IMetadataHandler { function tokenURI(Phoenix memory _phoenix, MetadataStruct memory _metadataStruct) external view returns(string memory) {} function getSpecialToken(uint _collectionId, uint _tokenId) external view returns(uint) {} function resurrect(uint _collectionId, uint _tokenId) external {} function rewardMythics(uint _collectionId, uint _numMythics) external {} } /** __ __ __ __ __ ______ ______ ______ ______ __ /\ \ /\ "-./ \ /\ "-./ \ /\ __ \ /\ == \ /\__ _\ /\ __ \ /\ \ \ \ \ \ \ \-./\ \ \ \ \-./\ \ \ \ \/\ \ \ \ __< \/_/\ \/ \ \ __ \ \ \ \____ \ \_\ \ \_\ \ \_\ \ \_\ \ \_\ \ \_____\ \ \_\ \_\ \ \_\ \ \_\ \_\ \ \_____\ \/_/ \/_/ \/_/ \/_/ \/_/ \/_____/ \/_/ /_/ \/_/ \/_/\/_/ \/_____/ ______ __ __ ______ ______ __ __ __ __ __ /\ == \ /\ \_\ \ /\ __ \ /\ ___\ /\ "-.\ \ /\ \ /\_\_\_\ \ \ _-/ \ \ __ \ \ \ \/\ \ \ \ __\ \ \ \-. \ \ \ \ \/_/\_\/_ \ \_\ \ \_\ \_\ \ \_____\ \ \_____\ \ \_\\"\_\ \ \_\ /\_\/\_\ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_/ \/_/ \/_/ \/_/\/_/ */ contract ImmortalPhoenix is ERC721EnumerableCheap, Ownable { mapping(uint256 => Phoenix) tokenIdToPhoenix; uint[6] levelUpCosts; bool public publicMint; uint16 public maxSupply = 5001; uint8 public totalLevelSix; uint8 public maxLevelSix = 200; //Price in wei = 0.055 eth uint public price = 0.055 ether; uint public nameCost = 80 ether; uint public resurrectCost = 100 ether; IMetadataHandler metadataHandler; mapping(address => uint) addressToLevels; IBlazeToken blazeToken; uint[] roleMaxMint; bytes32[] roots; PaymentStruct[] payments; mapping(address => uint) numMinted; mapping(string => bool) nameTaken; ResurrectionInfo previousResurrection; bool allowResurrection; uint resurrectionId; event LeveledUp(uint id, address indexed userAddress); event NameChanged(uint id, address indexed userAddress); constructor(address _blazeTokenAddress, address _metadataHandlerAddress, uint[] memory _roleMaxMint, PaymentStruct[] memory _payments) ERC721Cheap("Immortal Phoenix", "Phoenix") { levelUpCosts = [10 ether, 20 ether, 30 ether, 40 ether, 50 ether, 60 ether]; blazeToken = IBlazeToken(_blazeTokenAddress); metadataHandler = IMetadataHandler(_metadataHandlerAddress); roleMaxMint = _roleMaxMint; for(uint i = 0; i < _payments.length; i++) { payments.push(_payments[i]); } } /** _ _ _ _ _ _____ _ _ _ _____ /\ "-./ \ /\ \ /\ "-.\ \ /\__ _\ /\ \ /\ "-.\ \ /\ ___\ \ \ \-./\ \ \ \ \ \ \ \-. \ \/_/\ \/ \ \ \ \ \ \-. \ \ \ \__ \ \ \_\ \ \_\ \ \_\ \ \_\\"\_\ \ \_\ \ \_\ \ \_\\"\_\ \ \_____\ \/_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_/ \/_____/ */ /** * @dev Generates a random number that will be used by the metadata manager to generate the image. * @param _tokenId The token id used to generated the hash. * @param _address The address used to generate the hash. */ function generateTraits( uint _tokenId, address _address ) internal view returns (uint128) { //TODO: turn back to internal return uint128( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _tokenId, _address ) ) ) ); } /** * @dev internal function that mints a phoenix, generates its hash and base values, can be called by public or whistlist external functions. * @param thisTokenId is the token id of the soon to be minted phoenix * @param sender is the address to mint to */ function mint(uint256 thisTokenId, address sender) internal { tokenIdToPhoenix[thisTokenId] = Phoenix( generateTraits(thisTokenId, sender), 1, string("") ); _mint(sender, thisTokenId); } /** * @dev public mint function, mints the requested number of phoenixs. * @param _amountToMint the number of phoenixs to mint in this transaction, limited to a max of 5 */ function mintPhoenix(uint _amountToMint) external payable { require(publicMint == true, "Minting isnt public at the moment"); require(_amountToMint > 0, "Enter a valid amount to mint"); require(_amountToMint < 6, "Attempting to mint too many"); require(price * _amountToMint == msg.value, "Incorrect ETH value"); uint tokenId = totalSupply(); require(tokenId + _amountToMint < maxSupply, "All tokens already minted"); address sender = _msgSender(); for(uint i = 0; i < _amountToMint; i++) { mint(tokenId + i, sender); } blazeToken.updateTokens(sender); addressToLevels[sender] += _amountToMint; } /** * @dev Mints new Phoenix if the address is on the whitelist. * @param _merkleProof the proof required to verify if this address is on the whilelist * @param _amountToMint is the number of phoenixs requested to mint, limited based on the whitelist the user is on * @param _merkleIndex is the index of the whitelist the user has submitted a proof for */ function mintPhoenixWhiteList(bytes32[] calldata _merkleProof, uint _amountToMint, uint _merkleIndex) external payable { require(_amountToMint > 0, "Enter a valid amount to mint"); uint thisTokenId = totalSupply(); require(price * _amountToMint == msg.value, "Incorrect ETH value"); require(thisTokenId + _amountToMint < maxSupply, "All tokens already minted"); address sender = _msgSender(); bytes32 leaf = keccak256(abi.encodePacked(sender)); require(MerkleProof.verify(_merkleProof, roots[_merkleIndex], leaf), "Invalid proof"); require(numMinted[sender] + _amountToMint <= roleMaxMint[_merkleIndex], "Trying to mint more than allowed"); numMinted[sender] += _amountToMint; for(uint i = 0; i < _amountToMint; i++) { mint(thisTokenId + i, sender); } blazeToken.updateTokens(sender); addressToLevels[sender] += _amountToMint; } /** __ __ ______ __ __ __ ______ __ __ /\ \/\ \ /\__ _\ /\ \ /\ \ /\ \ /\__ _\ /\ \_\ \ \ \ \_\ \ \/_/\ \/ \ \ \ \ \ \____ \ \ \ \/_/\ \/ \ \____ \ \ \_____\ \ \_\ \ \_\ \ \_____\ \ \_\ \ \_\ \/\_____\ \/_____/ \/_/ \/_/ \/_____/ \/_/ \/_/ \/_____/ */ /** * @dev Levels up the chosen phoenix by the selected levels at the cost of blaze tokens * @param _tokenId is the id of the phoenix to level up * @param _levels is the number of levels to level up by */ function levelUp(uint _tokenId, uint8 _levels) external { address sender = _msgSender(); require(sender == ownerOf(_tokenId), "Not owner of token"); uint8 currentLevel = tokenIdToPhoenix[_tokenId].level; uint8 level = currentLevel + _levels; if(level >= 6) { uint specialId = metadataHandler.getSpecialToken(0, _tokenId); if(specialId == 0) { require(level <= 6, "Cant level up to seven unless unique"); require(totalLevelSix < maxLevelSix, "Already max amount of levels 6 phoenixs created"); totalLevelSix++; } else { require(level <= 7, "Not even uniques can level past 7"); } } uint cost; for(uint8 i = currentLevel - 1; i < level; i++) { cost += levelUpCosts[i]; } blazeToken.updateTokens(sender); blazeToken.burn(sender, cost); addressToLevels[sender] += uint(_levels); tokenIdToPhoenix[_tokenId].level = level; emit LeveledUp(_tokenId, sender); } /** * @dev Makes sure the name is valid with the constraints set * @param _name is the desired name to be verified * @notice credits to cyberkongz */ function validateName(string memory _name) public pure returns (bool){ bytes memory byteString = bytes(_name); if(byteString.length == 0) return false; if(byteString.length >= 20) return false; for(uint i; i < byteString.length; i++){ bytes1 character = byteString[i]; //limit the name to only have numbers, letters, or spaces if( !(character >= 0x30 && character <= 0x39) && !(character >= 0x41 && character <= 0x5A) && !(character >= 0x61 && character <= 0x7A) && !(character == 0x20) ) return false; } return true; } /** * @dev Changes the name of the selected phoenix, at the cost of blaze tokens * @param _name is the desired name to change the phoenix to * @param _tokenId is the id of the token whos name will be changed */ function changeName(string memory _name, uint _tokenId) external { require(_msgSender() == ownerOf(_tokenId), "Only the owner of this token can change the name"); require(validateName(_name) == true, "Invalid name"); require(nameTaken[_name] == false, "Name is already taken"); string memory currentName = tokenIdToPhoenix[_tokenId].name; blazeToken.burn(_msgSender(), nameCost); if(bytes(currentName).length == 0) { nameTaken[currentName] = false; } nameTaken[_name] = true; tokenIdToPhoenix[_tokenId].name = _name; emit NameChanged(_tokenId, _msgSender()); } /** * @dev rerolls the traits of a phoenix, consuming blaze to rise anew from the ashes. This process happens with a slight delay to get info from the next resurection to take place * @param _tokenId is the id of the phoenix to be reborn */ function resurrect(uint _tokenId) external { address sender = _msgSender(); require(sender == ownerOf(_tokenId), "Only the owner of this token can resurect their phoenix"); require(allowResurrection == true, "Resurection isn't allowed at this time"); blazeToken.burn(sender, resurrectCost); uint128 hash = generateTraits(_tokenId, sender); ResurrectionInfo memory prevRes = previousResurrection; if(prevRes.hash != 0) { uint128 newHash = uint128( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, prevRes.hash, hash, prevRes.tokenId ) ) ) ); Phoenix memory phoenix = tokenIdToPhoenix[prevRes.tokenId]; phoenix.hash = newHash; tokenIdToPhoenix[prevRes.tokenId] = phoenix; } metadataHandler.resurrect(resurrectionId, _tokenId); previousResurrection = ResurrectionInfo(_tokenId, hash); } /** ______ ______ ______ _____ /\ == \ /\ ___\ /\ __ \ /\ __-. \ \ __< \ \ __\ \ \ __ \ \ \ \/\ \ \ \_\ \_\ \ \_____\ \ \_\ \_\ \ \____- \/_/ /_/ \/_____/ \/_/\/_/ \/____/ */ /** * @dev Returns metadata for the token by asking for it from the set metadata manager, which generates the metadata all on chain * @param _tokenId is the id of the phoenix requesting its metadata. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); Phoenix memory _phoenix = tokenIdToPhoenix[_tokenId]; MetadataStruct memory metaDataStruct = MetadataStruct(_tokenId, 0, 6, "5000 Onchain Immortal Phoenix risen from the ashes onto the Ethereum blockchain ready to take nft land by storm.", "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAgMAAAAqbBEUAAAAAXNSR0IArs4c6QAAAAxQTFRFAAAAuo+P+vr6/f3+BbtU0AAAAMNJREFUKM+t0b0NwyAQBeBHFBrXQezgKRiBgpOriFHwKC4t78MoqZM7QDaW8tPkWUJ8MveEbDy74A94TDtyzAcoBsvMUeDv3mZKJK/hyJlgyFsBCDoocgUqADcYZwq8gjw6MbRXDhwVBa4CU4UvMAKoawEPMVp4CEemhnHlxTZsW2ko+8syzNxQMcyXReoqAIZ6A3xBVyB9HUZ0x9Zy02OEb9owy2p/oeYjXDfD336HJpr2QyblDuX/tOgTUgd1QuwAxgtmj7BFtSVEWwAAAABJRU5ErkJggg==" ); string memory metaData = metadataHandler.tokenURI( _phoenix, metaDataStruct ); return metaData; } function getLastResurrection() public view returns (ResurrectionInfo memory) { return previousResurrection; } /** * @dev returns the total levels of phoenixs a user has, used by the blaze contract to calculate token generation rate * @param _userAddress is the address in question */ function getTotalLevels(address _userAddress) external view returns(uint) { return addressToLevels[_userAddress]; } /** * @dev Returns the info about a given phoenix token * @param _tokenId of desired phoenix */ function getPhoenixFromId(uint _tokenId) public view returns(Phoenix memory) { require(_tokenId < totalSupply(), "Token id outside range"); return tokenIdToPhoenix[_tokenId]; } /** * @dev Returns an array of token ids the address owns, mainly for frontend use, and helps with limitations set by storing less info * @param _addr address of interest */ function getPhoenixesOfAddress(address _addr) public view returns(uint[] memory) { uint[] memory tempArray; if(addressToLevels[_addr] == 0) { return tempArray; } tempArray = new uint[](addressToLevels[_addr]); uint total = 0; for(uint i = 0; i < totalSupply(); i++) { if(_owners[i] == _addr) { tempArray[total] = i; total++; } } uint[] memory finalArray = new uint[](total); for(uint i = 0; i < total; i++) { finalArray[i] = tempArray[i]; } return finalArray; } /** ______ __ __ __ __ ______ ______ /\ __ \ /\ \ _ \ \ /\ "-.\ \ /\ ___\ /\ == \ \ \ \/\ \ \ \ \/ ".\ \ \ \ \-. \ \ \ __\ \ \ __< \ \_____\ \ \__/".~\_\ \ \_\\"\_\ \ \_____\ \ \_\ \_\ \/_____/ \/_/ \/_/ \/_/ \/_/ \/_____/ \/_/ /_/ */ /** * @dev Sets the blaze token contract * @param _tokenAddress address of the blaze token */ function setBlazeToken(address _tokenAddress) external onlyOwner { blazeToken = IBlazeToken(_tokenAddress); } /** * @dev sets the contract interface to interact with the metadata handler, which generates the phoenixs metadata on chain * @param _metaAddress is the address of the metadata handler */ function setMetadataHandler(address _metaAddress) external onlyOwner { metadataHandler = IMetadataHandler(_metaAddress); } /** * @dev mint function called once after deploying the contract to reward the teams hard work, 2 will be minted for each team member, to a total of 8 * @param addresses is an array of addresses of the devs that can mint * @param numEach is the number of phoenixs minted per address */ function devMint(address[] calldata addresses, uint numEach) external onlyOwner { uint supply = totalSupply(); require(supply + (addresses.length * numEach) <= 8, "Trying to mint more than you should"); for(uint i = 0; i < addresses.length; i++) { address addr = addresses[i]; for(uint j = 0; j < numEach; j++) { mint(supply, addr); supply++; } addressToLevels[addr] += numEach; } } /** * @dev Withdraw ether from this contract to the team for the agreed amounts, only callable by the owner */ function withdraw() external onlyOwner { address thisAddress = address(this); require(thisAddress.balance > 0, "there is no balance in the address"); require(payments.length > 0, "havent set the payments"); for(uint i = 0; i < payments.length; i++) { if(thisAddress.balance == 0) { return; } PaymentStruct memory payment = payments[i]; uint paymentLeft = payment.owed - payment.payed; if(paymentLeft > 0) { uint amountToPay; if(thisAddress.balance >= paymentLeft) { amountToPay = paymentLeft; } else { amountToPay = thisAddress.balance; } payment.payed += amountToPay; payments[i].payed = payment.payed; payable(payment.membersAddress).transfer(amountToPay); } } if(thisAddress.balance > 0) { payable(payments[payments.length - 1].membersAddress).transfer(thisAddress.balance); } } /** * @dev sets the root of the merkle tree, used to verify whitelist addresses * @param _root the root of the merkle tree */ function setMerkleRoots(bytes32[] calldata _root) external onlyOwner { roots = _root; } /** * @dev Lowers the max supply in case minting doesnt sell out * @param _newMaxSupply the new, and lower max supply */ function lowerMaxSupply(uint _newMaxSupply) external onlyOwner { require(_newMaxSupply >= totalSupply()); require(_newMaxSupply < maxSupply); maxSupply = uint16(_newMaxSupply); } /** * @dev toggles the ability for anyone to mint to whitelist only, of vice versa */ function togglePublicMint() external onlyOwner { publicMint = !publicMint; } // @notice Will receive any eth sent to the contract receive() external payable { } /** * @dev Reverts the name back to the base initial name, will be used by the team to revert offensive names * @param _tokenId token id to be reverted */ function revertName(uint _tokenId) external onlyOwner { tokenIdToPhoenix[_tokenId].name = ""; } /** * @dev Toggle the ability to resurect phoenix tokens and reroll traits */ function toggleResurrection() public onlyOwner { allowResurrection = !allowResurrection; } /** * @dev Give out mythics to phoenixs that have resurrected recently * @param _numMythics is the number of mythics that will be given out */ function rewardMythics(uint _numMythics) external onlyOwner { require(allowResurrection == false, "Need to have resurrection paused mythics are rewarded"); metadataHandler.rewardMythics(resurrectionId, _numMythics); toggleResurrection(); } /** * @dev Allows the owner to raise the max level six cap, but only by 100 at a time * @param _newMax is the new level six cap to be set */ function raiseMaxLevelSix(uint8 _newMax) external onlyOwner { require(_newMax > maxLevelSix, "Need to set the new max to be larger"); require(_newMax - maxLevelSix <= 100, "Can't raise it by more than 100 at a time"); maxLevelSix = _newMax; } function setRessurectionId(uint _id) external onlyOwner { resurrectionId = _id; } function setBlazeCosts(uint _nameCost, uint _resurrectCost) external onlyOwner { nameCost = _nameCost; resurrectCost = _resurrectCost; } /** ______ __ __ ______ ______ ______ __ _____ ______ /\ __ \ /\ \ / / /\ ___\ /\ == \ /\ == \ /\ \ /\ __-. /\ ___\ \ \ \/\ \ \ \ \'/ \ \ __\ \ \ __< \ \ __< \ \ \ \ \ \/\ \ \ \ __\ \ \_____\ \ \__| \ \_____\ \ \_\ \_\ \ \_\ \_\ \ \_\ \ \____- \ \_____\ \/_____/ \/_/ \/_____/ \/_/ /_/ \/_/ /_/ \/_/ \/____/ \/_____/ */ /** * @dev Override the transfer function to update the blaze token contract */ function transferFrom(address from, address to, uint256 tokenId) public override { blazeToken.updateTransfer(from, to); uint level = uint(tokenIdToPhoenix[tokenId].level); addressToLevels[from] -= level; addressToLevels[to] += level; ERC721Cheap.transferFrom(from, to, tokenId); } /** * @dev Override the transfer function to update the blaze token contract */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override { blazeToken.updateTransfer(from, to); uint level = uint(tokenIdToPhoenix[tokenId].level); addressToLevels[from] -= level; addressToLevels[to] += level; ERC721Cheap.safeTransferFrom(from, to, tokenId, _data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "./ERC721Cheap.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. * Altered to remove all storage variables to make minting and transfers cheaper, at the cost of more time to query * */ abstract contract ERC721EnumerableCheap is ERC721Cheap, IERC721Enumerable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721Cheap) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * Altered to loop through tokens rather thsn grab from stored map */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { uint ownerIndex; uint supply = totalSupply(); for(uint i = 0; i < supply; i++) { if(_owners[i] == owner) { if(ownerIndex == index) { return i; } ownerIndex++; } } //Need to catch this case additionally, can't call revert with a message so ill make sure it catches require(true == false, "ERC721Enumerable: owner index out of bounds"); } /** * @dev See {IERC721Enumerable-totalSupply}. * Altered to use the ERC721Cheap _owners array instead of _allTokens */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. * Altered to use ERC721Cheap _owners array instead of _allTokens */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721EnumerableCheap.totalSupply(), "ERC721Enumerable: global index out of bounds"); return index; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, _owners * * Altered _owners to an array and removed _balances, to allow for a cheaper {Erc721Enumerable} implementation at the cost of time * to query ownership of tokens */ contract ERC721Cheap is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Array of token ID to owner address, set to internal to give {ERC721EnumerableCheap} access address[] internal _owners; // 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}. * altered to remove the need to set a balances map */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); uint balance; uint totalSupply = _owners.length; for(uint i = 0; i < totalSupply; i++) { if(owner == _owners[i]) balance++; } return balance; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(tokenId < _owners.length, "token does now exist"); 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 = ERC721Cheap.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`). * * Altered to check from the _owners array instead of map */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length; //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 = ERC721Cheap.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. * * Altered to add to _owners array instead of a map */ 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); _owners.push(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. * * Altered to set the address of the token to the burn address instead of removing it */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Cheap.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); 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. * * Altered to not use the balances map */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Cheap.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); _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(ERC721Cheap.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 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 These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; 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 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 "../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); } }
Returns metadata for the token by asking for it from the set metadata manager, which generates the metadata all on chain _tokenId is the id of the phoenix requesting its metadata./
function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); Phoenix memory _phoenix = tokenIdToPhoenix[_tokenId]; MetadataStruct memory metaDataStruct = MetadataStruct(_tokenId, 0, 6, "5000 Onchain Immortal Phoenix risen from the ashes onto the Ethereum blockchain ready to take nft land by storm.", "iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAgMAAAAqbBEUAAAAAXNSR0IArs4c6QAAAAxQTFRFAAAAuo+P+vr6/f3+BbtU0AAAAMNJREFUKM+t0b0NwyAQBeBHFBrXQezgKRiBgpOriFHwKC4t78MoqZM7QDaW8tPkWUJ8MveEbDy74A94TDtyzAcoBsvMUeDv3mZKJK/hyJlgyFsBCDoocgUqADcYZwq8gjw6MbRXDhwVBa4CU4UvMAKoawEPMVp4CEemhnHlxTZsW2ko+8syzNxQMcyXReoqAIZ6A3xBVyB9HUZ0x9Zy02OEb9owy2p/oeYjXDfD336HJpr2QyblDuX/tOgTUgd1QuwAxgtmj7BFtSVEWwAAAABJRU5ErkJggg==" ); string memory metaData = metadataHandler.tokenURI( _phoenix, metaDataStruct ); return metaData; }
12,853,884
./partial_match/1/0x9Be61833A4a7aFb2c9a0DC90894C5CE82771e396/sources/BallyGang.sol
Returns the address of the current owner./
function owner() public view virtual returns (address) { return _owner ; }
4,243,968
// File: @openzeppelin/contracts/math/Math.sol pragma solidity 0.5.16; library Math { function MAX818(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN910(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.16; library SafeMath { function ADD553(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB354(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB354(a, b, "SafeMath: subtraction overflow"); } function SUB354(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL618(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV720(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV720(a, b, "SafeMath: division by zero"); } function DIV720(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD811(a, b, "SafeMath: modulo by zero"); } function MOD811(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.16; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER101() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA729() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.16; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED297(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER101(); emit OWNERSHIPTRANSFERRED297(address(0), _owner); } function OWNER579() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER471() { //inject NONSTANDARD NAMING require(ISOWNER602(), "Ownable: caller is not the owner"); _; } function ISOWNER602() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER101() == _owner; } function RENOUNCEOWNERSHIP987() public ONLYOWNER471 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED297(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP49(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP728(newOwner); } function _TRANSFEROWNERSHIP728(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED297(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.16; interface IERC20 { function TOTALSUPPLY250() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF938(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER79(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT2(address account, uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE644(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE576(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM482(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER160(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL369(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.16; library Address { function ISCONTRACT625(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE310(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE700(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity 0.5.16; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER546(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFER79.selector, to, value)); } function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFERFROM482.selector, from, to, value)); } function SAFEAPPROVE811(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE644(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, value)); } function SAFEINCREASEALLOWANCE917(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).ADD553(value); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE400(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).SUB354(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function CALLOPTIONALRETURN509(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT625(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.5.16; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function NOTIFYREWARDAMOUNT190(uint256 reward) external; //inject NONSTANDARD NAMING modifier ONLYREWARDDISTRIBUTION587() { //inject NONSTANDARD NAMING require(_MSGSENDER101() == rewardDistribution, "Caller is not reward distribution"); _; } function SETREWARDDISTRIBUTION306(address _rewardDistribution) //inject NONSTANDARD NAMING external ONLYOWNER471 { rewardDistribution = _rewardDistribution; } } pragma solidity 0.5.16; contract GOFTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY250() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF938(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function STAKE102(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD553(amount); _balances[msg.sender] = _balances[msg.sender].ADD553(amount); stakeToken.SAFETRANSFERFROM6(msg.sender, address(this), amount); } function WITHDRAW201(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB354(amount); _balances[msg.sender] = _balances[msg.sender].SUB354(amount); stakeToken.SAFETRANSFER546(msg.sender, amount); } } pragma solidity 0.5.16; contract GOFLINKPool is GOFTokenWrapper, IRewardDistributionRecipient { IERC20 public gof = IERC20(0x488E0369f9BC5C40C002eA7c1fe4fd01A198801c); uint256 public constant duration144 = 7 days; //inject NONSTANDARD NAMING uint256 public constant starttime308 = 1599652800; //utc+8 2020-09-09 20:00:00 //inject NONSTANDARD NAMING uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored = 0; bool private open = true; uint256 private constant _gunit942 = 1e18; //inject NONSTANDARD NAMING mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; // Unclaimed rewards event REWARDADDED578(uint256 reward); //inject NONSTANDARD NAMING event STAKED569(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN869(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID604(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event SETOPEN70(bool _open); //inject NONSTANDARD NAMING modifier UPDATEREWARD304(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN70(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE508(); if (account != address(0)) { rewards[account] = EARNED147(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE508() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN910(block.timestamp, periodFinish); } function REWARDPERTOKEN70() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY250() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD553( LASTTIMEREWARDAPPLICABLE508() .SUB354(lastUpdateTime) .MUL618(rewardRate) .MUL618(_gunit942) .DIV720(TOTALSUPPLY250()) ); } function EARNED147(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOF938(account) .MUL618(REWARDPERTOKEN70().SUB354(userRewardPerTokenPaid[account])) .DIV720(_gunit942) .ADD553(rewards[account]); } function STAKE102(uint256 amount) public CHECKOPEN514 CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot stake 0"); super.STAKE102(amount); emit STAKED569(msg.sender, amount); } function WITHDRAW201(uint256 amount) public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot withdraw 0"); super.WITHDRAW201(amount); emit WITHDRAWN869(msg.sender, amount); } function EXIT662() external { //inject NONSTANDARD NAMING WITHDRAW201(BALANCEOF938(msg.sender)); GETREWARD668(); } function GETREWARD668() public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING uint256 reward = EARNED147(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; gof.SAFETRANSFER546(msg.sender, reward); emit REWARDPAID604(msg.sender, reward); } } modifier CHECKSTART795(){ //inject NONSTANDARD NAMING require(block.timestamp > starttime308,"Golff-Link-POOL: Not start"); _; } modifier CHECKOPEN514() { //inject NONSTANDARD NAMING require(open, "Golff-Link-POOL: Pool is closed"); _; } function GETPERIODFINISH470() external view returns (uint256) { //inject NONSTANDARD NAMING return periodFinish; } function ISOPEN95() external view returns (bool) { //inject NONSTANDARD NAMING return open; } function SETOPEN315(bool _open) external ONLYOWNER471 { //inject NONSTANDARD NAMING open = _open; emit SETOPEN70(_open); } function NOTIFYREWARDAMOUNT190(uint256 reward) //inject NONSTANDARD NAMING external ONLYREWARDDISTRIBUTION587 CHECKOPEN514 UPDATEREWARD304(address(0)){ if (block.timestamp > starttime308){ if (block.timestamp >= periodFinish) { uint256 period = block.timestamp.SUB354(starttime308).DIV720(duration144).ADD553(1); periodFinish = starttime308.ADD553(period.MUL618(duration144)); rewardRate = reward.DIV720(periodFinish.SUB354(block.timestamp)); } else { uint256 remaining = periodFinish.SUB354(block.timestamp); uint256 leftover = remaining.MUL618(rewardRate); rewardRate = reward.ADD553(leftover).DIV720(remaining); } lastUpdateTime = block.timestamp; }else { rewardRate = reward.DIV720(duration144); periodFinish = starttime308.ADD553(duration144); lastUpdateTime = starttime308; } gof.MINT2(address(this),reward); emit REWARDADDED578(reward); // avoid overflow to lock assets _CHECKREWARDRATE734(); } function _CHECKREWARDRATE734() internal view returns (uint256) { //inject NONSTANDARD NAMING return duration144.MUL618(rewardRate).MUL618(_gunit942); } }
inject NONSTANDARD NAMING
function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal {
5,362,674
./partial_match/4/0x531e9308461f3A066a170B0E8f546b16AA241937/sources/SakeILO.sol
require(lpUnlockStartTimestamp == 0, "lp unlocked");
function projectPartyRefund() external nonReentrant whenNotPaused { require(isFundraisingSucceed() == false, "fundraising succeed"); projectPartyToken.transfer(msg.sender, maxProjectPartyAmount); }
8,520,456
./full_match/5/0x2e89601fAE0fe0690e7C8cAC0c1C43a2cE48F356/sources/lib/hypercerts-protocol/contracts/ERC3525Upgradeable.sol
solhint-disable-next-line
function _checkOnERC3525Received( uint256 fromTokenId_, uint256 toTokenId_, uint256 value_, bytes memory data_ ) private returns (bool) { address to = ownerOf((toTokenId_)); if (to.isContract() && IERC165Upgradeable(to).supportsInterface(type(IERC3525Receiver).interfaceId)) { try IERC3525Receiver(to).onERC3525Received(_msgSender(), fromTokenId_, toTokenId_, value_, data_) returns ( bytes4 retval ) { return retval == IERC3525Receiver.onERC3525Received.selector; if (reason.length == 0) { revert NotERC3525Receiver(to); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
11,629,139
// SPDX-License-Identifier: MIT // Developed by KG Technologies (https://kgtechnologies.io) pragma solidity 0.8.12; import "@openzeppelin/contracts/access/Ownable.sol"; import { MerkleProof } from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @notice Represents MetaTriad Smart Contract */ contract IMetaTriads { /** * @dev ERC-721 INTERFACE */ function ownerOf(uint256 tokenId) public view virtual returns (address) {} /** * @dev CUSTOM INTERFACE */ function mintTo(uint256 amount, address _to) external {} } /** * @title MetaTriadsTicketContract. * * @author KG Technologies (https://kgtechnologies.io). * * @notice This Smart Contract can be used to sell a fixed amount of tickets where some of them are * sold to permissioned wallets and the others are sold to the general public. * The tickets can then be used to mint a corresponding amount of NFTs. * * @dev The primary mode of verifying permissioned actions is through Merkle Proofs * which are generated off-chain. */ contract MetaTriadsTicketContract is Ownable { /** * @notice The Smart Contract of MetaTriad * @dev ERC-721 Smart Contract */ IMetaTriads public immutable nft; /** * @dev MINT DATA */ uint256 public phaseOneMaxSupply = 300; uint256 public phaseTwoMaxSupply = 2000; uint256 public pricePermissioned = 0.09 ether; mapping(uint256 => uint256) public boughtPermissioned; uint256 public marginOfSafety = 2 minutes; uint256 public phaseOneStartTime = 1647289800 - marginOfSafety; uint256 public phaseOneDuration = 30 minutes + marginOfSafety; uint256 public phaseTwoStartTime = 1647291600 - marginOfSafety; uint256 public phaseTwoDuration = 30 minutes + marginOfSafety; uint256 public maxSupplyOpen = 7200; uint256 public boughtOpen = 0; uint256 public limitOpen = 10; uint256 public priceOpen = 0.18 ether; uint256 public startTimeOpen = 1647293400 - marginOfSafety; uint256 public redeemStart = startTimeOpen + 1 hours; uint256 public redeemDuration = 30 days; mapping(address => uint256) public addressToTicketsOpen; mapping(address => mapping(uint256 => uint256)) public addressToTicketsPermissioned; mapping(address => uint256) public addressToMints; /// @dev Initial value is randomly generated from https://www.random.org/ bytes32 public merkleRoot = 0xa204682a31130d0acf7f63a1c180deb6c1036ec25a02190ba096e18033065319; /** * @dev GIVEAWAY */ uint256 public maxSupplyGiveaway = 500; uint256 public giveAwayRedeemed = 0; mapping(address => uint256) public addressToGiveawayRedeemed; bytes32 public giveAwayMerkleRoot = ""; /** * @dev Events */ event ReceivedEther(address indexed sender, uint256 indexed amount); event WithdrawAllEvent(address indexed to, uint256 amount); event Purchase(address indexed buyer, uint256 indexed amount, bool indexed permissioned); event RedeemTickets(address indexed redeemer, uint256 amount); event RedeemGiveAway(address indexed redeemer, uint256 amount); /// @dev Setters event setMaxSupplyPhaseOneEvent(uint256 indexed maxSupply); event setMaxSupplyPhaseTwoEvent(uint256 indexed maxSupply); event setMaxSupplyOpenEvent(uint256 indexed maxSupply); event setLimitOpenEvent(uint256 indexed limit); event setPriceOpenEvent(uint256 indexed price); event setRedeemStartEvent(uint256 indexed start); event setRedeemDurationEvent(uint256 indexed duration); event setMerkleRootEvent(bytes32 indexed merkleRoot); event setGiveAwayMerkleRootEvent(bytes32 indexed merkleRoot); event setGiveAwayMaxSupplyEvent(uint256 indexed newSupply); event setPricePermissionedEvent(uint256 indexed price); event setPhaseOneStartTimeEvent(uint256 indexed time); event setPhaseOneDurationEvent(uint256 indexed time); event setPhaseTwoStartTimeEvent(uint256 indexed time); event setPhaseTwoDurationEvent(uint256 indexed time); event setStartTimeOpenEvent(uint256 indexed time); constructor( address _metaTriadsAddress ) Ownable() { nft = IMetaTriads(_metaTriadsAddress); } /** * @dev SALE */ /** * @dev Caculates the Triads left from phase one sale */ function phaseOneLeft() public view returns(uint256) { if (phaseOneMaxSupply >= boughtPermissioned[1]) { return phaseOneMaxSupply - boughtPermissioned[1]; } else { return 0; } } /** * @dev Calculates the Traids left from phase two sale */ function phaseTwoLeft() public view returns(uint256) { if (phaseTwoMaxSupply >= boughtPermissioned[2]) { return phaseTwoMaxSupply - boughtPermissioned[2]; } else { return 0; } } /** * @dev Calculates the supply of public sale based * on what's left from phase one and phase two. */ function realSupplyOpen() public view returns(uint256) { return maxSupplyOpen + phaseOneLeft() + phaseTwoLeft(); } /** * @dev Calculates the Triads left from public sale */ function openLeft() public view returns(uint256) { if (realSupplyOpen() >= boughtOpen) { return realSupplyOpen() - boughtOpen; } else { return 0; } } /** * @notice Validates the sale data for each phase per user * * @dev For each phase validates that the time is correct, * that the ether supplied is correct and that the purchase * amount doesn't exceed the max amount * * @param amount. The amount the user want's to purchase * @param phase. The sale phase of the user */ function validatePhaseSpecificPurchase(uint256 amount, uint256 phase) internal { if (phase == 1) { require(block.timestamp < phaseOneStartTime + phaseOneDuration, "PHASE ONE SALE IS CLOSED"); require(msg.value >= priceOpen * amount, "ETHER SENT NOT CORRECT"); require(boughtPermissioned[phase] + amount <= phaseOneMaxSupply, "BUY AMOUNT GOES OVER MAX SUPPLY"); require(block.timestamp >= phaseOneStartTime, "PHASE ONE SALE HASN'T STARTED YET"); } else if (phase == 2) { require(block.timestamp < phaseTwoStartTime + phaseTwoDuration, "PHASE TWO SALE IS CLOSED"); require(msg.value >= pricePermissioned * amount, "ETHER SENT NOT CORRECT"); require(boughtPermissioned[phase] + amount <= phaseTwoMaxSupply, "BUY AMOUNT GOES OVER MAX SUPPLY"); require(block.timestamp >= phaseTwoStartTime, "PHASE TWO SALE HASN'T STARTED YET"); } else { revert("INCORRECT PHASE"); } } /** * @notice Function to buy one or more tickets. * @dev First the Merkle Proof is verified. * Then the buy is verified with the data embedded in the Merkle Proof. * Finally the tickets are bought to the user's wallet. * * @param amount. The amount of tickets to buy. * @param buyMaxAmount. The max amount the user can buy. * @param phase. The permissioned sale phase. * @param proof. The Merkle Proof of the user. */ function buyPermissioned(uint256 amount, uint256 buyMaxAmount, uint256 phase, bytes32[] calldata proof) external payable { /// @dev Verifies Merkle Proof submitted by user. /// @dev All mint data is embedded in the merkle proof. bytes32 leaf = keccak256(abi.encodePacked(msg.sender, buyMaxAmount, phase)); require(MerkleProof.verify(proof, merkleRoot, leaf), "INVALID PROOF"); /// @dev Verify that user can perform permissioned sale based on the provided parameters. require(address(nft) != address(0), "METATRIAD NFT SMART CONTRACT NOT SET"); require(amount > 0, "HAVE TO BUY AT LEAST 1"); require(addressToTicketsPermissioned[msg.sender][phase] + amount <= buyMaxAmount, "BUY AMOUNT EXCEEDS MAX FOR USER"); /// @dev verify that user can perform permissioned sale based on phase of user validatePhaseSpecificPurchase(amount, phase); boughtPermissioned[phase] += amount; addressToTicketsPermissioned[msg.sender][phase] += amount; emit Purchase(msg.sender, amount, true); } /** * @notice Function to buy one or more tickets. * * @param amount. The amount of tickets to buy. */ function buyOpen(uint256 amount) external payable { /// @dev Verifies that user can perform open sale based on the provided parameters. require(address(nft) != address(0), "METATRIADS NFT SMART CONTRACT NOT SET"); require(block.timestamp >= startTimeOpen, "OPEN SALE CLOSED"); require(amount > 0, "HAVE TO BUY AT LEAST 1"); require(addressToTicketsOpen[msg.sender] + amount <= limitOpen, "BUY AMOUNT EXCEEDS MAX FOR USER"); require(boughtOpen + amount <= realSupplyOpen(), "BUY AMOUNT GOES OVER MAX SUPPLY"); require(msg.value >= priceOpen * amount, "ETHER SENT NOT CORRECT"); /// @dev Updates contract variables and buys `amount` tickets to users wallet boughtOpen += amount; addressToTicketsOpen[msg.sender] += amount; emit Purchase(msg.sender, amount, false); } /** * @dev MINTING */ /** * @notice Allows users to redeem their tickets for NFTs. * * @dev Users from Phase 1 can bypass the time block. */ function redeemTickets() external { require(block.timestamp >= redeemStart || addressToTicketsPermissioned[msg.sender][1] > 0, "REDEEM CLOSED"); require(block.timestamp < redeemStart + redeemDuration, "REDEEM CLOSED"); uint256 ticketsOfSender = addressToTicketsPermissioned[msg.sender][1] + addressToTicketsPermissioned[msg.sender][2] + addressToTicketsOpen[msg.sender]; uint256 mintsOfSender = addressToMints[msg.sender]; uint256 mintable = ticketsOfSender - mintsOfSender; require(mintable > 0, "NO MINTABLE TICKETS"); uint256 maxMintPerTx = 100; uint256 toMint = mintable > maxMintPerTx ? maxMintPerTx : mintable; addressToMints[msg.sender] = addressToMints[msg.sender] + toMint; nft.mintTo(toMint, msg.sender); emit RedeemTickets(msg.sender, toMint); } /** * @notice Function to redeem giveaway. * @dev First the Merkle Proof is verified. * Then the redeem is verified with the data embedded in the Merkle Proof. * Finally the metatriads are minted to the user's wallet. * * @param redeemAmount. The amount to redeem. * @param proof. The Merkle Proof of the user. */ function redeemGiveAway(uint256 redeemAmount, bytes32[] calldata proof) external { /// @dev Verifies Merkle Proof submitted by user. /// @dev All giveaway data is embedded in the merkle proof. bytes32 leaf = keccak256(abi.encodePacked(msg.sender, redeemAmount)); require(MerkleProof.verify(proof, giveAwayMerkleRoot, leaf), "INVALID PROOF"); /// @dev Verifies that user can perform giveaway based on the provided parameters. require(address(nft) != address(0), "METATRIAD NFT SMART CONTRACT NOT SET"); require(giveAwayMerkleRoot != "", "GIVEAWAY CLOSED"); require(redeemAmount > 0, "HAVE TO REDEEM AT LEAST 1"); require(addressToGiveawayRedeemed[msg.sender] == 0, "GIVEAWAY ALREADY REDEEMED"); require(giveAwayRedeemed + redeemAmount <= maxSupplyGiveaway, "GIVEAWAY AMOUNT GOES OVER MAX SUPPLY"); /// @dev Updates contract variables and mints `redeemAmount` metatriads to users wallet giveAwayRedeemed += redeemAmount; addressToGiveawayRedeemed[msg.sender] = 1; nft.mintTo(redeemAmount, msg.sender); emit RedeemGiveAway(msg.sender, redeemAmount); } /** * @dev OWNER ONLY */ /** * @notice Change the maximum supply of tickets that are for sale in phase one permissioned sale. * * @param newMaxSupply. The new max supply. */ function setMaxSupplyPhaseOne(uint256 newMaxSupply) external onlyOwner { phaseOneMaxSupply = newMaxSupply; emit setMaxSupplyPhaseOneEvent(newMaxSupply); } /** * @notice Change the maximum supply of tickets that are for sale in phase two permissioned sale. * * @param newMaxSupply. The new max supply. */ function setMaxSupplyPhaseTwo(uint256 newMaxSupply) external onlyOwner { phaseTwoMaxSupply = newMaxSupply; emit setMaxSupplyPhaseTwoEvent(newMaxSupply); } /** * @notice Change the maximum supply of tickets that are for sale in open sale. * * @param newMaxSupply. The new max supply. */ function setMaxSupplyOpen(uint256 newMaxSupply) external onlyOwner { maxSupplyOpen = newMaxSupply; emit setMaxSupplyOpenEvent(newMaxSupply); } /** * @notice Change the limit of tickets per wallet in open sale. * * @param newLimitOpen. The new max supply. */ function setLimitOpen(uint256 newLimitOpen) external onlyOwner { limitOpen = newLimitOpen; emit setLimitOpenEvent(newLimitOpen); } /** * @notice Change the price of tickets that are for sale in open sale. * * @param newPriceOpen. The new price. */ function setPriceOpen(uint256 newPriceOpen) external onlyOwner { priceOpen = newPriceOpen; emit setPriceOpenEvent(newPriceOpen); } /** * @notice Change the price of tickets that are for sale in permissioned sale. * * @param newPricePermissioned. The new price. */ function setPricePermissioned(uint256 newPricePermissioned) external onlyOwner { pricePermissioned = newPricePermissioned; emit setPricePermissionedEvent(newPricePermissioned); } /** * @notice Allows owner to change the start time of the redeem period * * @param newStart. The new start time of the redeem period */ function setRedeemStart(uint256 newStart) external onlyOwner { redeemStart = newStart; emit setRedeemStartEvent(newStart); } /** * @notice Allows owner to change the duration of the redeem period * * @param newDuration. The new duration of the redeem period */ function setRedeemDuration(uint256 newDuration) external onlyOwner { redeemDuration = newDuration; emit setRedeemDurationEvent(newDuration); } /** * @notice Change the merkleRoot of the sale. * * @param newRoot. The new merkleRoot. */ function setMerkleRoot(bytes32 newRoot) external onlyOwner { merkleRoot = newRoot; emit setMerkleRootEvent(newRoot); } /** * @notice Delete the merkleRoot of the sale. */ function deleteMerkleRoot() external onlyOwner { merkleRoot = ""; emit setMerkleRootEvent(merkleRoot); } /** * @notice Change the merkleRoot of the giveaway. * * @param newRoot. The new merkleRoot. */ function setGiveAwayMerkleRoot(bytes32 newRoot) external onlyOwner { giveAwayMerkleRoot = newRoot; emit setGiveAwayMerkleRootEvent(newRoot); } /** * @notice Change the max supply for the giveaway. * * @param newSupply. The new giveaway max supply. */ function setGiveAwayMaxSupply(uint256 newSupply) external onlyOwner { maxSupplyGiveaway = newSupply; emit setGiveAwayMaxSupplyEvent(newSupply); } /** * @notice Change start time of the Phase One permissioned sale. * * @param newTime. The new time. */ function setPhaseOneStartTime(uint256 newTime) external onlyOwner { phaseOneStartTime = newTime; emit setPhaseOneStartTimeEvent(newTime); } /** * @notice Change duration of the Phase One permissioned sale. * * @param newDuration. The new duration. */ function setPhaseOneDuration(uint256 newDuration) external onlyOwner { phaseOneDuration = newDuration; emit setPhaseOneDurationEvent(newDuration); } /** * @notice Change start time of the Phase Two permissioned sale. * * @param newTime. The new time. */ function setPhaseTwoStartTime(uint256 newTime) external onlyOwner { phaseTwoStartTime = newTime; emit setPhaseTwoStartTimeEvent(newTime); } /** * @notice Change duration of the Phase One permissioned sale. * * @param newDuration. The new duration. */ function setPhaseTwoDuration(uint256 newDuration) external onlyOwner { phaseTwoDuration = newDuration; emit setPhaseTwoDurationEvent(newDuration); } /** * @notice Change start time of the open sale. * * @param newTime. The new time. */ function setStartTimeOpen(uint256 newTime) external onlyOwner { startTimeOpen = newTime; emit setStartTimeOpenEvent(newTime); } /** * @dev FINANCE */ /** * @notice Allows owner to withdraw funds generated from sale. * * @param _to. The address to send the funds to. */ function withdrawAll(address _to) external onlyOwner { require(_to != address(0), "CANNOT WITHDRAW TO ZERO ADDRESS"); uint256 contractBalance = address(this).balance; require(contractBalance > 0, "NO ETHER TO WITHDRAW"); payable(_to).transfer(contractBalance); emit WithdrawAllEvent(_to, contractBalance); } /** * @dev Fallback function for receiving Ether */ receive() external payable { emit ReceivedEther(msg.sender, msg.value); } } // 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 (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // 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; } }
Change the price of tickets that are for sale in permissioned sale. newPricePermissioned. The new price./
function setPricePermissioned(uint256 newPricePermissioned) external onlyOwner { pricePermissioned = newPricePermissioned; emit setPricePermissionedEvent(newPricePermissioned); }
10,178,736
./partial_match/1/0x8Cf8953D5D0B3cB9fd72C3Eac244790AB8d2007F/sources/Honesty.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Honesty", "Honesty") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 400_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,715,952
pragma solidity 0.4.24; 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; } } 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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BGAudit is Ownable { using SafeMath for uint; event AddedAuditor(address indexed auditor); event BannedAuditor(address indexed auditor); event AllowedAuditor(address indexed auditor); event CreatedAudit(uint indexed id); event ReviewingAudit(uint indexed id); event AuditorRewarded(uint indexed id, address indexed auditor, uint indexed reward); event AuditorStaked(uint indexed id, address indexed auditor, uint indexed amount); event WithdrawedStake(uint indexed id, address indexed auditor, uint indexed amount); event SlashedStake(uint indexed id, address indexed auditor); enum AuditStatus { New, InProgress, InReview, Completed } struct Auditor { bool banned; address addr; uint totalEarned; uint completedAudits; uint[] stakedAudits; // array of audit IDs they&#39;ve staked mapping(uint => bool) stakedInAudit; // key is AuditID; useful so we don&#39;t need to loop through the audits array above mapping(uint => bool) canWithdrawStake; // Audit ID => can withdraw stake or not } struct Audit { AuditStatus status; address owner; uint id; uint totalReward; // total reward shared b/w all auditors uint remainingReward; // keep track of how much reward is left uint stake; // required stake for each auditor in wei uint endTime; // scheduled end time for the audit uint maxAuditors; // max auditors allowed for this Audit address[] participants; // array of auditor that have staked } //=== Storage uint public stakePeriod = 90 days; // number of days to wait before stake can be withdrawn uint public maxAuditDuration = 365 days; // max amount of time for a security audit Audit[] public audits; mapping(address => Auditor) public auditors; //=== Owner related function transfer(address _to, uint _amountInWei) external onlyOwner { require(address(this).balance > _amountInWei); _to.transfer(_amountInWei); } function setStakePeriod(uint _days) external onlyOwner { stakePeriod = _days * 1 days; } function setMaxAuditDuration(uint _days) external onlyOwner { maxAuditDuration = _days * 1 days; } //=== Auditors function addAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr == address(0)); // Only add if they&#39;re not already added auditors[_auditor].banned = false; auditors[_auditor].addr = _auditor; auditors[_auditor].completedAudits = 0; auditors[_auditor].totalEarned = 0; emit AddedAuditor(_auditor); } function banAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); auditors[_auditor].banned = true; emit BannedAuditor(_auditor); } function allowAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); auditors[_auditor].banned = false; emit AllowedAuditor(_auditor); } //=== Audits and Rewards function createAudit(uint _stake, uint _endTimeInDays, uint _maxAuditors) external payable onlyOwner { uint endTime = _endTimeInDays * 1 days; require(endTime < maxAuditDuration); require(block.timestamp + endTime * 1 days > block.timestamp); require(msg.value > 0 && _maxAuditors > 0 && _stake > 0); Audit memory audit; audit.status = AuditStatus.New; audit.owner = msg.sender; audit.id = audits.length; audit.totalReward = msg.value; audit.remainingReward = audit.totalReward; audit.stake = _stake; audit.endTime = block.timestamp + endTime; audit.maxAuditors = _maxAuditors; audits.push(audit); // push into storage emit CreatedAudit(audit.id); } function reviewAudit(uint _id) external onlyOwner { require(audits[_id].status == AuditStatus.InProgress); require(block.timestamp >= audits[_id].endTime); audits[_id].endTime = block.timestamp; // override the endTime to when it actually ended audits[_id].status = AuditStatus.InReview; emit ReviewingAudit(_id); } function rewardAuditor(uint _id, address _auditor, uint _reward) external onlyOwner { audits[_id].remainingReward.sub(_reward); audits[_id].status = AuditStatus.Completed; auditors[_auditor].totalEarned.add(_reward); auditors[_auditor].completedAudits.add(1); auditors[_auditor].canWithdrawStake[_id] = true; // allow them to withdraw their stake after stakePeriod _auditor.transfer(_reward); emit AuditorRewarded(_id, _auditor, _reward); } function slashStake(uint _id, address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); require(auditors[_auditor].stakedInAudit[_id]); // participated in audit auditors[_auditor].canWithdrawStake[_id] = false; emit SlashedStake(_id, _auditor); } //=== User Actions function stake(uint _id) public payable { // Check conditions of the Audit require(msg.value == audits[_id].stake); require(block.timestamp < audits[_id].endTime); require(audits[_id].participants.length < audits[_id].maxAuditors); require(audits[_id].status == AuditStatus.New || audits[_id].status == AuditStatus.InProgress); // Check conditions of the Auditor require(auditors[msg.sender].addr == msg.sender && !auditors[msg.sender].banned); // auditor is authorized require(!auditors[msg.sender].stakedInAudit[_id]); //check if auditor has staked for this audit already // Update audit&#39;s states audits[_id].status = AuditStatus.InProgress; audits[_id].participants.push(msg.sender); // Update auditor&#39;s states auditors[msg.sender].stakedInAudit[_id] = true; auditors[msg.sender].stakedAudits.push(_id); emit AuditorStaked(_id, msg.sender, msg.value); } function withdrawStake(uint _id) public { require(audits[_id].status == AuditStatus.Completed); require(auditors[msg.sender].canWithdrawStake[_id]); require(block.timestamp >= audits[_id].endTime + stakePeriod); auditors[msg.sender].canWithdrawStake[_id] = false; //prevent replay attack address(msg.sender).transfer(audits[_id].stake); // do this last to prevent re-entrancy emit WithdrawedStake(_id, msg.sender, audits[_id].stake); } //=== Getters function auditorHasStaked(uint _id, address _auditor) public view returns(bool) { return auditors[_auditor].stakedInAudit[_id]; } function auditorCanWithdrawStake(uint _id, address _auditor) public view returns(bool) { if(auditors[_auditor].stakedInAudit[_id] && auditors[_auditor].canWithdrawStake[_id]) { return true; } return false; } // return a list of ids that _auditor has staked in function getStakedAudits(address _auditor) public view returns(uint[]) { return auditors[_auditor].stakedAudits; } // return a list of auditors that participated in this audit function getAuditors(uint _id) public view returns(address[]) { return audits[_id].participants; } }
return a list of auditors that participated in this audit
function getAuditors(uint _id) public view returns(address[]) { return audits[_id].participants; }
15,014,945
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; /** * @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 StringUtil { function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function append(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } function append2(string memory a, string memory b, string memory c) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c)); } function append3(string memory a, string memory b, string memory c, string memory d) internal pure returns (string memory) { return string(abi.encodePacked(a, b, c, d)); } function bool2str(bool b) internal pure returns(string memory){ if(b) return "true"; return "false"; } function address2str(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } } contract Constants { uint internal constant oneMantissa = 10**18; enum LoopControl { NONE, CONTINUE, BREAK } } contract CompoundAddresses { address internal constant cDAIAddr = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address internal constant cETHAddr = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address internal constant cUSDCAddr = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; address internal constant cUSDTAddr = 0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9; address internal constant cWBTCAddr = 0xC11b1268C1A384e55C48c2391d8d480264A3A7F4; address internal constant cWBTC2Addr = 0xccF4429DB6322D5C611ee964527D42E5d685DD6a; //migrated at block number 12069867 address internal constant cCOMPAddr = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address internal constant cSAIAddr = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC; address internal constant compAddr = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address internal constant compoundLensAddr = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address internal constant comptrollerAddr = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address internal constant uniswapAnchoredViewAddr = 0x922018674c12a7F0D394ebEEf9B58F186CdE13c1; function getCWBTCAddr(uint blockNumber) public pure returns(address){ if(blockNumber >= 12069867){ return cWBTC2Addr; } return cWBTCAddr; } } contract ERC20Addresses { address internal constant usdtAddr = 0xdAC17F958D2ee523a2206206994597C13D831ec7; } contract UniswapV2Addresses { address internal constant uniswapV2Router02Address = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address internal constant wETHAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } contract ERC20 { uint8 public decimals; function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function balanceOf(address owner) external view returns (uint); function transfer(address dst, uint amount) external returns (bool); function symbol() external view returns (string memory); } contract USDT_ERC20 { function approve(address spender, uint value) external; } contract Comptroller { struct Market { bool isListed; uint collateralFactorMantissa; bool isComped; } mapping(address => Market) public markets; mapping(address => uint) public compAccrued; uint public closeFactorMantissa; uint public liquidationIncentiveMantissa; address public oracle; function getAccountLiquidity(address account) public view returns (uint, uint, uint); function getAssetsIn(address account) external view returns (address[] memory); function compSpeeds(address cTokenAddress) external view returns(uint); function getAllMarkets() public view returns (CToken[] memory); } contract CToken is ERC20{ address public underlying; uint public totalBorrows; uint public totalReserves; function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function exchangeRateStored() public view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function getCash() external view returns (uint); function totalBorrowsCurrent() external view returns (uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); } contract PriceOracle { function getUnderlyingPrice(CToken cToken) public view returns (uint); } contract UniswapAnchoredView { function price(string memory symbol) public view returns (uint); } contract CErc20 is CToken { address public underlying; function liquidateBorrow(address borrower, uint repayAmount, CToken cTokenCollateral) external returns (uint); } contract CompoundLens { struct CompBalanceMetadataExt{ uint balance; uint votes; address delegate; uint allocated; } function getCompBalanceMetadataExt(Comp comp, ComptrollerLensInterface comptroller, address account) external returns (CompBalanceMetadataExt memory); } contract Comp { } interface ComptrollerLensInterface { } contract ERC20ErrorReporter { enum ERC20Error { NO_ERROR, TRANSFER_FROM_FAILED, APPROVE_FAILED, TRANSFER_FAILED } event fail(uint err); } contract ERC20Methods is ERC20ErrorReporter, ERC20Addresses{ function getDecimals(address token) internal view returns(uint decimals){ if(token == address(0)){ return 18; } return ERC20(token).decimals(); } function transferIn(address token, address from, address to, uint amount) internal returns(ERC20Error){ if(!ERC20(token).transferFrom(from, to, amount)){ emit fail(uint(ERC20Error.TRANSFER_FROM_FAILED)); return ERC20Error.TRANSFER_FROM_FAILED; } return ERC20Error.NO_ERROR; } function transferOut(address token, address to, uint amount) internal returns(ERC20Error){ ERC20 erc20 = ERC20(token); if(!erc20.approve(to, amount)){ emit fail(uint(ERC20Error.APPROVE_FAILED)); return ERC20Error.APPROVE_FAILED; } if(!erc20.transfer(to, amount)){ emit fail(uint(ERC20Error.TRANSFER_FAILED)); return ERC20Error.TRANSFER_FAILED; } return ERC20Error.NO_ERROR; } //works with ETH and ERC20 function balanceOf(address tokenAddr, address accAddr) internal view returns(uint){ //for ETH if(tokenAddr == address(0)){ return accAddr.balance; } return ERC20(tokenAddr).balanceOf(accAddr); } //works with standard and non-standard ERC20 function approve(address tokenAddr, address spender, uint256 amount) internal returns(bool){ if(tokenAddr == usdtAddr){ USDT_ERC20(usdtAddr).approve(spender, 0); USDT_ERC20(usdtAddr).approve(spender, amount); return true; } return ERC20(tokenAddr).approve(spender, amount); } } contract CompoundMethodsErrorReporter { enum CompoundMethodsError { NO_ERROR, Liquidation_Failed, APPROVE_FAILED, Redeem_Failed } event fail(uint err); event fail(uint err, uint detail); } contract CompoundMethods is CompoundMethodsErrorReporter, ERC20Methods, CompoundAddresses, UniswapV2Addresses, Constants, StringUtil{ using SafeMath for uint; function cmp_redeemUnderlying(address cToken, uint amount) internal returns(CompoundMethodsError err){ uint error_redeem = CToken(cToken).redeem(amount); if(error_redeem != 0){ emit fail(uint(CompoundMethodsError.Redeem_Failed), error_redeem); return CompoundMethodsError.Redeem_Failed; } return CompoundMethodsError.NO_ERROR; } function cmp_liquidateBorrow(address cTokenBorrowed, address underlyingBorrowed, address borrower, uint repayAmount, CToken cTokenCollateral) internal returns(CompoundMethodsError err){ //approve USDT won't work if(!approve(underlyingBorrowed, cTokenBorrowed, repayAmount)){ emit fail(uint(CompoundMethodsError.APPROVE_FAILED)); return CompoundMethodsError.APPROVE_FAILED; } //liquidate uint err_liquidateBorrow = CErc20(cTokenBorrowed).liquidateBorrow(borrower, repayAmount, cTokenCollateral); if(err_liquidateBorrow != 0){ emit fail(uint(CompoundMethodsError.APPROVE_FAILED), err_liquidateBorrow); return CompoundMethodsError.APPROVE_FAILED; } return CompoundMethodsError.NO_ERROR; } function cmp_getUnderlyingAddr(address cTokenAddr) internal view returns(address underlyingAddr) { if(cTokenAddr == cETHAddr){ return address(0); } underlyingAddr = CToken(cTokenAddr).underlying(); return underlyingAddr; } function cmp_underlyingValueInUSD(uint underlyingBalance, address cTokenAddr) internal view returns(uint valueInUSD){ uint underlyingDecimals = cmp_getUnderlyingDecimals(cTokenAddr); valueInUSD = cmp_getUnderlyingPriceInUSD(cTokenAddr).mul(underlyingBalance).div(10**underlyingDecimals); return valueInUSD; } function cmp_getUnderlyingPriceInUSD(address cTokenAddr) internal view returns (uint priceInUSD){ address oracleAddr = Comptroller(comptrollerAddr).oracle(); if(cTokenAddr == cUSDCAddr || cTokenAddr == cUSDTAddr){ priceInUSD = oneMantissa; return priceInUSD; } if(cTokenAddr == cWBTC2Addr || cTokenAddr == cWBTCAddr){ priceInUSD = PriceOracle(oracleAddr).getUnderlyingPrice(CToken(cTokenAddr)).div(10**10); return priceInUSD; } priceInUSD = PriceOracle(oracleAddr).getUnderlyingPrice(CToken(cTokenAddr)); return priceInUSD; } function cmp_getPriceInUSDByUnderlyingAddr(address underlyingAddr) internal view returns(uint underlyingPriceInUSD){ string memory symbol = ERC20(underlyingAddr).symbol(); if(compareStrings(symbol, "wBTC")){ symbol = "BTC"; } return cmp_getPriceBySymbol(symbol).mul(10**12); } function cmp_getPriceBySymbol(string memory symbol) internal view returns(uint priceInUSDMantissa6){ return UniswapAnchoredView(uniswapAnchoredViewAddr).price(symbol); } function cmp_getUnderlyingSymbol(address cTokenAddr) internal view returns(string memory getUnderlyingSymbol){ if(cTokenAddr == cETHAddr) return "ETH"; if(cTokenAddr == cSAIAddr) return "SAI"; return ERC20(CToken(cTokenAddr).underlying()).symbol(); } function cmp_getUnderlyingDecimals(address cTokenAddr) internal view returns(uint decimals){ if(cTokenAddr == cETHAddr){ decimals = 18; return decimals; } address underlyingAddr = cmp_getUnderlyingAddr(cTokenAddr); decimals = ERC20(underlyingAddr).decimals(); return decimals; } //not tested function cmp_getTotalSupplyInUSD(address cTokenAddr) internal view returns(uint totalSupplyInUSD){ return cmp_underlyingValueInUSD(cmp_getTotalSupply(cTokenAddr), cTokenAddr); } function cmp_getTotalSupply(address cTokenAddr) internal view returns(uint totalSupply){ CToken cToken = CToken(cTokenAddr); uint cash = cToken.getCash(); uint totalBorrow = cToken.totalBorrows(); uint totalReserves = cToken.totalReserves(); return cash.add(totalBorrow).sub(totalReserves); } function cmp_getCompDistSpeedPerBlock(address cTokenAddr) internal view returns(uint compDistSpeedPerBlock){ Comptroller comptroller = Comptroller(comptrollerAddr); return comptroller.compSpeeds(cTokenAddr); } function cmp_getCompDistAmount(address cTokenAddr, uint numberOfBlocks) internal view returns(uint compDistAmount){ return cmp_getCompDistSpeedPerBlock(cTokenAddr).mul(numberOfBlocks); } function cmp_getCurrentCTokenAddrList() internal view returns(address[] memory cTokenAddrList){ Comptroller comptroller = Comptroller(comptrollerAddr); CToken[] memory allMarkets = comptroller.getAllMarkets(); cTokenAddrList = new address[](cmp_getNumberOfCurrentCTokens(allMarkets)); CToken eachCToken; uint index; for(uint i = 0; i < allMarkets.length; i++){ eachCToken = allMarkets[i]; if(!cmp_isCurrentCToken(address(eachCToken))) continue; cTokenAddrList[index] = address(eachCToken); index++; } return cTokenAddrList; } function cmp_getCurrentCTokenSymbolList() internal view returns(string[] memory cTokenSymbolList){ Comptroller comptroller = Comptroller(comptrollerAddr); CToken[] memory allMarkets = comptroller.getAllMarkets(); cTokenSymbolList = new string[](cmp_getNumberOfCurrentCTokens(allMarkets)); CToken eachCToken; uint index; for(uint i = 0; i < allMarkets.length; i++){ eachCToken = allMarkets[i]; if(!cmp_isCurrentCToken(address(eachCToken))) continue; cTokenSymbolList[index] = eachCToken.symbol(); index++; } return cTokenSymbolList; } function cmp_isCurrentCToken(address cTokenAddr) internal view returns(bool){ bool isListed; bool isComped; Comptroller comptroller = Comptroller(comptrollerAddr); (isListed, , isComped) = comptroller.markets(cTokenAddr); if(isListed && isComped) return true; return false; } function cmp_getNumberOfCurrentCTokens(CToken[] memory allMarkets) internal view returns(uint numberOfCurrentCTokens){ for(uint i = 0; i < allMarkets.length; i++){ if(cmp_isCurrentCToken(address(allMarkets[i]))) numberOfCurrentCTokens++; } return numberOfCurrentCTokens; } function cmp_getPercentageOfStakeOnSupplyMantissa(address acc, address cTokenAddr) internal view returns(uint percentageOfStakeOnSupplyMantissa){ uint supplyByTheAcc = cmp_getUnderlyingBalanceOfAnAcc(acc, cTokenAddr); return cmp_calPercentageOfStakeOnSupplyMantissa(cTokenAddr, supplyByTheAcc); } function cmp_calPercentageOfStakeOnSupplyMantissa(address cTokenAddr, uint supplyByTheAcc) internal view returns(uint percentageOfStakeOnSupplyMantissa){ uint totalSupply = cmp_getTotalSupply(cTokenAddr); return supplyByTheAcc.mul(oneMantissa).div(totalSupply); } function cmp_getPercentageOfStakeOnBorrowMantissa(address acc, address cTokenAddr) internal view returns(uint percentageOfStakeOnBorrowMantissa){ uint err; uint borrowByTheAcc; (err, ,borrowByTheAcc, ) = CToken(cTokenAddr).getAccountSnapshot(acc); if(err != 0){ return 0; } return cmp_calPercentageOfStakeOnBorrowMantissa(cTokenAddr, borrowByTheAcc); } function cmp_calPercentageOfStakeOnBorrowMantissa(address cTokenAddr, uint borrowByTheAcc) internal view returns(uint percentageOfStakeOnBorrowMantissa){ uint totalBorrow = CToken(cTokenAddr).totalBorrows(); return borrowByTheAcc.mul(oneMantissa).div(totalBorrow); } function cmp_getUnderlyingBalanceOfAnAcc(address acc, address cTokenAddr) internal view returns(uint underlyingBalanceOfAnAcc){ CToken cToken = CToken(cTokenAddr); return cToken.balanceOf(acc).mul(cToken.exchangeRateStored()).div(oneMantissa); } function cmp_getBorrowedTokenList(address acc) internal view returns(address[] memory borrowedCTokenList){ CToken[] memory allMarkets = Comptroller(comptrollerAddr).getAllMarkets(); uint length; for(uint i = 0; i < allMarkets.length; i++){ //require(false, uint2str(CToken(cDAIAddr).borrowBalanceStored(acc))); if(allMarkets[i].borrowBalanceStored(acc) == 0) continue; length++; } borrowedCTokenList = new address[](length); uint index; for(uint i = 0; i < allMarkets.length; i++){ if(allMarkets[i].borrowBalanceStored(acc) == 0) continue; borrowedCTokenList[index] = address(allMarkets[i]); index++; } return borrowedCTokenList; } function cmp_getCollateralFactorMantissa(address cTokenAddr) internal view returns(uint collateralFactorMantissa){ bool isListed; (isListed, collateralFactorMantissa, ) = Comptroller(comptrollerAddr).markets(cTokenAddr); if(!isListed) return 0; return collateralFactorMantissa; } } contract ArrayUtil { function quickSortDESC(string[] memory keys, uint[] memory values) internal pure returns (string[] memory, uint[] memory){ string[] memory keysPlus = new string[](keys.length + 1); uint[] memory valuesPlus = new uint[](values.length + 1); for(uint i = 0; i < keys.length; i++){ keysPlus[i] = keys[i]; valuesPlus[i] = values[i]; } (keysPlus, valuesPlus) = quickSort(keysPlus, valuesPlus, 0, keysPlus.length - 1); string[] memory keys_desc = new string[](keys.length); uint[] memory values_desc = new uint[](values.length); for(uint i = 0; i < keys.length; i++){ keys_desc[keys.length - 1 - i] = keysPlus[i + 1]; values_desc[keys.length - 1 - i] = valuesPlus[i + 1]; } return (keys_desc, values_desc); } function quickSort(string[] memory keys, uint[] memory values, uint left, uint right) internal pure returns (string[] memory, uint[] memory){ uint i = left; uint j = right; uint pivot = values[left + (right - left) / 2]; while (i <= j) { while (values[i] < pivot) i++; while (pivot < values[j]) j--; if (i <= j) { (keys[i], keys[j]) = (keys[j], keys[i]); (values[i], values[j]) = (values[j], values[i]); i++; j--; } } if (left < j) quickSort(keys, values, left, j); if (i < right) quickSort(keys, values, i, right); return (keys, values); } } contract Logging is StringUtil{ function debug(string memory name, string[] memory values) internal pure{ string memory log_name = append(name, ": "); string memory valueStr; for(uint i = 0; i < values.length; i++){ valueStr = append(valueStr, values[i]); valueStr = append(valueStr, ", "); } require(false, append(log_name, valueStr)); } function debug(string memory name, address[] memory values) internal pure{ string memory log_name = append(name, ": "); string memory valueStr; for(uint i = 0; i < values.length; i++){ valueStr = append(valueStr, address2str(values[i])); valueStr = append(valueStr, ", "); } require(false, append(log_name, valueStr)); } function debug(string memory name, uint[] memory values) internal pure{ string memory log_name = append(name, ": "); string memory valueStr; for(uint i = 0; i < values.length; i++){ valueStr = append(valueStr, uint2str(values[i])); valueStr = append(valueStr, ", "); } require(false, append(log_name, valueStr)); } function debug(string memory name, string memory value) internal pure{ string memory log_name = append(name, ": "); string memory valueStr = value; require(false, append(log_name, valueStr)); } function debug(string memory name, address value) internal pure{ string memory log_name = append(name, ": "); string memory valueStr = address2str(value); require(false, append(log_name, valueStr)); } function debug(string memory name, uint value) internal pure{ string memory log_name = append(name, ": "); string memory valueStr = uint2str(value); require(false, append(log_name, valueStr)); } function debug(string memory name, bool value) internal pure{ string memory log_name = append(name, ": "); string memory valueStr = bool2str(value); require(false, append(log_name, valueStr)); } event log(string name, address value); event log(string name, uint value); event log(string name, string value); event log(string name, bool value); event log(string name, uint[] value); event log(string name, address[] value); } contract CompFarmingSummaryV3Model is CompoundMethods, ArrayUtil{ uint256 constant public MAX_INT_NUMBER = 115792089237316195423570985008687907853269984665640564039457584007913129639935; enum LiquidationRiskRanking{ ZERO_RISK, INTEREST_RISK_ONLY, PRICE_MOVEMENT_RISK } struct CompProfile{ uint balance; uint yetToClaimed; } struct AccountInterestProfile{ CTokenInterest[] supplyInterests; CTokenInterest[] borrowInterests; uint totalInterestInUSD_; bool isPositiveInterest_; } struct CTokenInterest{ address cTokenAddr; uint interestRateMantissa; uint balance; uint numberOfBlocks; string underlyingSymbol_; uint interestInUSD_; } struct AccountProfile{ SupplyAsset[] suppliedAssets; BorrowAsset[] borrowedAssets; uint totalSuppliedInUSD_; uint totalBorrowedInUSD_; uint totalSuppliedInUsdAsCollateral_; uint borrowLimitPCTMantissa_; uint accountCapital_; uint[] borrowLimitPCTLineItemMantissaList; } struct SupplyAsset{ Asset asset; uint collateralFactorMantissa_; uint suppliedInUsdAsCollateral_; } struct BorrowAsset{ Asset asset; } struct Asset{ address cTokenAddr; uint amount; string underlyingSymbol_; uint underlyingDecimals_; uint valueInUSD_; uint compSpeed_; } function createCTokenInterest(address cTokenAddr, uint interestRateMantissa, uint balance, uint numberOfBlocks) internal view returns(CTokenInterest memory cTokenInterest){ cTokenInterest.cTokenAddr = cTokenAddr; cTokenInterest.interestRateMantissa = interestRateMantissa; cTokenInterest.balance = balance; cTokenInterest.numberOfBlocks = numberOfBlocks; refreshCTokenInterest(cTokenInterest); return cTokenInterest; } function refreshCTokenInterest(CTokenInterest memory cTokenInterest) internal view{ cTokenInterest.underlyingSymbol_ = cmp_getUnderlyingSymbol(cTokenInterest.cTokenAddr); cTokenInterest.interestInUSD_ = cmp_underlyingValueInUSD(cTokenInterest.balance.mul(cTokenInterest.interestRateMantissa), cTokenInterest.cTokenAddr).mul(cTokenInterest.numberOfBlocks).div(oneMantissa); } function createAccountInterestProfile(CTokenInterest[] memory supplyInterests, CTokenInterest[] memory borrowInterests) internal pure returns(AccountInterestProfile memory accountInterestProfile){ accountInterestProfile.supplyInterests = supplyInterests; accountInterestProfile.borrowInterests = borrowInterests; refreshAccountInterestProfile(accountInterestProfile); return accountInterestProfile; } function refreshAccountInterestProfile(AccountInterestProfile memory accountInterestProfile) internal pure { uint totalSupplyInterestInUSD; uint totalBorrowInterestInUSD; for(uint i = 0; i < accountInterestProfile.supplyInterests.length; i++){ totalSupplyInterestInUSD += accountInterestProfile.supplyInterests[i].interestInUSD_; } for(uint i = 0; i < accountInterestProfile.borrowInterests.length; i++){ totalBorrowInterestInUSD += accountInterestProfile.borrowInterests[i].interestInUSD_; } if(totalSupplyInterestInUSD > totalBorrowInterestInUSD){ accountInterestProfile.totalInterestInUSD_ = totalSupplyInterestInUSD.sub(totalBorrowInterestInUSD); accountInterestProfile.isPositiveInterest_ = true; } if(totalSupplyInterestInUSD <= totalBorrowInterestInUSD){ accountInterestProfile.totalInterestInUSD_ = totalBorrowInterestInUSD.sub(totalSupplyInterestInUSD); accountInterestProfile.isPositiveInterest_ = false; } } function createSupplyAsset(address cTokenAddr, uint amount) internal view returns(SupplyAsset memory supplyAsset){ Asset memory asset = createAsset(cTokenAddr, amount); supplyAsset.asset = asset; refreshSupplyAsset(supplyAsset); return supplyAsset; } function createBorrowAsset(address cTokenAddr, uint amount) internal view returns(BorrowAsset memory borrowAsset){ Asset memory asset = createAsset(cTokenAddr, amount); borrowAsset.asset = asset; return borrowAsset; } function updateSupplyAssetAmount(SupplyAsset memory supplyAsset, uint newAmount) internal view{ supplyAsset.asset.amount = newAmount; refreshAsset(supplyAsset.asset); refreshSupplyAsset(supplyAsset); } function updateBorrowAssetAmount(BorrowAsset memory borrowAsset, uint newAmount) internal view{ borrowAsset.asset.amount = newAmount; refreshAsset(borrowAsset.asset); } function refreshSupplyAsset(SupplyAsset memory supplyAsset) internal view{ supplyAsset.collateralFactorMantissa_ = cmp_getCollateralFactorMantissa(supplyAsset.asset.cTokenAddr); supplyAsset.suppliedInUsdAsCollateral_ = supplyAsset.asset.valueInUSD_.mul(supplyAsset.collateralFactorMantissa_).div(oneMantissa); } function createAsset(address cTokenAddr, uint amount) internal view returns(Asset memory asset){ updateAsset(asset, cTokenAddr, amount); return asset; } function updateAsset(Asset memory asset, address cTokenAddr, uint amount) internal view{ asset.cTokenAddr = cTokenAddr; asset.amount = amount; refreshAsset(asset); } function refreshAsset(Asset memory asset) internal view{ asset.underlyingSymbol_ = cmp_getUnderlyingSymbol(asset.cTokenAddr); asset.underlyingDecimals_ = cmp_getUnderlyingDecimals(asset.cTokenAddr); asset.valueInUSD_ = cmp_underlyingValueInUSD(asset.amount, asset.cTokenAddr); asset.compSpeed_ = cmp_getCompDistSpeedPerBlock(asset.cTokenAddr); } function createAccountProfile(SupplyAsset[] memory suppliedAssets, BorrowAsset[] memory borrowedAssets) internal pure returns(AccountProfile memory accountProfile){ accountProfile.suppliedAssets = suppliedAssets; accountProfile.borrowedAssets = borrowedAssets; refreshAccountProfile(accountProfile); } function refreshAccountProfile(AccountProfile memory accountProfile) internal pure{ accountProfile.totalSuppliedInUSD_ = calTotalSuppliedInUSD(accountProfile.suppliedAssets); accountProfile.totalBorrowedInUSD_ = calTotalBorrowedInUSD(accountProfile.borrowedAssets); accountProfile.totalSuppliedInUsdAsCollateral_ = calTotalSuppliedInUsdAsCollateral(accountProfile.suppliedAssets); accountProfile.accountCapital_ = calAccountCapital(accountProfile.totalSuppliedInUSD_, accountProfile.totalBorrowedInUSD_); accountProfile.borrowLimitPCTMantissa_ = calBorrowLimitPCTMantissa(accountProfile.totalSuppliedInUsdAsCollateral_, accountProfile.totalBorrowedInUSD_); accountProfile.borrowLimitPCTLineItemMantissaList = calBorrowLimitPCTLineItemMantissaList(accountProfile.suppliedAssets, accountProfile.borrowedAssets); } function calTotalSuppliedInUSD(SupplyAsset[] memory suppliedAssets) internal pure returns(uint totalSuppliedInUSD){ for(uint i = 0; i < suppliedAssets.length; i++){ totalSuppliedInUSD += suppliedAssets[i].asset.valueInUSD_; } return totalSuppliedInUSD; } function calTotalBorrowedInUSD(BorrowAsset[] memory borrowedAssets) internal pure returns(uint totalBorrowedInUSD){ for(uint i = 0; i < borrowedAssets.length; i++){ totalBorrowedInUSD += borrowedAssets[i].asset.valueInUSD_; } return totalBorrowedInUSD; } function calTotalSuppliedInUsdAsCollateral(SupplyAsset[] memory suppliedAssets) internal pure returns(uint totalSuppliedInUsdAsCollateral){ for(uint i = 0; i < suppliedAssets.length; i++){ totalSuppliedInUsdAsCollateral += suppliedAssets[i].suppliedInUsdAsCollateral_; } return totalSuppliedInUsdAsCollateral; } function calBorrowLimitPCTMantissa(uint totalSuppliedInUsdAsCollateral, uint totalBorrowedInUSD) internal pure returns(uint borrowLimitPCTMantissa){ if(totalSuppliedInUsdAsCollateral == 0) return oneMantissa; return totalBorrowedInUSD.mul(oneMantissa).div(totalSuppliedInUsdAsCollateral); } function calBorrowLimitPCTLineItemMantissaList(SupplyAsset[] memory suppliedAssets, BorrowAsset[] memory borrowedAssets) internal pure returns(uint[] memory borrowLimitPCTLineItemMantissaList){ borrowLimitPCTLineItemMantissaList = new uint[](suppliedAssets.length); bool _hasFound; BorrowAsset memory _borrowedAsset; for(uint i = 0; i < suppliedAssets.length; i++){ (_hasFound, _borrowedAsset) = findBorrowedAssetBycTokenAddr(suppliedAssets[i].asset.cTokenAddr, borrowedAssets); if(suppliedAssets[i].suppliedInUsdAsCollateral_ == 0){ borrowLimitPCTLineItemMantissaList[i] = MAX_INT_NUMBER; } if(!_hasFound){ borrowLimitPCTLineItemMantissaList[i] = 0; continue; } if(suppliedAssets[i].suppliedInUsdAsCollateral_ != 0){ borrowLimitPCTLineItemMantissaList[i] = _borrowedAsset.asset.valueInUSD_.mul(oneMantissa).div(suppliedAssets[i].suppliedInUsdAsCollateral_); } } return borrowLimitPCTLineItemMantissaList; } function calAccountCapital(uint totalSuppliedInUSD, uint totalBorrowedInUSD) internal pure returns(uint accountCapital){ if(totalSuppliedInUSD > totalBorrowedInUSD){ return totalSuppliedInUSD.sub(totalBorrowedInUSD); } return 0; } function findBorrowedAssetBycTokenAddr(address cTokenAddr, BorrowAsset[] memory borrowedAssets) internal pure returns(bool hasFound, BorrowAsset memory borrowAsset){ for(uint i = 0; i < borrowedAssets.length; i++){ if(borrowedAssets[i].asset.cTokenAddr == cTokenAddr) return (true, borrowedAssets[i]); } return (false, borrowAsset); } function addSuppliedAsset(AccountProfile memory accountProfile, SupplyAsset memory supplyAsset) internal view{ for(uint i = 0; i < accountProfile.suppliedAssets.length; i++){ if(accountProfile.suppliedAssets[i].asset.cTokenAddr != supplyAsset.asset.cTokenAddr) continue; updateSupplyAssetAmount(accountProfile.suppliedAssets[i], accountProfile.suppliedAssets[i].asset.amount.add(supplyAsset.asset.amount)); refreshAccountProfile(accountProfile); return; } //if not matching existing supplyAsset found uint length = accountProfile.suppliedAssets.length.add(1); SupplyAsset[] memory newSupplyAsset = new SupplyAsset[](length); for(uint i = 0; i < accountProfile.suppliedAssets.length; i++){ newSupplyAsset[i] = accountProfile.suppliedAssets[i]; } newSupplyAsset[length-1] = supplyAsset; accountProfile.suppliedAssets = newSupplyAsset; refreshAccountProfile(accountProfile); } function addBorrowAsset(AccountProfile memory accountProfile, BorrowAsset memory borrowAsset) internal view{ for(uint i = 0; i < accountProfile.borrowedAssets.length; i++){ if(accountProfile.borrowedAssets[i].asset.cTokenAddr != borrowAsset.asset.cTokenAddr) continue; updateBorrowAssetAmount(accountProfile.borrowedAssets[i], accountProfile.borrowedAssets[i].asset.amount.add(borrowAsset.asset.amount)); refreshAccountProfile(accountProfile); return; } uint length = accountProfile.borrowedAssets.length.add(1); BorrowAsset[] memory newBorrowAssets = new BorrowAsset[](length); for(uint i = 0; i < accountProfile.borrowedAssets.length; i++){ newBorrowAssets[i] = accountProfile.borrowedAssets[i]; } newBorrowAssets[length-1] = borrowAsset; accountProfile.borrowedAssets = newBorrowAssets; refreshAccountProfile(accountProfile); } function findSuppliedAsset(address cTokenAddr, SupplyAsset[] memory supplyAssets) internal pure returns(bool hasFound, SupplyAsset memory supplyAsset){ for(uint i = 0; i < supplyAssets.length; i++){ if(cTokenAddr == supplyAssets[i].asset.cTokenAddr){ return (true, supplyAssets[i]); } } return (false, supplyAsset); } function findBorrowAsset(address cTokenAddr, BorrowAsset[] memory borrowAssets) internal pure returns(bool hasFound, BorrowAsset memory borrowAsset){ for(uint i = 0; i < borrowAssets.length; i++){ if(cTokenAddr == borrowAssets[i].asset.cTokenAddr){ return (true, borrowAssets[i]); } } return (false, borrowAsset); } function removeEmptySupplyAsset(SupplyAsset[] memory supplyAssets) internal pure returns(SupplyAsset[] memory newSupplyAssets){ uint length; for(uint i = 0; i < supplyAssets.length; i++){ if(supplyAssets[i].asset.valueInUSD_ == 0) continue; length++; } newSupplyAssets = new SupplyAsset[](length); uint index; for(uint i = 0; i < supplyAssets.length; i++){ if(supplyAssets[i].asset.valueInUSD_ == 0) continue; newSupplyAssets[index] = supplyAssets[i]; index++; } return newSupplyAssets; } function removeEmptyBorrowAsset(BorrowAsset[] memory borrowAssets) internal pure returns(BorrowAsset[] memory newBorrowAssets){ uint length; for(uint i = 0; i < borrowAssets.length; i++){ if(borrowAssets[i].asset.valueInUSD_ == 0) continue; length++; } newBorrowAssets = new BorrowAsset[](length); uint index; for(uint i = 0; i < borrowAssets.length; i++){ if(borrowAssets[i].asset.valueInUSD_ == 0) continue; newBorrowAssets[index] = borrowAssets[i]; index++; } return newBorrowAssets; } } contract CompFarmingSummaryV3 is CompFarmingSummaryV3Model{ string constant public version = "v3"; uint constant internal n80PCTMantissa = 800000000000000000; uint constant internal n1PCTMantissa = 10000000000000000; uint constant internal borrowLimitPCTDelta = 50000000000000000; function getCompProfile(address acc) external returns(CompProfile memory compProfile){ return getCompProfileInternal(acc); } function getCOMPPriceInUSD() public view returns(uint compPriceInUSD){ return cmp_getUnderlyingPriceInUSD(cCOMPAddr); } //bulk testing required function getTotalCompReceivable(address acc, uint numberOfBlocks) public view returns(uint totalCompReceivable){ return getTotalCompReceivableInternal(acc, numberOfBlocks); } function getTotalCompReceivablByAP(AccountProfile memory accountProfile, uint numberOfBlocks) public view returns(uint compReceivable){ return getTotalCompReceivableInternal(accountProfile, numberOfBlocks); } //bulk testing done function getAccountProfile(address acc) external view returns(AccountProfile memory accountProfile){ return getAccountProfileInternal(acc); } function getAccountInterestProfile(address acc, uint numberOfBlocks) external view returns(AccountInterestProfile memory accountInterestProfile){ return getAccountInterestProfileInternal(acc, numberOfBlocks); } function getFarmingAccountProfileByAP(AccountProfile memory accountProfile, uint targetedBorrowLimitPCTMantissa) public view returns(bool isValidated, AccountProfile memory farmingAccountProfile){ return getFarmingAccountProfileInternal(accountProfile, targetedBorrowLimitPCTMantissa); } function getAccountInterestProfileByAP(AccountProfile memory accountProfile, uint numberOfBlocks) public view returns(AccountInterestProfile memory accountInterestProfile){ return getAccountInterestProfileInternal(accountProfile, numberOfBlocks); } //bulk testing done function getLiquidationRiskRanking(address acc) external view returns(LiquidationRiskRanking liquidationRiskRanking){ return getLiquidationRiskRankingInternal(acc); } function getLiquidationRiskRankingByAP(AccountProfile memory accountProfile) public view returns(LiquidationRiskRanking liquidationRiskRanking){ return getLiquidationRiskRankingInternal(accountProfile); } function getMaxInterestAccountProfileByAP(AccountProfile memory accountProfile) public view returns(bool isValidated, AccountProfile memory maxInterestAccountProfile){ return getMaxInterestAccountProfileInternal(accountProfile); } //internal functions below function getTotalCompReceivableInternal(address acc, uint numberOfBlocks) internal view returns(uint compReceivable){ return getTotalCompReceivableInternal(getAccountProfileInternal(acc), numberOfBlocks); } function getCompReceivableOfCToken(uint supplyByTheAcc, uint borrowByTheAcc, address cTokenAddr, uint numberOfBlocks) internal view returns(uint compReceivableByCToken){ uint compDistAmount = cmp_getCompDistAmount(cTokenAddr, numberOfBlocks); uint percentageOfStakeOnSupplyMantissa = cmp_calPercentageOfStakeOnSupplyMantissa(cTokenAddr, supplyByTheAcc); uint percentageOfStakeOnBorrowMantissa = cmp_calPercentageOfStakeOnBorrowMantissa(cTokenAddr, borrowByTheAcc); uint decimals = cmp_getUnderlyingDecimals(cCOMPAddr); //formula: compDistAmount * (stakeSupplied + stakeBorrowed) compReceivableByCToken = compDistAmount.mul(percentageOfStakeOnSupplyMantissa.add(percentageOfStakeOnBorrowMantissa)).div(10**decimals); return compReceivableByCToken; } function getTotalCompReceivableInternal(AccountProfile memory accountProfile, uint numberOfBlocks) internal view returns(uint compReceivable){ SupplyAsset[] memory suppliedAssets = accountProfile.suppliedAssets; BorrowAsset[] memory borrowedAssets = accountProfile.borrowedAssets; for(uint i = 0; i < suppliedAssets.length; i++){ compReceivable += getCompReceivableOfCToken(suppliedAssets[i].asset.amount, 0, suppliedAssets[i].asset.cTokenAddr, numberOfBlocks); } for(uint i = 0; i < borrowedAssets.length; i++){ compReceivable += getCompReceivableOfCToken(0, borrowedAssets[i].asset.amount, borrowedAssets[i].asset.cTokenAddr, numberOfBlocks); } return compReceivable; } function getCompProfileInternal(address acc) internal returns(CompProfile memory compProfile){ compProfile.balance = ERC20(compAddr).balanceOf(acc); CompoundLens compoundLens = CompoundLens(compoundLensAddr); compProfile.yetToClaimed = compoundLens.getCompBalanceMetadataExt(Comp(compAddr), ComptrollerLensInterface(comptrollerAddr), acc).allocated; } function getAccountProfileInternal(address acc) internal view returns(AccountProfile memory accountProfile){ SupplyAsset[] memory suppliedAssets = getSuppliedAssets(acc); BorrowAsset[] memory borrowedAssets = getBorrowedAssets(acc); return createAccountProfile(suppliedAssets, borrowedAssets); } function getSuppliedAssets(address acc) internal view returns(SupplyAsset[] memory suppliedAssets){ address[] memory suppliedCTokenAddrList = Comptroller(comptrollerAddr).getAssetsIn(acc); suppliedAssets = new SupplyAsset[](suppliedCTokenAddrList.length); for(uint i = 0; i < suppliedCTokenAddrList.length; i++){ //filter out cSAI //if(suppliedCTokenAddrList[i] == 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC) continue; suppliedAssets[i] = createSupplyAsset(suppliedCTokenAddrList[i], cmp_getUnderlyingBalanceOfAnAcc(acc, suppliedCTokenAddrList[i])); } suppliedAssets = removeEmptySupplyAsset(suppliedAssets); return suppliedAssets; } function getBorrowedAssets(address acc) internal view returns(BorrowAsset[] memory borrowedAssets){ address[] memory borrowedCTokenList = cmp_getBorrowedTokenList(acc); borrowedAssets = new BorrowAsset[](borrowedCTokenList.length); for(uint i = 0; i < borrowedCTokenList.length; i++){ borrowedAssets[i] = createBorrowAsset(borrowedCTokenList[i], CToken(borrowedCTokenList[i]).borrowBalanceStored(acc)); } borrowedAssets = removeEmptyBorrowAsset(borrowedAssets); return borrowedAssets; } function getFarmingAccountProfileInternal(AccountProfile memory accountProfile, uint targetedBorrowLimitPCTMantissa) internal view returns(bool isValidated, AccountProfile memory farmingAccountProfile){ //liquidation risk ranking needs to be lower or equials to 2 if(uint(getLiquidationRiskRankingInternal(accountProfile)) > 1) return (false, farmingAccountProfile); //each supplied asset, run borrowANDsupplym check util borrowLimitsPCTPerAsset hits 80%withDelta SupplyAsset[] memory suppliedAssets = accountProfile.suppliedAssets; for(uint i = 0; i < suppliedAssets.length; i++){ if(suppliedAssets[i].collateralFactorMantissa_ == 0) continue; uint maxBorrowAmount; BorrowAsset memory moreBorrowAsset; SupplyAsset memory moreSupplyAsset; while(accountProfile.borrowLimitPCTLineItemMantissaList[i] <= targetedBorrowLimitPCTMantissa.sub(n1PCTMantissa)){ maxBorrowAmount = suppliedAssets[i].asset.amount.mul(suppliedAssets[i].collateralFactorMantissa_).mul(targetedBorrowLimitPCTMantissa.sub(accountProfile.borrowLimitPCTLineItemMantissaList[i])).div(oneMantissa).div(oneMantissa); moreBorrowAsset = createBorrowAsset(suppliedAssets[i].asset.cTokenAddr, maxBorrowAmount); moreSupplyAsset = createSupplyAsset(suppliedAssets[i].asset.cTokenAddr, maxBorrowAmount); addBorrowAsset(accountProfile, moreBorrowAsset); addSuppliedAsset(accountProfile, moreSupplyAsset); } } return (true, accountProfile); } function getAccountInterestProfileInternal(address acc, uint numberOfBlocks) internal view returns(AccountInterestProfile memory accountInterestProfile){ return getAccountInterestProfileInternal(getAccountProfileInternal(acc), numberOfBlocks); } function getAccountInterestProfileInternal(AccountProfile memory accountProfile, uint numberOfBlocks) internal view returns(AccountInterestProfile memory accountInterestProfile){ return createAccountInterestProfile(getSupplyInterests(accountProfile.suppliedAssets, numberOfBlocks), getBorrowInterests(accountProfile.borrowedAssets, numberOfBlocks)); } function getSupplyInterests(SupplyAsset[] memory supplyAssets, uint numberOfBlocks) internal view returns(CTokenInterest[] memory supplyInterests){ supplyInterests = new CTokenInterest[](supplyAssets.length); address cTokenAddr; uint interestRateMantissa; uint balance; for(uint i = 0; i < supplyAssets.length; i++){ cTokenAddr = supplyAssets[i].asset.cTokenAddr; interestRateMantissa = CToken(cTokenAddr).supplyRatePerBlock(); balance = supplyAssets[i].asset.amount; supplyInterests[i] = createCTokenInterest(cTokenAddr, interestRateMantissa, balance, numberOfBlocks); } return supplyInterests; } function getBorrowInterests(BorrowAsset[] memory borrowedAssets, uint numberOfBlocks) internal view returns(CTokenInterest[] memory borrowInterests){ borrowInterests = new CTokenInterest[](borrowedAssets.length); address cTokenAddr; uint interestRateMantissa; uint balance; for(uint i = 0; i < borrowedAssets.length; i++){ cTokenAddr = borrowedAssets[i].asset.cTokenAddr; interestRateMantissa = CToken(cTokenAddr).borrowRatePerBlock(); balance = borrowedAssets[i].asset.amount; borrowInterests[i] = createCTokenInterest(cTokenAddr, interestRateMantissa, balance, numberOfBlocks); } return borrowInterests; } function getLiquidationRiskRankingInternal(AccountProfile memory accountProfile) internal view returns(LiquidationRiskRanking liquidationRiskRanking){ //find all the supplied asset //find all the matching asset //find calBorrowLimitPCTLineItemMantissaList //check to see if any borrowed asset outside from supplied asset, acceptable asset require valueInUSD over 1 //check to see if any borrowed asset with underlying supplied of 0 collateral factor //get account interest profile liquidationRiskRanking = LiquidationRiskRanking.ZERO_RISK; /// if(!getAccountInterestProfileInternal(accountProfile, 1).isPositiveInterest_){ liquidationRiskRanking = LiquidationRiskRanking.INTEREST_RISK_ONLY; } for(uint i = 0; i < accountProfile.borrowLimitPCTLineItemMantissaList.length; i++){ if(accountProfile.borrowLimitPCTLineItemMantissaList[i] == MAX_INT_NUMBER) continue; if(accountProfile.borrowLimitPCTLineItemMantissaList[i] > oneMantissa) { liquidationRiskRanking = LiquidationRiskRanking.PRICE_MOVEMENT_RISK; break; } } bool hasFound; SupplyAsset memory suppliedAsset; for(uint i = 0; i < accountProfile.borrowedAssets.length; i++){ if(accountProfile.borrowedAssets[i].asset.valueInUSD_ < oneMantissa) continue; //filter small value asset(asset USD value less than 1 USD) (hasFound, suppliedAsset) = findSuppliedAsset(accountProfile.borrowedAssets[i].asset.cTokenAddr, accountProfile.suppliedAssets); if(!hasFound){ liquidationRiskRanking = LiquidationRiskRanking.PRICE_MOVEMENT_RISK; break; } if(suppliedAsset.collateralFactorMantissa_ == 0){ liquidationRiskRanking = LiquidationRiskRanking.PRICE_MOVEMENT_RISK; break; } } return liquidationRiskRanking; } function getLiquidationRiskRankingInternal(address acc) internal view returns(LiquidationRiskRanking liquidationRiskRanking){ return getLiquidationRiskRankingInternal(getAccountProfileInternal(acc)); } function getMaxInterestAccountProfileInternal(AccountProfile memory accountProfile) internal view returns(bool isValidated, AccountProfile memory maxInterestAccountProfile){ if(uint(getLiquidationRiskRankingInternal(accountProfile)) > 1) return (false, maxInterestAccountProfile); SupplyAsset[] memory newSupplyAssets = new SupplyAsset[](accountProfile.suppliedAssets.length); address cTokenAddr; uint amount; bool hasFound; BorrowAsset memory borrowedAsset; for(uint i = 0; i < accountProfile.suppliedAssets.length; i++){ cTokenAddr = accountProfile.suppliedAssets[i].asset.cTokenAddr; (hasFound, borrowedAsset) = findBorrowAsset(cTokenAddr, accountProfile.borrowedAssets); if(!hasFound){ amount = accountProfile.suppliedAssets[i].asset.amount; } amount = accountProfile.suppliedAssets[i].asset.amount.sub(borrowedAsset.asset.amount); newSupplyAssets[i] = createSupplyAsset(cTokenAddr, amount); } BorrowAsset[] memory borrowedAssets; return (true, createAccountProfile(newSupplyAssets, borrowedAssets)); } }
formula: compDistAmount (stakeSupplied + stakeBorrowed)
function getCompReceivableOfCToken(uint supplyByTheAcc, uint borrowByTheAcc, address cTokenAddr, uint numberOfBlocks) internal view returns(uint compReceivableByCToken){ uint compDistAmount = cmp_getCompDistAmount(cTokenAddr, numberOfBlocks); uint percentageOfStakeOnSupplyMantissa = cmp_calPercentageOfStakeOnSupplyMantissa(cTokenAddr, supplyByTheAcc); uint percentageOfStakeOnBorrowMantissa = cmp_calPercentageOfStakeOnBorrowMantissa(cTokenAddr, borrowByTheAcc); uint decimals = cmp_getUnderlyingDecimals(cCOMPAddr); compReceivableByCToken = compDistAmount.mul(percentageOfStakeOnSupplyMantissa.add(percentageOfStakeOnBorrowMantissa)).div(10**decimals); return compReceivableByCToken; }
5,983,965
/** *Submitted for verification at Etherscan.io on 2022-02-07 */ /** *Submitted for verification at Etherscan.io on 2022-01-25 */ // SPDX-License-Identifier: MIT pragma solidity >= 0.6.0 <0.8.0; pragma experimental ABIEncoderV2; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } 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); } 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; } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); function setBuyFee(uint256 _fee) external returns(bool); function setSellFee(uint256 _fee) external returns(bool); function setBuyLiqDistribute(uint256 _distribution) external returns(bool); function setSellLiqDistribute(uint256 _distribution) external returns(bool); function setMaxBuyLock(bool _lock) external; function updateLiquidityWallet(address _wallet) external; function updateMarketingWallet(address _wallet) external; function swapAndLiquifyEnabled() external view returns(bool); function setSwapAndLiquifyEnabled(bool _enabled) external; function setSwapAndLiquifyLimit(uint256 _limit) external; /**/ } /** * @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; } } /** * @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() public { _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); } } /** * @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 Ownable, IERC20, IERC20Metadata { using SafeMath for uint256; IUniswapV2Router02 private uniswapRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint buyFee = 3; uint sellFee = 3; uint buyLiqDistribute = 50; uint sellLiqDistribute = 50; uint256 _swapAndLiquifyLimit = 10 ** 3 * 10 ** 18; bool maxBuyLock; bool _swapAndLiquifyEnabled; bool inSwapAndLiquify; address private liquidityWallet = 0x0DE2CB186C5590311D9aeF5Fd83F390d064Be603 ; address private marketingWallet = 0x7a099B1d22d601190d456549Cfb6e8a66cea57d6 ; /** * @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. */ modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(string memory name_, string memory symbol_) public { _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; } function swapAndLiquifyEnabled() public view virtual override returns (bool) { return _swapAndLiquifyEnabled; } /** * @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)); 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue)); return true; } function setBuyFee(uint256 _fee) external virtual override onlyOwner returns(bool) { require(_fee > 0 && _fee < 100, "fee must be greater than zero"); buyFee = _fee; return true; } function setSellFee(uint256 _fee) external virtual override onlyOwner returns(bool) { require(_fee > 0 && _fee < 100, "fee must be greater than zero"); sellFee = _fee; return true; } function setBuyLiqDistribute(uint256 _distribute) external virtual override onlyOwner returns(bool) { require(_distribute > 0 && _distribute < 100, "discount must be greater than zero"); buyLiqDistribute = _distribute; return true; } function setSellLiqDistribute(uint256 _distribute) external virtual override onlyOwner returns(bool) { require(_distribute > 0 && _distribute < 100, "discount must be greater than zero"); sellLiqDistribute = _distribute; return true; } function updateLiquidityWallet(address _wallet) external virtual override onlyOwner { require(_wallet != address(0), "address is null"); require(_wallet != liquidityWallet, "address is already setted"); liquidityWallet = _wallet; } function updateMarketingWallet(address _wallet) external virtual override onlyOwner { require(_wallet != address(0), "address is null"); require(_wallet != marketingWallet, "address is already setted"); marketingWallet = _wallet; } function setSwapAndLiquifyEnabled(bool _enabled) external virtual override onlyOwner { _swapAndLiquifyEnabled = _enabled; } function setSwapAndLiquifyLimit(uint256 _limit) external virtual override onlyOwner { require(_limit > 0, "Not able zero"); _swapAndLiquifyLimit = _limit; } /** * @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 ) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); address _pair = IUniswapV2Factory(uniswapRouter.factory()).getPair(address(this), uniswapRouter.WETH()); if (sender == _pair) { if (maxBuyLock) { require(amount <= totalSupply() / 100, "Exceed buying limit"); } uint256 fee = amount * buyFee / 100; uint256 rest = amount - fee; _executeTransfer(sender, recipient, rest); _executeTransfer(sender, address(this), fee * buyLiqDistribute / 100); _executeTransfer(sender, marketingWallet, fee * (100 - buyLiqDistribute) / 100); } else { if (sender == owner() || recipient == owner()) { _executeTransfer(sender, recipient, amount); } else { uint256 fee = amount * sellFee / 100; uint256 rest = amount - fee; _executeTransfer(sender, recipient, rest); _executeTransfer(sender, address(this), fee * sellLiqDistribute / 100); _executeTransfer(sender, marketingWallet, fee * (100 - sellLiqDistribute) / 100); if (_swapAndLiquifyEnabled && _pair != address(0)) { uint256 _tokenBalance = balanceOf(address(this)); if (_tokenBalance >= _swapAndLiquifyLimit) { swapTokensForEth(_swapAndLiquifyLimit); } } } } } function setMaxBuyLock(bool _lock) external virtual override onlyOwner { maxBuyLock = _lock; } function _executeTransfer( 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"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, tokenAmount * 5); // make the swap uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount / 2, 0, // accept any amount of ETH path, address(this), block.timestamp ); uint256 ethAmount = address(this).balance; (uint _amountToken, uint _amountETH) = calculateTokenAndETHForLiquify(address(this), uniswapRouter.WETH(), tokenAmount / 2, ethAmount, 0, 0); uint _balanceToken = balanceOf(address(this)); if (ethAmount >= _amountETH && _balanceToken >= _amountToken) { // add the liquidity uniswapRouter.addLiquidityETH{value: _amountETH}( address(this), _amountToken, 0, // slippage is unavoidable 0, // slippage is unavoidable marketingWallet, block.timestamp ); } } function calculateTokenAndETHForLiquify( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) private view returns (uint amountA, uint amountB) { (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(uniswapRouter.factory(), tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } /** @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); _balances[account] = _balances[account].sub(amount); _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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 private immutable _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor(uint8 decimals_) public { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } /** * @title BurnableERC20 * @dev Implementation of the BurnableERC20 */ contract Mizuchi is ERC20Decimals, ERC20Burnable { struct AirDrop { address to; uint distribute; } constructor() ERC20("Mizuchi", "Mizuchi") public ERC20Decimals(18) { uint256 supply = 7 * 10 ** 33 * 10 ** 18; _mint(_msgSender(), supply); } function decimals() public view virtual override(ERC20, ERC20Decimals) returns (uint8) { return super.decimals(); } function airDrop(AirDrop[] calldata list) external onlyOwner { require(list.length > 0, "No list"); for (uint i; i < list.length; i ++) { transfer(list[i].to, totalSupply() * list[i].distribute / 100); } } receive() external payable {} }
generate the uniswap pair path of token -> weth make the swap add the liquidity
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, tokenAmount * 5); uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount / 2, path, address(this), block.timestamp ); uint256 ethAmount = address(this).balance; (uint _amountToken, uint _amountETH) = calculateTokenAndETHForLiquify(address(this), uniswapRouter.WETH(), tokenAmount / 2, ethAmount, 0, 0); uint _balanceToken = balanceOf(address(this)); if (ethAmount >= _amountETH && _balanceToken >= _amountToken) { address(this), _amountToken, marketingWallet, block.timestamp ); } }
111,752
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IEdenToken.sol"; import "./lib/AccessControl.sol"; /** * @title EdenToken * @dev ERC-20 with minting + add-ons to allow for offchain signing * See EIP-712, EIP-2612, and EIP-3009 for details */ contract EdenToken is AccessControl, IEdenToken { /// @notice EIP-20 token name for this token string public override name = "Eden"; /// @notice EIP-20 token symbol for this token string public override symbol = "EDEN"; /// @notice EIP-20 token decimals for this token uint8 public override constant decimals = 18; /// @notice Total number of tokens in circulation uint256 public override totalSupply; /// @notice Max total supply uint256 public constant override maxSupply = 250_000_000e18; // 250 million /// @notice Minter role bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @notice Address which may change token metadata address public override metadataManager; /// @dev Allowance amounts on behalf of others mapping (address => mapping (address => uint256)) public override allowance; /// @dev Official record of token balanceOf for each account mapping (address => uint256) public override balanceOf; /// @notice The EIP-712 typehash for the contract's domain /// keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") bytes32 public constant override DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; /// @notice The EIP-712 version hash /// keccak256("1"); bytes32 public constant override VERSION_HASH = 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6; /// @notice The EIP-712 typehash for permit (EIP-2612) /// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice The EIP-712 typehash for transferWithAuthorization (EIP-3009) /// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"); bytes32 public constant override TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; /// @notice The EIP-712 typehash for receiveWithAuthorization (EIP-3009) /// keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant override RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; /// @notice A record of states for signing / validating signatures mapping (address => uint) public override nonces; /// @dev authorizer address > nonce > state (true = used / false = unused) mapping (address => mapping (bytes32 => bool)) public authorizationState; /** * @notice Construct a new Eden token * @param _admin Default admin role */ constructor(address _admin) { metadataManager = _admin; emit MetadataManagerChanged(address(0), metadataManager); _setupRole(DEFAULT_ADMIN_ROLE, _admin); } /** * @notice Change the metadataManager address * @param newMetadataManager The address of the new metadata manager * @return true if successful */ function setMetadataManager(address newMetadataManager) external override returns (bool) { require(msg.sender == metadataManager, "Eden::setMetadataManager: only MM can change MM"); emit MetadataManagerChanged(metadataManager, newMetadataManager); metadataManager = newMetadataManager; return true; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param amount The number of tokens to be minted * @return Boolean indicating success of mint */ function mint(address dst, uint256 amount) external override returns (bool) { require(hasRole(MINTER_ROLE, msg.sender), "Eden::mint: only minters can mint"); require(totalSupply + amount <= maxSupply, "Eden::mint: exceeds max supply"); require(dst != address(0), "Eden::mint: cannot transfer to the zero address"); totalSupply = totalSupply + amount; balanceOf[dst] = balanceOf[dst] + amount; emit Transfer(address(0), dst, amount); return true; } /** * @notice Burn tokens * @param amount The number of tokens to burn * @return Boolean indicating success of burn */ function burn(uint256 amount) external override returns (bool) { balanceOf[msg.sender] = balanceOf[msg.sender] - amount; totalSupply = totalSupply - amount; emit Transfer(msg.sender, address(0), amount); return true; } /** * @notice Update the token name and symbol * @param tokenName The new name for the token * @param tokenSymbol The new symbol for the token * @return true if successful */ function updateTokenMetadata(string memory tokenName, string memory tokenSymbol) external override returns (bool) { require(msg.sender == metadataManager, "Eden::updateTokenMeta: only MM can update token metadata"); name = tokenName; symbol = tokenSymbol; emit TokenMetaUpdated(name, symbol); return true; } /** * @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) * It is recommended to use increaseAllowance and decreaseAllowance instead * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @notice Increase the allowance by a given amount * @param spender Spender's address * @param addedValue Amount of increase in allowance * @return True if successful */ function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] + addedValue ); return true; } /** * @notice Decrease the allowance by a given amount * @param spender Spender's address * @param subtractedValue Amount of decrease in allowance * @return True if successful */ function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] - subtractedValue ); return true; } /** * @notice Triggers an approval from owner to spender * @param owner The address to approve from * @param spender The address to be approved * @param value The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "Eden::permit: signature expired"); bytes32 encodeData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); _validateSignedData(owner, encodeData, v, r, s); _approve(owner, spender, value); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external override returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = allowance[src][spender]; if (spender != src && spenderAllowance != type(uint256).max) { uint256 newAllowance = spenderAllowance - amount; allowance[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Transfer tokens with a signed authorization * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @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 transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external override { require(block.timestamp > validAfter, "Eden::transferWithAuth: auth not yet valid"); require(block.timestamp < validBefore, "Eden::transferWithAuth: auth expired"); require(!authorizationState[from][nonce], "Eden::transferWithAuth: auth already used"); bytes32 encodeData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce)); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transferTokens(from, to, value); } /** * @notice Receive a transfer with a signed authorization from the payer * @dev This has an additional check to ensure that the payee's address matches * the caller of this function to prevent front-running attacks. * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external override { require(to == msg.sender, "Eden::receiveWithAuth: caller must be the payee"); require(block.timestamp > validAfter, "Eden::receiveWithAuth: auth not yet valid"); require(block.timestamp < validBefore, "Eden::receiveWithAuth: auth expired"); require(!authorizationState[from][nonce], "Eden::receiveWithAuth: auth already used"); bytes32 encodeData = keccak256(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce)); _validateSignedData(from, encodeData, v, r, s); authorizationState[from][nonce] = true; emit AuthorizationUsed(from, nonce); _transferTokens(from, to, value); } /** * @notice EIP-712 Domain separator * @return Separator */ function getDomainSeparator() public view override returns (bytes32) { return keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), VERSION_HASH, block.chainid, address(this) ) ); } /** * @notice Recovers address from signed data and validates the signature * @param signer Address that signed the data * @param encodeData Data signed by the address * @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 _validateSignedData(address signer, bytes32 encodeData, uint8 v, bytes32 r, bytes32 s) internal view { bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", getDomainSeparator(), encodeData ) ); address recoveredAddress = ecrecover(digest, v, r, s); // Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages require(recoveredAddress != address(0) && recoveredAddress == signer, "Eden::validateSig: invalid signature"); } /** * @notice Approval implementation * @param owner The address of the account which owns tokens * @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) */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "Eden::_approve: approve from the zero address"); require(spender != address(0), "Eden::_approve: approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Transfer implementation * @param from The address of the account which owns tokens * @param to The address of the account which is receiving tokens * @param value The number of tokens that are being transferred */ function _transferTokens(address from, address to, uint256 value) internal { require(to != address(0), "Eden::_transferTokens: cannot transfer to the zero address"); balanceOf[from] = balanceOf[from] - value; balanceOf[to] = balanceOf[to] + value; emit Transfer(from, to, value); } }
Decrease the allowance by a given amount spender Spender's address subtractedValue Amount of decrease in allowance return True if successful/
function decreaseAllowance(address spender, uint256 subtractedValue) external override returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] - subtractedValue ); return true; }
13,062,039
pragma solidity ^0.5.0; import "testeth/Log.sol"; import "testeth/Account.sol"; import "testeth/Assert.sol"; import "./MetaTransactionPool.sol"; contract ERC20Events { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } contract ERC20Interface is ERC20Events { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint); function allowance(address tokenOwner, address spender) public view returns (uint); function approve(address spender, uint amount) public returns (bool); function transfer(address to, uint amount) public returns (bool); function transferFrom( address from, address to, uint amount ) public returns (bool); } contract ERC20Token is DSMath, ERC20Interface { // Standard EIP20 Name, Symbol, Decimals string public symbol = "INTCOIN"; string public name = "InterestCoin"; string public version = "1.0.0"; uint8 public decimals = 18; uint256 public supply; function totalSupply() public view returns (uint256) { return supply; } constructor(address owner, uint256 amount) public { balances[owner] = amount; supply = amount; } // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) approvals; // Standard EIP20: BalanceOf, Transfer, TransferFrom, Allow, Allowance methods.. // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // Transfer the balance from owner's account to another account function transfer(address to, uint256 tokens) public returns (bool success) { return transferFrom(msg.sender, to, tokens); } // Send `tokens` amount of tokens from address `from` to address `to` // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { if (from != msg.sender) approvals[from][msg.sender] = sub(approvals[from][msg.sender], tokens); balances[from] = sub(balances[from], tokens); balances[to] = add(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint256 tokens) public returns (bool success) { approvals[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function specialApproval(address from, address spender, uint256 tokens) public { approvals[from][spender] = tokens; } // ------------------------------------------------------------------------ // 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 view returns (uint remaining) { return approvals[tokenOwner][spender]; } } contract User { ERC20Token coin; function () external payable {} function setToken(address _token) public { coin = ERC20Token(_token); } function transferFrom(address from, address to, uint256 tokens) public { coin.transferFrom(from, to, tokens); } function transfer(address to, uint256 tokens) public { coin.transfer(to, tokens); } function approve(address spender, uint256 tokens) public { coin.approve(spender, tokens); } } contract TestMetaTransactionPool_Claim { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), true); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract TestMetaTransactionPool_ClaimAndMove { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0100000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), true); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 9 ether); Assert.equal(coin.balanceOf(address(user2)), 1 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 0 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract TestMetaTransactionPool_Move { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; address account2; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); account2 = msg.sender; uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } // account 2 sends to account 3 function check_a5_buildNewTransfer_useAccount3() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(keccak256("new nonce")), false, false, token, 8 ether, // the balance of account 2 feeRecipient, fee, // 1 ether fee expiry)) )); Account.sign(2, releaseHash); } bytes32[] signatures2; function check_a6_attemptMoveTransfer_useAccount3(uint8 v, bytes32 r, bytes32 s) public { // MOVE destination bytes32 destinationTemp = bytes32(uint256(0x0200000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(keccak256("new nonce"))) >> 8)); address sendr = msg.sender; assembly { destinationTemp := add(destinationTemp, sendr) } bytes32 senderSigVBytes; assembly { senderSigVBytes := add(0, v) } signatures2.push(senderSigVBytes); signatures2.push(r); signatures2.push(s); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(account2, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); instance.transfer( destinationTemp, // 0x00 or 01 or 02 ... 0000 ... address token, 8 ether, feeRecipient, fee, // 1 ether fee expiry, signatures2); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 1 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 8 ether); Assert.equal(coin.balanceOf(address(user2)), 1 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract TestMetaTransactionPool_Shift { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; address account2; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); account2 = msg.sender; uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } // account 2 sends to account 3 function check_a5_buildNewTransfer_useAccount3() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), false, false, token, 8 ether, // the balance of account 2 feeRecipient, fee, // 1 ether fee expiry)) )); Account.sign(2, releaseHash); } bytes32[] signatures2; function check_a6_attemptMoveTransfer_useAccount3(uint8 v, bytes32 r, bytes32 s) public { // MOVE destination bytes32 destinationTemp = bytes32(uint256(0x0300000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); address sendr = msg.sender; assembly { destinationTemp := add(destinationTemp, sendr) } bytes32 senderSigVBytes; assembly { senderSigVBytes := add(0, v) } signatures2.push(senderSigVBytes); signatures2.push(r); signatures2.push(s); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(account2, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); instance.transfer( destinationTemp, // 0x00 or 01 or 02 ... 0000 ... address token, 8 ether, feeRecipient, fee, // 1 ether fee expiry, signatures2); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 8 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 2 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract TestMetaTransactionPool_Claim_invalidExpiry { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp; bytes32 releaseHash; function check_a0_secondAccount_useAccount2_increaseTime86400() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2_shouldThrow(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), true); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract TestMetaTransactionPool_Claim_invalidSenderSignature { User user1 = new User(); User user2 = new User(); ERC20Token coin = new ERC20Token(address(user1), 100 ether); MetaTransactionPool instance = new MetaTransactionPool(); address recipient; address token = address(coin); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp; bytes32 releaseHash; function check_a0_secondAccount_useAccount2_increaseTime86400() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1() public { user1.setToken(address(coin)); user2.setToken(address(coin)); sndr = msg.sender; Assert.equal(coin.balanceOf(address(user1)), 100 ether); Assert.equal(coin.balanceOf(address(user2)), 0 ether); user1.transfer(msg.sender, 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 10 ether); coin.specialApproval(msg.sender, address(instance), 10 ether); Assert.equal(coin.allowance(address(msg.sender), address(instance)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2_shouldThrow(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(bytes32(0)); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(coin.balanceOf(address(sndr)), 10 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 0 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 10 ether); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), true); Assert.equal(coin.balanceOf(address(sndr)), 0 ether); Assert.equal(coin.balanceOf(address(msg.sender)), 0 ether); Assert.equal(coin.balanceOf(address(instance)), 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(coin)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(coin)), 1 ether); Assert.equal(coin.allowance(address(sndr), address(instance)), 0 ether); } } contract MetaTransactionPoolSpecial is MetaTransactionPool { function specialDeposit(address sendr) payable public { tokenBalances[sendr][address(0)] = msg.value; } } contract TestMetaTransactionPool_Claim_Ether { User user1 = new User(); User user2 = new User(); MetaTransactionPoolSpecial instance = new MetaTransactionPoolSpecial(); address recipient; address token = address(0); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; // 10 ether value function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1_useValue10000000000000000000() public payable { sndr = msg.sender; instance.specialDeposit.value(10 ether)(msg.sender); Assert.equal(address(instance).balance, 10 ether); Assert.equal(msg.value, 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(0)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); Assert.equal(instance.tokenBalances(msg.sender, address(token)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(token)), 0 ether); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.tokenBalances(msg.sender, address(token)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(token)), 1 ether); } } contract TestMetaTransactionPool_ClaimAndMove_Ether { User user1 = new User(); User user2 = new User(); MetaTransactionPoolSpecial instance = new MetaTransactionPoolSpecial(); address recipient; address token = address(0); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1_useValue10000000000000000000() public payable { sndr = msg.sender; instance.specialDeposit.value(10 ether)(msg.sender); Assert.equal(address(instance).balance, 10 ether); Assert.equal(msg.value, 10 ether); Assert.equal(instance.tokenBalances(msg.sender, address(0)), 10 ether); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0100000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = address(user1); // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(address(instance).balance, 10 ether); Assert.equal(address(user1).balance, 0 ether); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), false); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.invalidatedHashes(sndr, releaseHash), true); Assert.equal(address(instance).balance, 0 ether); Assert.equal(address(user1).balance, 9 ether); Assert.equal(address(user2).balance, 1 ether); } } contract TestMetaTransactionPool_Move_Ether { User user1 = new User(); User user2 = new User(); MetaTransactionPoolSpecial instance = new MetaTransactionPoolSpecial(); address recipient; address token = address(0); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1_useValue10000000000000000000() public payable { sndr = msg.sender; instance.specialDeposit.value(10 ether)(msg.sender); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; address account2; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); account2 = msg.sender; uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(instance.tokenBalances(address(msg.sender), address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 0 ether); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.tokenBalances(address(msg.sender), address(0)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 1 ether); } // account 2 sends to account 3 function check_a5_buildNewTransfer_useAccount3() public { recipient = address(user1); releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(keccak256("new nonce")), false, false, token, 8 ether, // the balance of account 2 feeRecipient, fee, // 1 ether fee expiry)) )); Account.sign(2, releaseHash); } bytes32[] signatures2; function check_a6_attemptMoveTransfer_useAccount3(uint8 v, bytes32 r, bytes32 s) public { // MOVE destination bytes32 destinationTemp = bytes32(uint256(0x0200000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(keccak256("new nonce"))) >> 8)); address sendr = address(user1); assembly { destinationTemp := add(destinationTemp, sendr) } bytes32 senderSigVBytes; assembly { senderSigVBytes := add(0, v) } signatures2.push(senderSigVBytes); signatures2.push(r); signatures2.push(s); Assert.equal(address(user1).balance, 0 ether); Assert.equal(address(user2).balance, 0 ether); Assert.equal(instance.tokenBalances(address(account2), address(0)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 1 ether); instance.transfer( destinationTemp, // 0x00 or 01 or 02 ... 0000 ... address token, 8 ether, feeRecipient, fee, // 1 ether fee expiry, signatures2); Assert.equal(instance.tokenBalances(address(account2), address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user1), address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 1 ether); Assert.equal(address(user1).balance, 8 ether); Assert.equal(address(user2).balance, 1 ether); } } contract TestMetaTransactionPool_Shift_Ether { User user1 = new User(); User user2 = new User(); MetaTransactionPoolSpecial instance = new MetaTransactionPoolSpecial(); address recipient; address token = address(0); uint256 amount = 9 ether; address payable feeRecipient = address(user2); uint256 fee = 1 ether; bytes32 nonce = keccak256("hello world"); uint256 expiry = block.timestamp + 7 days; bytes32 releaseHash; function check_a0_secondAccount_useAccount2() public { recipient = msg.sender; releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(nonce), true, true, token, amount, feeRecipient, fee, expiry)) )); } address sndr; function check_a1_checkSetup_useAccount1_useValue10000000000000000000() public payable { sndr = msg.sender; instance.specialDeposit.value(10 ether)(msg.sender); Account.sign(1, releaseHash); } uint8 senderSigV; bytes32 senderSigR; bytes32 senderSigS; function check_a2_useSignature_useAccount1(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(releaseHash, v, r, s)); senderSigV = v; senderSigR = r; senderSigS = s; } bytes32 destination; function check_a3_buildSecondSignature_useAccount2() public { // Move and Transfer bytes32 destinationTemp = bytes32(uint256(0x0000000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(nonce)) >> 8)); bytes32 result; address sendr = msg.sender; // CLAIM destination assembly { result := add(destinationTemp, sendr) } destination = result; Account.sign(2, destination); } bytes32[] signatures; address account2; function check_a4_nickpayClaim_useAccount2(uint8 v, bytes32 r, bytes32 s) public { Assert.equal(msg.sender, ecrecover(destination, v, r, s)); account2 = msg.sender; uint8 _senderSigV = senderSigV; bytes32 senderSigVBytes; bytes32 recipientSigVBytes; assembly { senderSigVBytes := add(0, _senderSigV) recipientSigVBytes := add(0, v) } signatures.push(senderSigVBytes); signatures.push(senderSigR); signatures.push(senderSigS); signatures.push(recipientSigVBytes); signatures.push(r); signatures.push(s); Assert.equal(instance.tokenBalances(msg.sender, address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 0 ether); instance.transfer( destination, // 0x00 or 01 or 02 ... 0000 ... address token, amount, feeRecipient, fee, expiry, signatures); Assert.equal(instance.tokenBalances(msg.sender, address(0)), 9 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 1 ether); } // account 2 sends to account 3 function check_a5_buildNewTransfer_useAccount3() public { recipient = address(user1); releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(keccak256("new nonce")), false, false, token, 8 ether, // the balance of account 2 feeRecipient, fee, // 1 ether fee expiry)) )); Account.sign(2, releaseHash); } bytes32[] signatures2; function check_a6_attemptMoveTransfer_useAccount3(uint8 v, bytes32 r, bytes32 s) public { // MOVE destination bytes32 destinationTemp = bytes32(uint256(0x0300000000000000000000000000000000000000000000000000000000000000) + uint256(bytes32(bytes11(keccak256("new nonce"))) >> 8)); address sendr = address(user1); assembly { destinationTemp := add(destinationTemp, sendr) } bytes32 senderSigVBytes; assembly { senderSigVBytes := add(0, v) } signatures2.push(senderSigVBytes); signatures2.push(r); signatures2.push(s); Assert.equal(instance.tokenBalances(account2, address(0)), 9 ether); Assert.equal(instance.tokenBalances(address(user1), address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 1 ether); instance.transfer( destinationTemp, // 0x00 or 01 or 02 ... 0000 ... address token, 8 ether, feeRecipient, fee, // 1 ether fee expiry, signatures2); Assert.equal(instance.tokenBalances(account2, address(0)), 0 ether); Assert.equal(instance.tokenBalances(address(user1), address(0)), 8 ether); Assert.equal(instance.tokenBalances(address(user2), address(0)), 2 ether); } }
account 2 sends to account 3
function check_a5_buildNewTransfer_useAccount3() public { recipient = address(user1); releaseHash = keccak256(abi.encodePacked( "\x19\x01", instance.DOMAIN_SEPARATOR(), keccak256(abi.encode( instance.SIGNEDTRANSFER_TYPEHASH(), recipient, bytes11(keccak256("new nonce")), false, false, token, feeRecipient, expiry)) )); Account.sign(2, releaseHash); } bytes32[] signatures2;
1,827,948
./full_match/1/0xe63C777dCaab7Db2F6667fCA5f323D47fEE565B2/sources/MyContract.sol
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); }
8,463,227
pragma solidity ^0.4.13; interface FundInterface { // EVENTS event PortfolioContent(address[] assets, uint[] holdings, uint[] prices); event RequestUpdated(uint id); event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed); event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply); event ErrorMessage(string errorMessage); // EXTERNAL METHODS // Compliance by Investor function requestInvestment(uint giveQuantity, uint shareQuantity, address investmentAsset) external; function executeRequest(uint requestId) external; function cancelRequest(uint requestId) external; function redeemAllOwnedAssets(uint shareQuantity) external returns (bool); // Administration by Manager function enableInvestment(address[] ofAssets) external; function disableInvestment(address[] ofAssets) external; function shutDown() external; // PUBLIC METHODS function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success); function calcSharePriceAndAllocateFees() public returns (uint); // PUBLIC VIEW METHODS // Get general information function getModules() view returns (address, address, address); function getLastRequestId() view returns (uint); function getManager() view returns (address); // Get accounting information function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint); function calcSharePrice() view returns (uint); } interface AssetInterface { /* * Implements ERC 20 standard. * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md * https://github.com/ethereum/EIPs/issues/20 * * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload. * https://github.com/ethereum/EIPs/issues/223 */ // Events event Approval(address indexed _owner, address indexed _spender, uint _value); // There is no ERC223 compatible Transfer event, with `_data` included. //ERC 223 // PUBLIC METHODS function transfer(address _to, uint _value, bytes _data) public returns (bool success); // ERC 20 // PUBLIC METHODS function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); // PUBLIC VIEW METHODS function balanceOf(address _owner) view public returns (uint balance); function allowance(address _owner, address _spender) public view returns (uint remaining); } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface SharesInterface { event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity); // VIEW METHODS function getName() view returns (bytes32); function getSymbol() view returns (bytes8); function getDecimals() view returns (uint); function getCreationTime() view returns (uint); function toSmallestShareUnit(uint quantity) view returns (uint); function toWholeShareUnit(uint quantity) view returns (uint); } interface CompetitionInterface { // EVENTS event Register(uint withId, address fund, address manager); event ClaimReward(address registrant, address fund, uint shares); // PRE, POST, INVARIANT CONDITIONS function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool); function isWhitelisted(address x) view returns (bool); function isCompetitionActive() view returns (bool); // CONSTANT METHODS function getMelonAsset() view returns (address); function getRegistrantId(address x) view returns (uint); function getRegistrantFund(address x) view returns (address); function getCompetitionStatusOfRegistrants() view returns (address[], address[], bool[]); function getTimeTillEnd() view returns (uint); function getEtherValue(uint amount) view returns (uint); function calculatePayout(uint payin) view returns (uint); // PUBLIC METHODS function registerForCompetition(address fund, uint8 v, bytes32 r, bytes32 s) payable; function batchAddToWhitelist(uint maxBuyinQuantity, address[] whitelistants); function withdrawMln(address to, uint amount); function claimReward(); } interface ComplianceInterface { // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool); /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool); } contract DBC { // MODIFIERS modifier pre_cond(bool condition) { require(condition); _; } modifier post_cond(bool condition) { _; assert(condition); } modifier invariant(bool condition) { require(condition); _; assert(condition); } } contract Owned is DBC { // FIELDS address public owner; // NON-CONSTANT METHODS function Owned() { owner = msg.sender; } function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; } // PRE, POST, INVARIANT CONDITIONS function isOwner() internal returns (bool) { return msg.sender == owner; } } contract CompetitionCompliance is ComplianceInterface, DBC, Owned { address public competitionAddress; // CONSTRUCTOR /// @dev Constructor /// @param ofCompetition Address of the competition contract function CompetitionCompliance(address ofCompetition) public { competitionAddress = ofCompetition; } // PUBLIC VIEW METHODS /// @notice Checks whether investment is permitted for a participant /// @param ofParticipant Address requesting to invest in a Melon fund /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @return Whether identity is eligible to invest in a Melon fund. function isInvestmentPermitted( address ofParticipant, uint256 giveQuantity, uint256 shareQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether redemption is permitted for a participant /// @param ofParticipant Address requesting to redeem from a Melon fund /// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem /// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity /// @return isEligible Whether identity is eligible to redeem from a Melon fund. function isRedemptionPermitted( address ofParticipant, uint256 shareQuantity, uint256 receiveQuantity ) view returns (bool) { return competitionAddress == ofParticipant; } /// @notice Checks whether an address is whitelisted in the competition contract and competition is active /// @param x Address /// @return Whether the address is whitelisted function isCompetitionAllowed( address x ) view returns (bool) { return CompetitionInterface(competitionAddress).isWhitelisted(x) && CompetitionInterface(competitionAddress).isCompetitionActive(); } // PUBLIC METHODS /// @notice Changes the competition address /// @param ofCompetition Address of the competition contract function changeCompetitionAddress( address ofCompetition ) pre_cond(isOwner()) { competitionAddress = ofCompetition; } } contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSExec { function tryExec( address target, bytes calldata, uint value) internal returns (bool call_ret) { return target.call.value(value)(calldata); } function exec( address target, bytes calldata, uint value) internal { if(!tryExec(target, calldata, value)) { revert(); } } // Convenience aliases function exec( address t, bytes c ) internal { exec(t, c, 0); } function exec( address t, uint256 v ) internal { bytes memory c; exec(t, c, v); } function tryExec( address t, bytes c ) internal returns (bool) { return tryExec(t, c, 0); } function tryExec( address t, uint256 v ) internal returns (bool) { bytes memory c; return tryExec(t, c, v); } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract Asset is DSMath, ERC20Interface { // DATA STRUCTURES mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; uint public _totalSupply; // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed. /// @notice Restriction: An account can only use this function to send to itself /// @dev Allows for an approved third party to transfer tokens from one /// address to another. Returns success. /// @param _from Address from where tokens are withdrawn. /// @param _to Address to where tokens are sent. /// @param _value Number of tokens to transfer. /// @return Returns success of function call. function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_from != address(0)); require(_to != address(0)); require(_to != address(this)); require(balances[_from] >= _value); require(allowed[_from][msg.sender] >= _value); require(balances[_to] + _value >= balances[_to]); // require(_to == msg.sender); // can only use transferFrom to send to self balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address. /// @dev Sets approved amount of tokens for spender. Returns success. /// @param _spender Address of allowed account. /// @param _value Number of approved tokens. /// @return Returns success of function call. function approve(address _spender, uint _value) public returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // PUBLIC VIEW METHODS /// @dev Returns number of allowed tokens that a spender can transfer on /// behalf of a token owner. /// @param _owner Address of token owner. /// @param _spender Address of token spender. /// @return Returns remaining allowance for spender. function allowance(address _owner, address _spender) constant public returns (uint) { return allowed[_owner][_spender]; } /// @dev Returns number of tokens owned by the given address. /// @param _owner Address of token owner. /// @return Returns balance of owner. function balanceOf(address _owner) constant public returns (uint) { return balances[_owner]; } function totalSupply() view public returns (uint) { return _totalSupply; } } contract Shares is SharesInterface, Asset { // FIELDS // Constructor fields bytes32 public name; bytes8 public symbol; uint public decimal; uint public creationTime; // METHODS // CONSTRUCTOR /// @param _name Name these shares /// @param _symbol Symbol of shares /// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract /// @param _creationTime Timestamp of share creation function Shares(bytes32 _name, bytes8 _symbol, uint _decimal, uint _creationTime) { name = _name; symbol = _symbol; decimal = _decimal; creationTime = _creationTime; } // PUBLIC METHODS /** * @notice Send `_value` tokens to `_to` from `msg.sender` * @dev Transfers sender's tokens to a given address * @dev Similar to transfer(address, uint, bytes), but without _data parameter * @param _to Address of token receiver * @param _value Number of tokens to transfer * @return Returns success of function call */ function transfer(address _to, uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); // sanity checks require(balances[_to] + _value >= balances[_to]); balances[msg.sender] = sub(balances[msg.sender], _value); balances[_to] = add(balances[_to], _value); emit Transfer(msg.sender, _to, _value); return true; } // PUBLIC VIEW METHODS function getName() view returns (bytes32) { return name; } function getSymbol() view returns (bytes8) { return symbol; } function getDecimals() view returns (uint) { return decimal; } function getCreationTime() view returns (uint) { return creationTime; } function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); } function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); } // INTERNAL METHODS /// @param recipient Address the new shares should be sent to /// @param shareQuantity Number of shares to be created function createShares(address recipient, uint shareQuantity) internal { _totalSupply = add(_totalSupply, shareQuantity); balances[recipient] = add(balances[recipient], shareQuantity); emit Created(msg.sender, now, shareQuantity); emit Transfer(address(0), recipient, shareQuantity); } /// @param recipient Address the new shares should be taken from when destroyed /// @param shareQuantity Number of shares to be annihilated function annihilateShares(address recipient, uint shareQuantity) internal { _totalSupply = sub(_totalSupply, shareQuantity); balances[recipient] = sub(balances[recipient], shareQuantity); emit Annihilated(msg.sender, now, shareQuantity); emit Transfer(recipient, address(0), shareQuantity); } } contract Fund is DSMath, DBC, Owned, Shares, FundInterface { event OrderUpdated(address exchange, bytes32 orderId, UpdateType updateType); // TYPES struct Modules { // Describes all modular parts, standardised through an interface CanonicalPriceFeed pricefeed; // Provides all external data ComplianceInterface compliance; // Boolean functions regarding invest/redeem RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders } struct Calculations { // List of internal calculations uint gav; // Gross asset value uint managementFee; // Time based fee uint performanceFee; // Performance based fee measured against QUOTE_ASSET uint unclaimedFees; // Fees not yet allocated to the fund manager uint nav; // Net asset value uint highWaterMark; // A record of best all-time fund performance uint totalSupply; // Total supply of shares uint timestamp; // Time when calculations are performed in seconds } enum UpdateType { make, take, cancel } enum RequestStatus { active, cancelled, executed } struct Request { // Describes and logs whenever asset enter and leave fund due to Participants address participant; // Participant in Melon fund requesting investment or redemption RequestStatus status; // Enum: active, cancelled, executed; Status of request address requestAsset; // Address of the asset being requested uint shareQuantity; // Quantity of Melon fund shares uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity uint timestamp; // Time of request creation in seconds uint atUpdateId; // Pricefeed updateId when this request was created } struct Exchange { address exchange; address exchangeAdapter; bool takesCustody; // exchange takes custody before making order } struct OpenMakeOrder { uint id; // Order Id from exchange uint expiresAt; // Timestamp when the order expires } struct Order { // Describes an order event (make or take order) address exchangeAddress; // address of the exchange this order is on bytes32 orderId; // Id as returned from exchange UpdateType updateType; // Enum: make, take (cancel should be ignored) address makerAsset; // Order maker's asset address takerAsset; // Order taker's asset uint makerQuantity; // Quantity of makerAsset to be traded uint takerQuantity; // Quantity of takerAsset to be traded uint timestamp; // Time of order creation in seconds uint fillTakerQuantity; // Quantity of takerAsset to be filled } // FIELDS // Constant fields uint public constant MAX_FUND_ASSETS = 20; // Max ownable assets by the fund supported by gas limits uint public constant ORDER_EXPIRATION_TIME = 86400; // Make order expiration time (1 day) // Constructor fields uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD address public VERSION; // Address of Version contract Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract // Methods fields Modules public modules; // Struct which holds all the initialised module instances Exchange[] public exchanges; // Array containing exchanges this fund supports Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call Order[] public orders; // append-only list of makes/takes from this fund mapping (address => mapping(address => OpenMakeOrder)) public exchangesToOpenMakeOrders; // exchangeIndex to: asset to open make orders bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked Request[] public requests; // All the requests this fund received from participants mapping (address => bool) public isInvestAllowed; // If false, fund rejects investments from the key asset address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset // METHODS // CONSTRUCTOR /// @dev Should only be called via Version.setupFund(..) /// @param withName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest using this single asset /// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD /// @param ofCompliance Address of compliance module /// @param ofRiskMgmt Address of risk management module /// @param ofPriceFeed Address of price feed module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Addresses of assets to enable invest for (quote asset is already enabled) /// @return Deployed Fund with manager set as ofManager function Fund( address ofManager, bytes32 withName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address ofPriceFeed, address[] ofExchanges, address[] ofDefaultAssets ) Shares(withName, "MLNF", 18, now) { require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent isInvestAllowed[ofQuoteAsset] = true; owner = ofManager; MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18 PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18 VERSION = msg.sender; modules.compliance = ComplianceInterface(ofCompliance); modules.riskmgmt = RiskMgmtInterface(ofRiskMgmt); modules.pricefeed = CanonicalPriceFeed(ofPriceFeed); // Bridged to Melon exchange interface by exchangeAdapter library for (uint i = 0; i < ofExchanges.length; ++i) { require(modules.pricefeed.exchangeIsRegistered(ofExchanges[i])); var (ofExchangeAdapter, takesCustody, ) = modules.pricefeed.getExchangeInformation(ofExchanges[i]); exchanges.push(Exchange({ exchange: ofExchanges[i], exchangeAdapter: ofExchangeAdapter, takesCustody: takesCustody })); } QUOTE_ASSET = Asset(ofQuoteAsset); // Quote Asset always in owned assets list ownedAssets.push(ofQuoteAsset); isInAssetList[ofQuoteAsset] = true; require(address(QUOTE_ASSET) == modules.pricefeed.getQuoteAsset()); // Sanity check for (uint j = 0; j < ofDefaultAssets.length; j++) { require(modules.pricefeed.assetIsRegistered(ofDefaultAssets[j])); isInvestAllowed[ofDefaultAssets[j]] = true; } atLastUnclaimedFeeAllocation = Calculations({ gav: 0, managementFee: 0, performanceFee: 0, unclaimedFees: 0, nav: 0, highWaterMark: 10 ** getDecimals(), totalSupply: _totalSupply, timestamp: now }); } // EXTERNAL METHODS // EXTERNAL : ADMINISTRATION /// @notice Enable investment in specified assets /// @param ofAssets Array of assets to enable investment in function enableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { require(modules.pricefeed.assetIsRegistered(ofAssets[i])); isInvestAllowed[ofAssets[i]] = true; } } /// @notice Disable investment in specified assets /// @param ofAssets Array of assets to disable investment in function disableInvestment(address[] ofAssets) external pre_cond(isOwner()) { for (uint i = 0; i < ofAssets.length; ++i) { isInvestAllowed[ofAssets[i]] = false; } } function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; } // EXTERNAL : PARTICIPATION /// @notice Give melon tokens to receive shares of this fund /// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices /// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity /// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received /// @param investmentAsset Address of asset to invest in function requestInvestment( uint giveQuantity, uint shareQuantity, address investmentAsset ) external pre_cond(!isShutDown) pre_cond(isInvestAllowed[investmentAsset]) // investment using investmentAsset has not been deactivated by the Manager pre_cond(modules.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted { requests.push(Request({ participant: msg.sender, status: RequestStatus.active, requestAsset: investmentAsset, shareQuantity: shareQuantity, giveQuantity: giveQuantity, receiveQuantity: shareQuantity, timestamp: now, atUpdateId: modules.pricefeed.getLastUpdateId() })); emit RequestUpdated(getLastRequestId()); } /// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor /// @dev Distributes melon and shares according to the request /// @param id Index of request to be executed /// @dev Active investment or redemption request executed function executeRequest(uint id) external pre_cond(!isShutDown) pre_cond(requests[id].status == RequestStatus.active) pre_cond( _totalSupply == 0 || ( now >= add(requests[id].timestamp, modules.pricefeed.getInterval()) && modules.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2) ) ) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment) { Request request = requests[id]; var (isRecent, , ) = modules.pricefeed.getPriceInfo(address(request.requestAsset)); require(isRecent); // sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals if (request.requestAsset != address(QUOTE_ASSET)) { var (isPriceRecent, invertedRequestAssetPrice, requestAssetDecimal) = modules.pricefeed.getInvertedPriceInfo(request.requestAsset); if (!isPriceRecent) { revert(); } costQuantity = mul(costQuantity, invertedRequestAssetPrice) / 10 ** requestAssetDecimal; } if ( isInvestAllowed[request.requestAsset] && costQuantity <= request.giveQuantity ) { request.status = RequestStatus.executed; require(AssetInterface(request.requestAsset).transferFrom(request.participant, address(this), costQuantity)); // Allocate Value createShares(request.participant, request.shareQuantity); // Accounting if (!isInAssetList[request.requestAsset]) { ownedAssets.push(request.requestAsset); isInAssetList[request.requestAsset] = true; } } else { revert(); // Invalid Request or invalid giveQuantity / receiveQuantity } } /// @notice Cancels active investment and redemption requests /// @param id Index of request to be executed function cancelRequest(uint id) external pre_cond(requests[id].status == RequestStatus.active) // Request is active pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down { requests[id].status = RequestStatus.cancelled; } /// @notice Redeems by allocating an ownership percentage of each asset to the participant /// @dev Independent of running price feed! /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets /// @return Whether all assets sent to shareholder or not function redeemAllOwnedAssets(uint shareQuantity) external returns (bool success) { return emergencyRedeem(shareQuantity, ownedAssets); } // EXTERNAL : MANAGING /// @notice Universal method for calling exchange functions through adapters /// @notice See adapter contracts for parameters needed for each exchange /// @param exchangeIndex Index of the exchange in the "exchanges" array /// @param method Signature of the adapter method to call (as per ABI spec) /// @param orderAddresses [0] Order maker /// @param orderAddresses [1] Order taker /// @param orderAddresses [2] Order maker asset /// @param orderAddresses [3] Order taker asset /// @param orderAddresses [4] Fee recipient /// @param orderValues [0] Maker token quantity /// @param orderValues [1] Taker token quantity /// @param orderValues [2] Maker fee /// @param orderValues [3] Taker fee /// @param orderValues [4] Timestamp (seconds) /// @param orderValues [5] Salt/nonce /// @param orderValues [6] Fill amount: amount of taker token to be traded /// @param orderValues [7] Dexy signature mode /// @param identifier Order identifier /// @param v ECDSA recovery id /// @param r ECDSA signature output r /// @param s ECDSA signature output s function callOnExchange( uint exchangeIndex, bytes4 method, address[5] orderAddresses, uint[8] orderValues, bytes32 identifier, uint8 v, bytes32 r, bytes32 s ) external { require( modules.pricefeed.exchangeMethodIsAllowed( exchanges[exchangeIndex].exchange, method ) ); require( exchanges[exchangeIndex].exchangeAdapter.delegatecall( method, exchanges[exchangeIndex].exchange, orderAddresses, orderValues, identifier, v, r, s ) ); } function addOpenMakeOrder( address ofExchange, address ofSellAsset, uint orderId ) pre_cond(msg.sender == address(this)) { isInOpenMakeOrder[ofSellAsset] = true; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].id = orderId; exchangesToOpenMakeOrders[ofExchange][ofSellAsset].expiresAt = add(now, ORDER_EXPIRATION_TIME); } function removeOpenMakeOrder( address ofExchange, address ofSellAsset ) pre_cond(msg.sender == address(this)) { delete exchangesToOpenMakeOrders[ofExchange][ofSellAsset]; } function orderUpdateHook( address ofExchange, bytes32 orderId, UpdateType updateType, address[2] orderAddresses, // makerAsset, takerAsset uint[3] orderValues // makerQuantity, takerQuantity, fillTakerQuantity (take only) ) pre_cond(msg.sender == address(this)) { // only save make/take if (updateType == UpdateType.make || updateType == UpdateType.take) { orders.push(Order({ exchangeAddress: ofExchange, orderId: orderId, updateType: updateType, makerAsset: orderAddresses[0], takerAsset: orderAddresses[1], makerQuantity: orderValues[0], takerQuantity: orderValues[1], timestamp: block.timestamp, fillTakerQuantity: orderValues[2] })); } emit OrderUpdated(ofExchange, orderId, updateType); } // PUBLIC METHODS // PUBLIC METHODS : ACCOUNTING /// @notice Calculates gross asset value of the fund /// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar /// @dev Assumes that module.pricefeed.getPriceInfo(..) returns recent prices /// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcGav() returns (uint gav) { // prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal uint[] memory allAssetHoldings = new uint[](ownedAssets.length); uint[] memory allAssetPrices = new uint[](ownedAssets.length); address[] memory tempOwnedAssets; tempOwnedAssets = ownedAssets; delete ownedAssets; for (uint i = 0; i < tempOwnedAssets.length; ++i) { address ofAsset = tempOwnedAssets[i]; // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal) uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), // asset base units held by fund quantityHeldInCustodyOfExchange(ofAsset) ); // assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal) var (isRecent, assetPrice, assetDecimals) = modules.pricefeed.getPriceInfo(ofAsset); if (!isRecent) { revert(); } allAssetHoldings[i] = assetHoldings; allAssetPrices[i] = assetPrice; // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals) gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order ownedAssets.push(ofAsset); } else { isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero } } emit PortfolioContent(tempOwnedAssets, allAssetHoldings, allAssetPrices); } /// @notice Add an asset to the list that this fund owns function addAssetToOwnedAssets (address ofAsset) public pre_cond(isOwner() || msg.sender == address(this)) { isInOpenMakeOrder[ofAsset] = true; if (!isInAssetList[ofAsset]) { ownedAssets.push(ofAsset); isInAssetList[ofAsset] = true; } } /** @notice Calculates unclaimed fees of the fund manager @param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals @return { "managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals", "unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals" } */ function calcUnclaimedFees(uint gav) view returns ( uint managementFee, uint performanceFee, uint unclaimedFees) { // Management fee calculation uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp); uint gavPercentage = mul(timePassed, gav) / (1 years); managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE); // Performance fee calculation // Handle potential division through zero by defining a default value uint valuePerShareExclMgmtFees = _totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), _totalSupply) : toSmallestShareUnit(1); if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) { uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark); uint investmentProfits = wmul(gainInSharePrice, _totalSupply); performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE); } // Sum of all FEES unclaimedFees = add(managementFee, performanceFee); } /// @notice Calculates the Net asset value of this fund /// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcNav(uint gav, uint unclaimedFees) view returns (uint nav) { nav = sub(gav, unclaimedFees); } /// @notice Calculates the share price of the fund /// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers /// @dev Non-zero share supply; value denominated in [base unit of melonAsset] /// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals /// @param numShares the number of shares multiplied by 10 ** shareDecimals /// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals function calcValuePerShare(uint totalValue, uint numShares) view pre_cond(numShares > 0) returns (uint valuePerShare) { valuePerShare = toSmallestShareUnit(totalValue) / numShares; } /** @notice Calculates essential fund metrics @return { "gav": "Gross asset value of this fund denominated in [base unit of melonAsset]", "managementFee": "A time (seconds) based fee", "performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee", "unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]", "feesShareQuantity": "The number of shares to be given as fees to the manager", "nav": "Net asset value denominated in [base unit of melonAsset]", "sharePrice": "Share price denominated in [base unit of melonAsset]" } */ function performCalculations() view returns ( uint gav, uint managementFee, uint performanceFee, uint unclaimedFees, uint feesShareQuantity, uint nav, uint sharePrice ) { gav = calcGav(); // Reflects value independent of fees (managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav); nav = calcNav(gav, unclaimedFees); // The value of unclaimedFees measured in shares of this fund at current value feesShareQuantity = (gav == 0) ? 0 : mul(_totalSupply, unclaimedFees) / gav; // The total share supply including the value of unclaimedFees, measured in shares of this fund uint totalSupplyAccountingForFees = add(_totalSupply, feesShareQuantity); sharePrice = _totalSupply > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value } /// @notice Converts unclaimed fees of the manager into fund shares /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePriceAndAllocateFees() public returns (uint) { var ( gav, managementFee, performanceFee, unclaimedFees, feesShareQuantity, nav, sharePrice ) = performCalculations(); createShares(owner, feesShareQuantity); // Updates _totalSupply by creating shares allocated to manager // Update Calculations uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice; atLastUnclaimedFeeAllocation = Calculations({ gav: gav, managementFee: managementFee, performanceFee: performanceFee, unclaimedFees: unclaimedFees, nav: nav, highWaterMark: highWaterMark, totalSupply: _totalSupply, timestamp: now }); emit FeesConverted(now, feesShareQuantity, unclaimedFees); emit CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, _totalSupply); return sharePrice; } // PUBLIC : REDEEMING /// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant /// @dev This works, but with loops, so only up to a certain number of assets (right now the max is 4) /// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value /// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for a slice of assets /// @param requestedAssets List of addresses that consitute a subset of ownedAssets. /// @return Whether all assets sent to shareholder or not function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares returns (bool) { address ofAsset; uint[] memory ownershipQuantities = new uint[](requestedAssets.length); address[] memory redeemedAssets = new address[](requestedAssets.length); // Check whether enough assets held by fund for (uint i = 0; i < requestedAssets.length; ++i) { ofAsset = requestedAssets[i]; require(isInAssetList[ofAsset]); for (uint j = 0; j < redeemedAssets.length; j++) { if (ofAsset == redeemedAssets[j]) { revert(); } } redeemedAssets[i] = ofAsset; uint assetHoldings = add( uint(AssetInterface(ofAsset).balanceOf(address(this))), quantityHeldInCustodyOfExchange(ofAsset) ); if (assetHoldings == 0) continue; // participant's ownership percentage of asset holdings ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / _totalSupply; // CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address if (uint(AssetInterface(ofAsset).balanceOf(address(this))) < ownershipQuantities[i]) { isShutDown = true; emit ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy"); return false; } } // Annihilate shares before external calls to prevent reentrancy annihilateShares(msg.sender, shareQuantity); // Transfer ownershipQuantity of Assets for (uint k = 0; k < requestedAssets.length; ++k) { // Failed to send owed ownershipQuantity from fund to participant ofAsset = requestedAssets[k]; if (ownershipQuantities[k] == 0) { continue; } else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[k])) { revert(); } } emit Redeemed(msg.sender, now, shareQuantity); return true; } // PUBLIC : FEES /// @dev Quantity of asset held in exchange according to associated order id /// @param ofAsset Address of asset /// @return Quantity of input asset held in exchange function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) { uint totalSellQuantity; // quantity in custody across exchanges uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange for (uint i; i < exchanges.length; i++) { if (exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id == 0) { continue; } var (sellAsset, , sellQuantity, ) = GenericExchangeInterface(exchanges[i].exchangeAdapter).getOrder(exchanges[i].exchange, exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id); if (sellQuantity == 0) { // remove id if remaining sell quantity zero (closed) delete exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset]; } totalSellQuantity = add(totalSellQuantity, sellQuantity); if (!exchanges[i].takesCustody) { totalSellQuantityInApprove += sellQuantity; } } if (totalSellQuantity == 0) { isInOpenMakeOrder[sellAsset] = false; } return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody } // PUBLIC VIEW METHODS /// @notice Calculates sharePrice denominated in [base unit of melonAsset] /// @return sharePrice Share price denominated in [base unit of melonAsset] function calcSharePrice() view returns (uint sharePrice) { (, , , , , sharePrice) = performCalculations(); return sharePrice; } function getModules() view returns (address, address, address) { return ( address(modules.pricefeed), address(modules.compliance), address(modules.riskmgmt) ); } function getLastRequestId() view returns (uint) { return requests.length - 1; } function getLastOrderIndex() view returns (uint) { return orders.length - 1; } function getManager() view returns (address) { return owner; } function getOwnedAssetsLength() view returns (uint) { return ownedAssets.length; } function getExchangeInfo() view returns (address[], address[], bool[]) { address[] memory ofExchanges = new address[](exchanges.length); address[] memory ofAdapters = new address[](exchanges.length); bool[] memory takesCustody = new bool[](exchanges.length); for (uint i = 0; i < exchanges.length; i++) { ofExchanges[i] = exchanges[i].exchange; ofAdapters[i] = exchanges[i].exchangeAdapter; takesCustody[i] = exchanges[i].takesCustody; } return (ofExchanges, ofAdapters, takesCustody); } function orderExpired(address ofExchange, address ofAsset) view returns (bool) { uint expiryTime = exchangesToOpenMakeOrders[ofExchange][ofAsset].expiresAt; require(expiryTime > 0); return block.timestamp >= expiryTime; } function getOpenOrderInfo(address ofExchange, address ofAsset) view returns (uint, uint) { OpenMakeOrder order = exchangesToOpenMakeOrders[ofExchange][ofAsset]; return (order.id, order.expiresAt); } } contract Competition is CompetitionInterface, DSMath, DBC, Owned { // TYPES struct Registrant { address fund; // Address of the Melon fund address registrant; // Manager and registrant of the fund bool hasSigned; // Whether initial requirements passed and Registrant signed Terms and Conditions; uint buyinQuantity; // Quantity of buyinAsset spent uint payoutQuantity; // Quantity of payoutAsset received as prize bool isRewarded; // Is the Registrant rewarded yet } struct RegistrantId { uint id; // Actual Registrant Id bool exists; // Used to check if the mapping exists } // FIELDS // Constant fields // Competition terms and conditions as displayed on https://ipfs.io/ipfs/QmXuUfPi6xeYfuMwpVAughm7GjGUjkbEojhNR8DJqVBBxc // IPFS hash encoded using http://lenschulwitz.com/base58 bytes public constant TERMS_AND_CONDITIONS = hex"12208E21FD34B8B2409972D30326D840C9D747438A118580D6BA8C0735ED53810491"; uint public MELON_BASE_UNIT = 10 ** 18; // Constructor fields address public custodian; // Address of the custodian which holds the funds sent uint public startTime; // Competition start time in seconds (Temporarily Set) uint public endTime; // Competition end time in seconds uint public payoutRate; // Fixed MLN - Ether conversion rate uint public bonusRate; // Bonus multiplier uint public totalMaxBuyin; // Limit amount of deposit to participate in competition (Valued in Ether) uint public currentTotalBuyin; // Total buyin till now uint public maxRegistrants; // Limit number of participate in competition uint public prizeMoneyAsset; // Equivalent to payoutAsset uint public prizeMoneyQuantity; // Total prize money pool address public MELON_ASSET; // Adresss of Melon asset contract ERC20Interface public MELON_CONTRACT; // Melon as ERC20 contract address public COMPETITION_VERSION; // Version contract address // Methods fields Registrant[] public registrants; // List of all registrants, can be externally accessed mapping (address => address) public registeredFundToRegistrants; // For fund address indexed accessing of registrant addresses mapping(address => RegistrantId) public registrantToRegistrantIds; // For registrant address indexed accessing of registrant ids mapping(address => uint) public whitelistantToMaxBuyin; // For registrant address to respective max buyIn cap (Valued in Ether) //EVENTS event Register(uint withId, address fund, address manager); // METHODS // CONSTRUCTOR function Competition( address ofMelonAsset, address ofCompetitionVersion, address ofCustodian, uint ofStartTime, uint ofEndTime, uint ofPayoutRate, uint ofTotalMaxBuyin, uint ofMaxRegistrants ) { MELON_ASSET = ofMelonAsset; MELON_CONTRACT = ERC20Interface(MELON_ASSET); COMPETITION_VERSION = ofCompetitionVersion; custodian = ofCustodian; startTime = ofStartTime; endTime = ofEndTime; payoutRate = ofPayoutRate; totalMaxBuyin = ofTotalMaxBuyin; maxRegistrants = ofMaxRegistrants; } // PRE, POST, INVARIANT CONDITIONS /// @dev Proofs that terms and conditions have been read and understood /// @param byManager Address of the fund manager, as used in the ipfs-frontend /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n34", TERMS_AND_CONDITIONS), v, r, s ) == byManager; // Has sender signed TERMS_AND_CONDITIONS } /// @dev Whether message sender is KYC verified through CERTIFIER /// @param x Address to be checked for KYC verification function isWhitelisted(address x) view returns (bool) { return whitelistantToMaxBuyin[x] > 0; } /// @dev Whether the competition is on-going function isCompetitionActive() view returns (bool) { return now >= startTime && now < endTime; } // CONSTANT METHODS function getMelonAsset() view returns (address) { return MELON_ASSET; } /// @return Get RegistrantId from registrant address function getRegistrantId(address x) view returns (uint) { return registrantToRegistrantIds[x].id; } /// @return Address of the fund registered by the registrant address function getRegistrantFund(address x) view returns (address) { return registrants[getRegistrantId(x)].fund; } /// @return Get time to end of the competition function getTimeTillEnd() view returns (uint) { if (now > endTime) { return 0; } return sub(endTime, now); } /// @return Get value of MLN amount in Ether function getEtherValue(uint amount) view returns (uint) { address feedAddress = Version(COMPETITION_VERSION).CANONICAL_PRICEFEED(); var (isRecent, price, ) = CanonicalPriceFeed(feedAddress).getPriceInfo(MELON_ASSET); if (!isRecent) { revert(); } return mul(price, amount) / 10 ** 18; } /// @return Calculated payout in MLN with bonus for payin in Ether function calculatePayout(uint payin) view returns (uint payoutQuantity) { payoutQuantity = mul(payin, payoutRate) / 10 ** 18; } /** @notice Returns an array of fund addresses and an associated array of whether competing and whether disqualified @return { "fundAddrs": "Array of addresses of Melon Funds", "fundRegistrants": "Array of addresses of Melon fund managers, as used in the ipfs-frontend", } */ function getCompetitionStatusOfRegistrants() view returns( address[], address[], bool[] ) { address[] memory fundAddrs = new address[](registrants.length); address[] memory fundRegistrants = new address[](registrants.length); bool[] memory isRewarded = new bool[](registrants.length); for (uint i = 0; i < registrants.length; i++) { fundAddrs[i] = registrants[i].fund; fundRegistrants[i] = registrants[i].registrant; isRewarded[i] = registrants[i].isRewarded; } return (fundAddrs, fundRegistrants, isRewarded); } // NON-CONSTANT METHODS /// @notice Register to take part in the competition /// @dev Check if the fund address is actually from the Competition Version /// @param fund Address of the Melon fund /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function registerForCompetition( address fund, uint8 v, bytes32 r, bytes32 s ) payable pre_cond(isCompetitionActive() && !Version(COMPETITION_VERSION).isShutDown()) pre_cond(termsAndConditionsAreSigned(msg.sender, v, r, s) && isWhitelisted(msg.sender)) { require(registeredFundToRegistrants[fund] == address(0) && registrantToRegistrantIds[msg.sender].exists == false); require(add(currentTotalBuyin, msg.value) <= totalMaxBuyin && registrants.length < maxRegistrants); require(msg.value <= whitelistantToMaxBuyin[msg.sender]); require(Version(COMPETITION_VERSION).getFundByManager(msg.sender) == fund); // Calculate Payout Quantity, invest the quantity in registrant's fund uint payoutQuantity = calculatePayout(msg.value); registeredFundToRegistrants[fund] = msg.sender; registrantToRegistrantIds[msg.sender] = RegistrantId({id: registrants.length, exists: true}); currentTotalBuyin = add(currentTotalBuyin, msg.value); FundInterface fundContract = FundInterface(fund); MELON_CONTRACT.approve(fund, payoutQuantity); // Give payoutRequest MLN in return for msg.value fundContract.requestInvestment(payoutQuantity, getEtherValue(payoutQuantity), MELON_ASSET); fundContract.executeRequest(fundContract.getLastRequestId()); custodian.transfer(msg.value); // Emit Register event emit Register(registrants.length, fund, msg.sender); registrants.push(Registrant({ fund: fund, registrant: msg.sender, hasSigned: true, buyinQuantity: msg.value, payoutQuantity: payoutQuantity, isRewarded: false })); } /// @notice Add batch addresses to whitelist with set maxBuyinQuantity /// @dev Only the owner can call this function /// @param maxBuyinQuantity Quantity of payoutAsset received as prize /// @param whitelistants Performance of Melon fund at competition endTime; Can be changed for any other comparison metric function batchAddToWhitelist( uint maxBuyinQuantity, address[] whitelistants ) pre_cond(isOwner()) pre_cond(now < endTime) { for (uint i = 0; i < whitelistants.length; ++i) { whitelistantToMaxBuyin[whitelistants[i]] = maxBuyinQuantity; } } /// @notice Withdraw MLN /// @dev Only the owner can call this function function withdrawMln(address to, uint amount) pre_cond(isOwner()) { MELON_CONTRACT.transfer(to, amount); } /// @notice Claim Reward function claimReward() pre_cond(getRegistrantFund(msg.sender) != address(0)) { require(block.timestamp >= endTime || Version(COMPETITION_VERSION).isShutDown()); Registrant registrant = registrants[getRegistrantId(msg.sender)]; require(registrant.isRewarded == false); registrant.isRewarded = true; // Is this safe to assume this or should we transfer all the balance instead? uint balance = AssetInterface(registrant.fund).balanceOf(address(this)); require(AssetInterface(registrant.fund).transfer(registrant.registrant, balance)); // Emit ClaimedReward event emit ClaimReward(msg.sender, registrant.fund, balance); } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSGroup is DSExec, DSNote { address[] public members; uint public quorum; uint public window; uint public actionCount; mapping (uint => Action) public actions; mapping (uint => mapping (address => bool)) public confirmedBy; mapping (address => bool) public isMember; // Legacy events event Proposed (uint id, bytes calldata); event Confirmed (uint id, address member); event Triggered (uint id); struct Action { address target; bytes calldata; uint value; uint confirmations; uint deadline; bool triggered; } function DSGroup( address[] members_, uint quorum_, uint window_ ) { members = members_; quorum = quorum_; window = window_; for (uint i = 0; i < members.length; i++) { isMember[members[i]] = true; } } function memberCount() constant returns (uint) { return members.length; } function target(uint id) constant returns (address) { return actions[id].target; } function calldata(uint id) constant returns (bytes) { return actions[id].calldata; } function value(uint id) constant returns (uint) { return actions[id].value; } function confirmations(uint id) constant returns (uint) { return actions[id].confirmations; } function deadline(uint id) constant returns (uint) { return actions[id].deadline; } function triggered(uint id) constant returns (bool) { return actions[id].triggered; } function confirmed(uint id) constant returns (bool) { return confirmations(id) >= quorum; } function expired(uint id) constant returns (bool) { return now > deadline(id); } function deposit() note payable { } function propose( address target, bytes calldata, uint value ) onlyMembers note returns (uint id) { id = ++actionCount; actions[id].target = target; actions[id].calldata = calldata; actions[id].value = value; actions[id].deadline = now + window; Proposed(id, calldata); } function confirm(uint id) onlyMembers onlyActive(id) note { assert(!confirmedBy[id][msg.sender]); confirmedBy[id][msg.sender] = true; actions[id].confirmations++; Confirmed(id, msg.sender); } function trigger(uint id) onlyMembers onlyActive(id) note { assert(confirmed(id)); actions[id].triggered = true; exec(actions[id].target, actions[id].calldata, actions[id].value); Triggered(id); } modifier onlyMembers { assert(isMember[msg.sender]); _; } modifier onlyActive(uint id) { assert(!expired(id)); assert(!triggered(id)); _; } //------------------------------------------------------------------ // Legacy functions //------------------------------------------------------------------ function getInfo() constant returns ( uint quorum_, uint memberCount, uint window_, uint actionCount_ ) { return (quorum, members.length, window, actionCount); } function getActionStatus(uint id) constant returns ( uint confirmations, uint deadline, bool triggered, address target, uint value ) { return ( actions[id].confirmations, actions[id].deadline, actions[id].triggered, actions[id].target, actions[id].value ); } } contract DSGroupFactory is DSNote { mapping (address => bool) public isGroup; function newGroup( address[] members, uint quorum, uint window ) note returns (DSGroup group) { group = new DSGroup(members, quorum, window); isGroup[group] = true; } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } interface GenericExchangeInterface { // EVENTS event OrderUpdated(uint id); // METHODS // EXTERNAL METHODS function makeOrder( address onExchange, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) external returns (uint); function takeOrder(address onExchange, uint id, uint quantity) external returns (bool); function cancelOrder(address onExchange, uint id) external returns (bool); // PUBLIC METHODS // PUBLIC VIEW METHODS function isApproveOnly() view returns (bool); function getLastOrderId(address onExchange) view returns (uint); function isActive(address onExchange, uint id) view returns (bool); function getOwner(address onExchange, uint id) view returns (address); function getOrder(address onExchange, uint id) view returns (address, address, uint, uint); function getTimestamp(address onExchange, uint id) view returns (uint); } contract CanonicalRegistrar is DSThing, DBC { // TYPES struct Asset { bool exists; // True if asset is registered here bytes32 name; // Human-readable name of the Asset as in ERC223 token standard bytes8 symbol; // Human-readable symbol of the Asset as in ERC223 token standard uint decimals; // Decimal, order of magnitude of precision, of the Asset as in ERC223 token standard string url; // URL for additional information of Asset string ipfsHash; // Same as url but for ipfs address breakIn; // Break in contract on destination chain address breakOut; // Break out contract on this chain; A way to leave uint[] standards; // compliance with standards like ERC20, ERC223, ERC777, etc. (the uint is the standard number) bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->Asset` as much as possible. I.e. name same concepts with the same functionSignature. uint price; // Price of asset quoted against `QUOTE_ASSET` * 10 ** decimals uint timestamp; // Timestamp of last price update of this asset } struct Exchange { bool exists; address adapter; // adapter contract for this exchange // One-time note: takesCustody is inverse case of isApproveOnly bool takesCustody; // True in case of exchange implementation which requires are approved when an order is made instead of transfer bytes4[] functionSignatures; // Whitelisted function signatures that can be called using `useExternalFunction` in Fund contract. Note: Adhere to a naming convention for `Fund<->ExchangeAdapter` as much as possible. I.e. name same concepts with the same functionSignature. } // TODO: populate each field here // TODO: add whitelistFunction function // FIELDS // Methods fields mapping (address => Asset) public assetInformation; address[] public registeredAssets; mapping (address => Exchange) public exchangeInformation; address[] public registeredExchanges; // METHODS // PUBLIC METHODS /// @notice Registers an Asset information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofAsset is registered /// @param ofAsset Address of asset to be registered /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputDecimals Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs /// @param breakInBreakOut Address of break in and break out contracts on destination chain /// @param inputStandards Integers of EIP standards this asset adheres to /// @param inputFunctionSignatures Function signatures for whitelisted asset functions function registerAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] breakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(!assetInformation[ofAsset].exists) { assetInformation[ofAsset].exists = true; registeredAssets.push(ofAsset); updateAsset( ofAsset, inputName, inputSymbol, inputDecimals, inputUrl, inputIpfsHash, breakInBreakOut, inputStandards, inputFunctionSignatures ); assert(assetInformation[ofAsset].exists); } /// @notice Register an exchange information entry /// @dev Pre: Only registrar owner should be able to register /// @dev Post: Address ofExchange is registered /// @param ofExchange Address of the exchange /// @param ofExchangeAdapter Address of exchange adapter for this exchange /// @param inputTakesCustody Whether this exchange takes custody of tokens before trading /// @param inputFunctionSignatures Function signatures for whitelisted exchange functions function registerExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(!exchangeInformation[ofExchange].exists) { exchangeInformation[ofExchange].exists = true; registeredExchanges.push(ofExchange); updateExchange( ofExchange, ofExchangeAdapter, inputTakesCustody, inputFunctionSignatures ); assert(exchangeInformation[ofExchange].exists); } /// @notice Updates description information of a registered Asset /// @dev Pre: Owner can change an existing entry /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash /// @param ofAsset Address of the asset to be updated /// @param inputName Human-readable name of the Asset as in ERC223 token standard /// @param inputSymbol Human-readable symbol of the Asset as in ERC223 token standard /// @param inputUrl Url for extended information of the asset /// @param inputIpfsHash Same as url but for ipfs function updateAsset( address ofAsset, bytes32 inputName, bytes8 inputSymbol, uint inputDecimals, string inputUrl, string inputIpfsHash, address[2] ofBreakInBreakOut, uint[] inputStandards, bytes4[] inputFunctionSignatures ) auth pre_cond(assetInformation[ofAsset].exists) { Asset asset = assetInformation[ofAsset]; asset.name = inputName; asset.symbol = inputSymbol; asset.decimals = inputDecimals; asset.url = inputUrl; asset.ipfsHash = inputIpfsHash; asset.breakIn = ofBreakInBreakOut[0]; asset.breakOut = ofBreakInBreakOut[1]; asset.standards = inputStandards; asset.functionSignatures = inputFunctionSignatures; } function updateExchange( address ofExchange, address ofExchangeAdapter, bool inputTakesCustody, bytes4[] inputFunctionSignatures ) auth pre_cond(exchangeInformation[ofExchange].exists) { Exchange exchange = exchangeInformation[ofExchange]; exchange.adapter = ofExchangeAdapter; exchange.takesCustody = inputTakesCustody; exchange.functionSignatures = inputFunctionSignatures; } // TODO: check max size of array before remaking this becomes untenable /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofAsset address for which specific information is requested function removeAsset( address ofAsset, uint assetIndex ) auth pre_cond(assetInformation[ofAsset].exists) { require(registeredAssets[assetIndex] == ofAsset); delete assetInformation[ofAsset]; // Sets exists boolean to false delete registeredAssets[assetIndex]; for (uint i = assetIndex; i < registeredAssets.length-1; i++) { registeredAssets[i] = registeredAssets[i+1]; } registeredAssets.length--; assert(!assetInformation[ofAsset].exists); } /// @notice Deletes an existing entry /// @dev Owner can delete an existing entry /// @param ofExchange address for which specific information is requested /// @param exchangeIndex index of the exchange in array function removeExchange( address ofExchange, uint exchangeIndex ) auth pre_cond(exchangeInformation[ofExchange].exists) { require(registeredExchanges[exchangeIndex] == ofExchange); delete exchangeInformation[ofExchange]; delete registeredExchanges[exchangeIndex]; for (uint i = exchangeIndex; i < registeredExchanges.length-1; i++) { registeredExchanges[i] = registeredExchanges[i+1]; } registeredExchanges.length--; assert(!exchangeInformation[ofExchange].exists); } // PUBLIC VIEW METHODS // get asset specific information function getName(address ofAsset) view returns (bytes32) { return assetInformation[ofAsset].name; } function getSymbol(address ofAsset) view returns (bytes8) { return assetInformation[ofAsset].symbol; } function getDecimals(address ofAsset) view returns (uint) { return assetInformation[ofAsset].decimals; } function assetIsRegistered(address ofAsset) view returns (bool) { return assetInformation[ofAsset].exists; } function getRegisteredAssets() view returns (address[]) { return registeredAssets; } function assetMethodIsAllowed( address ofAsset, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = assetInformation[ofAsset].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } // get exchange-specific information function exchangeIsRegistered(address ofExchange) view returns (bool) { return exchangeInformation[ofExchange].exists; } function getRegisteredExchanges() view returns (address[]) { return registeredExchanges; } function getExchangeInformation(address ofExchange) view returns (address, bool) { Exchange exchange = exchangeInformation[ofExchange]; return ( exchange.adapter, exchange.takesCustody ); } function getExchangeFunctionSignatures(address ofExchange) view returns (bytes4[]) { return exchangeInformation[ofExchange].functionSignatures; } function exchangeMethodIsAllowed( address ofExchange, bytes4 querySignature ) returns (bool) { bytes4[] memory signatures = exchangeInformation[ofExchange].functionSignatures; for (uint i = 0; i < signatures.length; i++) { if (signatures[i] == querySignature) { return true; } } return false; } } interface SimplePriceFeedInterface { // EVENTS event PriceUpdated(bytes32 hash); // PUBLIC METHODS function update(address[] ofAssets, uint[] newPrices) external; // PUBLIC VIEW METHODS // Get price feed operation specific information function getQuoteAsset() view returns (address); function getLastUpdateId() view returns (uint); // Get asset specific information as updated in price feed function getPrice(address ofAsset) view returns (uint price, uint timestamp); function getPrices(address[] ofAssets) view returns (uint[] prices, uint[] timestamps); } contract SimplePriceFeed is SimplePriceFeedInterface, DSThing, DBC { // TYPES struct Data { uint price; uint timestamp; } // FIELDS mapping(address => Data) public assetsToPrices; // Constructor fields address public QUOTE_ASSET; // Asset of a portfolio against which all other assets are priced // Contract-level variables uint public updateId; // Update counter for this pricefeed; used as a check during investment CanonicalRegistrar public registrar; CanonicalPriceFeed public superFeed; // METHODS // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function SimplePriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) { registrar = CanonicalRegistrar(ofRegistrar); QUOTE_ASSET = ofQuoteAsset; superFeed = CanonicalPriceFeed(ofSuperFeed); } // EXTERNAL METHODS /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses /// @param newPrices list of prices for each of the assets function update(address[] ofAssets, uint[] newPrices) external auth { _updatePrices(ofAssets, newPrices); } // PUBLIC VIEW METHODS // Get pricefeed specific information function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getLastUpdateId() view returns (uint) { return updateId; } /** @notice Gets price of an asset multiplied by ten to the power of assetDecimals @dev Asset has been registered @param ofAsset Asset for which price should be returned @return { "price": "Price formatting: mul(exchangePrice, 10 ** decimal), to avoid floating numbers", "timestamp": "When the asset's price was updated" } */ function getPrice(address ofAsset) view returns (uint price, uint timestamp) { Data data = assetsToPrices[ofAsset]; return (data.price, data.timestamp); } /** @notice Price of a registered asset in format (bool areRecent, uint[] prices, uint[] decimals) @dev Convention for price formatting: mul(price, 10 ** decimal), to avoid floating numbers @param ofAssets Assets for which prices should be returned @return { "prices": "Array of prices", "timestamps": "Array of timestamps", } */ function getPrices(address[] ofAssets) view returns (uint[], uint[]) { uint[] memory prices = new uint[](ofAssets.length); uint[] memory timestamps = new uint[](ofAssets.length); for (uint i; i < ofAssets.length; i++) { var (price, timestamp) = getPrice(ofAssets[i]); prices[i] = price; timestamps[i] = timestamp; } return (prices, timestamps); } // INTERNAL METHODS /// @dev Internal so that feeds inheriting this one are not obligated to have an exposed update(...) method, but can still perform updates function _updatePrices(address[] ofAssets, uint[] newPrices) internal pre_cond(ofAssets.length == newPrices.length) { updateId++; for (uint i = 0; i < ofAssets.length; ++i) { require(registrar.assetIsRegistered(ofAssets[i])); require(assetsToPrices[ofAssets[i]].timestamp != now); // prevent two updates in one block assetsToPrices[ofAssets[i]].timestamp = now; assetsToPrices[ofAssets[i]].price = newPrices[i]; } emit PriceUpdated(keccak256(ofAssets, newPrices)); } } contract StakingPriceFeed is SimplePriceFeed { OperatorStaking public stakingContract; AssetInterface public stakingToken; // CONSTRUCTOR /// @param ofQuoteAsset Address of quote asset /// @param ofRegistrar Address of canonical registrar /// @param ofSuperFeed Address of superfeed function StakingPriceFeed( address ofRegistrar, address ofQuoteAsset, address ofSuperFeed ) SimplePriceFeed(ofRegistrar, ofQuoteAsset, ofSuperFeed) { stakingContract = OperatorStaking(ofSuperFeed); // canonical feed *is* staking contract stakingToken = AssetInterface(stakingContract.stakingToken()); } // EXTERNAL METHODS /// @param amount Number of tokens to stake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function depositStake(uint amount, bytes data) external auth { require(stakingToken.transferFrom(msg.sender, address(this), amount)); require(stakingToken.approve(stakingContract, amount)); stakingContract.stake(amount, data); } /// @param amount Number of tokens to unstake for this feed /// @param data Data may be needed for some future applications (can be empty for now) function unstake(uint amount, bytes data) external auth { stakingContract.unstake(amount, data); } function withdrawStake() external auth { uint amountToWithdraw = stakingContract.stakeToWithdraw(address(this)); stakingContract.withdrawStake(); require(stakingToken.transfer(msg.sender, amountToWithdraw)); } } interface RiskMgmtInterface { // METHODS // PUBLIC VIEW METHODS /// @notice Checks if the makeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If makeOrder is permitted function isMakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); /// @notice Checks if the takeOrder price is reasonable and not manipulative /// @param orderPrice Price of Order /// @param referencePrice Reference price obtained through PriceFeed contract /// @param sellAsset Asset (as registered in Asset registrar) to be sold /// @param buyAsset Asset (as registered in Asset registrar) to be bought /// @param sellQuantity Quantity of sellAsset to be sold /// @param buyQuantity Quantity of buyAsset to be bought /// @return If takeOrder is permitted function isTakePermitted( uint orderPrice, uint referencePrice, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (bool); } contract OperatorStaking is DBC { // EVENTS event Staked(address indexed user, uint256 amount, uint256 total, bytes data); event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data); event StakeBurned(address indexed user, uint256 amount, bytes data); // TYPES struct StakeData { uint amount; address staker; } // Circular linked list struct Node { StakeData data; uint prev; uint next; } // FIELDS // INTERNAL FIELDS Node[] internal stakeNodes; // Sorted circular linked list nodes containing stake data (Built on top https://programtheblockchain.com/posts/2018/03/30/storage-patterns-doubly-linked-list/) // PUBLIC FIELDS uint public minimumStake; uint public numOperators; uint public withdrawalDelay; mapping (address => bool) public isRanked; mapping (address => uint) public latestUnstakeTime; mapping (address => uint) public stakeToWithdraw; mapping (address => uint) public stakedAmounts; uint public numStakers; // Current number of stakers (Needed because of array holes) AssetInterface public stakingToken; // TODO: consider renaming "operator" depending on how this is implemented // (i.e. is pricefeed staking itself?) function OperatorStaking( AssetInterface _stakingToken, uint _minimumStake, uint _numOperators, uint _withdrawalDelay ) public { require(address(_stakingToken) != address(0)); stakingToken = _stakingToken; minimumStake = _minimumStake; numOperators = _numOperators; withdrawalDelay = _withdrawalDelay; StakeData memory temp = StakeData({ amount: 0, staker: address(0) }); stakeNodes.push(Node(temp, 0, 0)); } // METHODS : STAKING function stake( uint amount, bytes data ) public pre_cond(amount >= minimumStake) { stakedAmounts[msg.sender] += amount; updateStakerRanking(msg.sender); require(stakingToken.transferFrom(msg.sender, address(this), amount)); } function unstake( uint amount, bytes data ) public { uint preStake = stakedAmounts[msg.sender]; uint postStake = preStake - amount; require(postStake >= minimumStake || postStake == 0); require(stakedAmounts[msg.sender] >= amount); latestUnstakeTime[msg.sender] = block.timestamp; stakedAmounts[msg.sender] -= amount; stakeToWithdraw[msg.sender] += amount; updateStakerRanking(msg.sender); emit Unstaked(msg.sender, amount, stakedAmounts[msg.sender], data); } function withdrawStake() public pre_cond(stakeToWithdraw[msg.sender] > 0) pre_cond(block.timestamp >= latestUnstakeTime[msg.sender] + withdrawalDelay) { uint amount = stakeToWithdraw[msg.sender]; stakeToWithdraw[msg.sender] = 0; require(stakingToken.transfer(msg.sender, amount)); } // VIEW FUNCTIONS function isValidNode(uint id) view returns (bool) { // 0 is a sentinel and therefore invalid. // A valid node is the head or has a previous node. return id != 0 && (id == stakeNodes[0].next || stakeNodes[id].prev != 0); } function searchNode(address staker) view returns (uint) { uint current = stakeNodes[0].next; while (isValidNode(current)) { if (staker == stakeNodes[current].data.staker) { return current; } current = stakeNodes[current].next; } return 0; } function isOperator(address user) view returns (bool) { address[] memory operators = getOperators(); for (uint i; i < operators.length; i++) { if (operators[i] == user) { return true; } } return false; } function getOperators() view returns (address[]) { uint arrLength = (numOperators > numStakers) ? numStakers : numOperators; address[] memory operators = new address[](arrLength); uint current = stakeNodes[0].next; for (uint i; i < arrLength; i++) { operators[i] = stakeNodes[current].data.staker; current = stakeNodes[current].next; } return operators; } function getStakersAndAmounts() view returns (address[], uint[]) { address[] memory stakers = new address[](numStakers); uint[] memory amounts = new uint[](numStakers); uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { stakers[i] = stakeNodes[current].data.staker; amounts[i] = stakeNodes[current].data.amount; current = stakeNodes[current].next; } return (stakers, amounts); } function totalStakedFor(address user) view returns (uint) { return stakedAmounts[user]; } // INTERNAL METHODS // DOUBLY-LINKED LIST function insertNodeSorted(uint amount, address staker) internal returns (uint) { uint current = stakeNodes[0].next; if (current == 0) return insertNodeAfter(0, amount, staker); while (isValidNode(current)) { if (amount > stakeNodes[current].data.amount) { break; } current = stakeNodes[current].next; } return insertNodeBefore(current, amount, staker); } function insertNodeAfter(uint id, uint amount, address staker) internal returns (uint newID) { // 0 is allowed here to insert at the beginning. require(id == 0 || isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes.push(Node({ data: StakeData(amount, staker), prev: id, next: node.next })); newID = stakeNodes.length - 1; stakeNodes[node.next].prev = newID; node.next = newID; numStakers++; } function insertNodeBefore(uint id, uint amount, address staker) internal returns (uint) { return insertNodeAfter(stakeNodes[id].prev, amount, staker); } function removeNode(uint id) internal { require(isValidNode(id)); Node storage node = stakeNodes[id]; stakeNodes[node.next].prev = node.prev; stakeNodes[node.prev].next = node.next; delete stakeNodes[id]; numStakers--; } // UPDATING OPERATORS function updateStakerRanking(address _staker) internal { uint newStakedAmount = stakedAmounts[_staker]; if (newStakedAmount == 0) { isRanked[_staker] = false; removeStakerFromArray(_staker); } else if (isRanked[_staker]) { removeStakerFromArray(_staker); insertNodeSorted(newStakedAmount, _staker); } else { isRanked[_staker] = true; insertNodeSorted(newStakedAmount, _staker); } } function removeStakerFromArray(address _staker) internal { uint id = searchNode(_staker); require(id > 0); removeNode(id); } } contract CanonicalPriceFeed is OperatorStaking, SimplePriceFeed, CanonicalRegistrar { // EVENTS event SetupPriceFeed(address ofPriceFeed); struct HistoricalPrices { address[] assets; uint[] prices; uint timestamp; } // FIELDS bool public updatesAreAllowed = true; uint public minimumPriceCount = 1; uint public VALIDITY; uint public INTERVAL; mapping (address => bool) public isStakingFeed; // If the Staking Feed has been created through this contract HistoricalPrices[] public priceHistory; // METHODS // CONSTRUCTOR /// @dev Define and register a quote asset against which all prices are measured/based against /// @param ofStakingAsset Address of staking asset (may or may not be quoteAsset) /// @param ofQuoteAsset Address of quote asset /// @param quoteAssetName Name of quote asset /// @param quoteAssetSymbol Symbol for quote asset /// @param quoteAssetDecimals Decimal places for quote asset /// @param quoteAssetUrl URL related to quote asset /// @param quoteAssetIpfsHash IPFS hash associated with quote asset /// @param quoteAssetBreakInBreakOut Break-in/break-out for quote asset on destination chain /// @param quoteAssetStandards EIP standards quote asset adheres to /// @param quoteAssetFunctionSignatures Whitelisted functions of quote asset contract // /// @param interval Number of seconds between pricefeed updates (this interval is not enforced on-chain, but should be followed by the datafeed maintainer) // /// @param validity Number of seconds that datafeed update information is valid for /// @param ofGovernance Address of contract governing the Canonical PriceFeed function CanonicalPriceFeed( address ofStakingAsset, address ofQuoteAsset, // Inital entry in asset registrar contract is Melon (QUOTE_ASSET) bytes32 quoteAssetName, bytes8 quoteAssetSymbol, uint quoteAssetDecimals, string quoteAssetUrl, string quoteAssetIpfsHash, address[2] quoteAssetBreakInBreakOut, uint[] quoteAssetStandards, bytes4[] quoteAssetFunctionSignatures, uint[2] updateInfo, // interval, validity uint[3] stakingInfo, // minStake, numOperators, unstakeDelay address ofGovernance ) OperatorStaking( AssetInterface(ofStakingAsset), stakingInfo[0], stakingInfo[1], stakingInfo[2] ) SimplePriceFeed(address(this), ofQuoteAsset, address(0)) { registerAsset( ofQuoteAsset, quoteAssetName, quoteAssetSymbol, quoteAssetDecimals, quoteAssetUrl, quoteAssetIpfsHash, quoteAssetBreakInBreakOut, quoteAssetStandards, quoteAssetFunctionSignatures ); INTERVAL = updateInfo[0]; VALIDITY = updateInfo[1]; setOwner(ofGovernance); } // EXTERNAL METHODS /// @notice Create a new StakingPriceFeed function setupStakingPriceFeed() external { address ofStakingPriceFeed = new StakingPriceFeed( address(this), stakingToken, address(this) ); isStakingFeed[ofStakingPriceFeed] = true; StakingPriceFeed(ofStakingPriceFeed).setOwner(msg.sender); emit SetupPriceFeed(ofStakingPriceFeed); } /// @dev override inherited update function to prevent manual update from authority function update(address[] ofAssets, uint[] newPrices) external { revert(); } /// @dev Burn state for a pricefeed operator /// @param user Address of pricefeed operator to burn the stake from function burnStake(address user) external auth { uint totalToBurn = add(stakedAmounts[user], stakeToWithdraw[user]); stakedAmounts[user] = 0; stakeToWithdraw[user] = 0; updateStakerRanking(user); emit StakeBurned(user, totalToBurn, ""); } // PUBLIC METHODS // STAKING function stake( uint amount, bytes data ) public pre_cond(isStakingFeed[msg.sender]) { OperatorStaking.stake(amount, data); } // function stakeFor( // address user, // uint amount, // bytes data // ) // public // pre_cond(isStakingFeed[user]) // { // OperatorStaking.stakeFor(user, amount, data); // } // AGGREGATION /// @dev Only Owner; Same sized input arrays /// @dev Updates price of asset relative to QUOTE_ASSET /** Ex: * Let QUOTE_ASSET == MLN (base units), let asset == EUR-T, * let Value of 1 EUR-T := 1 EUR == 0.080456789 MLN, hence price 0.080456789 MLN / EUR-T * and let EUR-T decimals == 8. * Input would be: information[EUR-T].price = 8045678 [MLN/ (EUR-T * 10**8)] */ /// @param ofAssets list of asset addresses function collectAndUpdate(address[] ofAssets) public auth pre_cond(updatesAreAllowed) { uint[] memory newPrices = pricesToCommit(ofAssets); priceHistory.push( HistoricalPrices({assets: ofAssets, prices: newPrices, timestamp: block.timestamp}) ); _updatePrices(ofAssets, newPrices); } function pricesToCommit(address[] ofAssets) view returns (uint[]) { address[] memory operators = getOperators(); uint[] memory newPrices = new uint[](ofAssets.length); for (uint i = 0; i < ofAssets.length; i++) { uint[] memory assetPrices = new uint[](operators.length); for (uint j = 0; j < operators.length; j++) { SimplePriceFeed feed = SimplePriceFeed(operators[j]); var (price, timestamp) = feed.assetsToPrices(ofAssets[i]); if (now > add(timestamp, VALIDITY)) { continue; // leaves a zero in the array (dealt with later) } assetPrices[j] = price; } newPrices[i] = medianize(assetPrices); } return newPrices; } /// @dev from MakerDao medianizer contract function medianize(uint[] unsorted) view returns (uint) { uint numValidEntries; for (uint i = 0; i < unsorted.length; i++) { if (unsorted[i] != 0) { numValidEntries++; } } if (numValidEntries < minimumPriceCount) { revert(); } uint counter; uint[] memory out = new uint[](numValidEntries); for (uint j = 0; j < unsorted.length; j++) { uint item = unsorted[j]; if (item != 0) { // skip zero (invalid) entries if (counter == 0 || item >= out[counter - 1]) { out[counter] = item; // item is larger than last in array (we are home) } else { uint k = 0; while (item >= out[k]) { k++; // get to where element belongs (between smaller and larger items) } for (uint m = counter; m > k; m--) { out[m] = out[m - 1]; // bump larger elements rightward to leave slot } out[k] = item; } counter++; } } uint value; if (counter % 2 == 0) { uint value1 = uint(out[(counter / 2) - 1]); uint value2 = uint(out[(counter / 2)]); value = add(value1, value2) / 2; } else { value = out[(counter - 1) / 2]; } return value; } function setMinimumPriceCount(uint newCount) auth { minimumPriceCount = newCount; } function enableUpdates() auth { updatesAreAllowed = true; } function disableUpdates() auth { updatesAreAllowed = false; } // PUBLIC VIEW METHODS // FEED INFORMATION function getQuoteAsset() view returns (address) { return QUOTE_ASSET; } function getInterval() view returns (uint) { return INTERVAL; } function getValidity() view returns (uint) { return VALIDITY; } function getLastUpdateId() view returns (uint) { return updateId; } // PRICES /// @notice Whether price of asset has been updated less than VALIDITY seconds ago /// @param ofAsset Asset in registrar /// @return isRecent Price information ofAsset is recent function hasRecentPrice(address ofAsset) view pre_cond(assetIsRegistered(ofAsset)) returns (bool isRecent) { var ( , timestamp) = getPrice(ofAsset); return (sub(now, timestamp) <= VALIDITY); } /// @notice Whether prices of assets have been updated less than VALIDITY seconds ago /// @param ofAssets All assets in registrar /// @return isRecent Price information ofAssets array is recent function hasRecentPrices(address[] ofAssets) view returns (bool areRecent) { for (uint i; i < ofAssets.length; i++) { if (!hasRecentPrice(ofAssets[i])) { return false; } } return true; } function getPriceInfo(address ofAsset) view returns (bool isRecent, uint price, uint assetDecimals) { isRecent = hasRecentPrice(ofAsset); (price, ) = getPrice(ofAsset); assetDecimals = getDecimals(ofAsset); } /** @notice Gets inverted price of an asset @dev Asset has been initialised and its price is non-zero @dev Existing price ofAssets quoted in QUOTE_ASSET (convention) @param ofAsset Asset for which inverted price should be return @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "invertedPrice": "Price based (instead of quoted) against QUOTE_ASSET", "assetDecimals": "Decimal places for this asset" } */ function getInvertedPriceInfo(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint assetDecimals) { uint inputPrice; // inputPrice quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal (isRecent, inputPrice, assetDecimals) = getPriceInfo(ofAsset); // outputPrice based in QUOTE_ASSET and multiplied by 10 ** quoteDecimal uint quoteDecimals = getDecimals(QUOTE_ASSET); return ( isRecent, mul(10 ** uint(quoteDecimals), 10 ** uint(assetDecimals)) / inputPrice, quoteDecimals // TODO: check on this; shouldn't it be assetDecimals? ); } /** @notice Gets reference price of an asset pair @dev One of the address is equal to quote asset @dev either ofBase == QUOTE_ASSET or ofQuote == QUOTE_ASSET @param ofBase Address of base asset @param ofQuote Address of quote asset @return { "isRecent": "Whether the price is fresh, given VALIDITY interval", "referencePrice": "Reference price", "decimal": "Decimal places for this asset" } */ function getReferencePriceInfo(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal) { if (getQuoteAsset() == ofQuote) { (isRecent, referencePrice, decimal) = getPriceInfo(ofBase); } else if (getQuoteAsset() == ofBase) { (isRecent, referencePrice, decimal) = getInvertedPriceInfo(ofQuote); } else { revert(); // no suitable reference price available } } /// @notice Gets price of Order /// @param sellAsset Address of the asset to be sold /// @param buyAsset Address of the asset to be bought /// @param sellQuantity Quantity in base units being sold of sellAsset /// @param buyQuantity Quantity in base units being bought of buyAsset /// @return orderPrice Price as determined by an order function getOrderPriceInfo( address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity ) view returns (uint orderPrice) { return mul(buyQuantity, 10 ** uint(getDecimals(sellAsset))) / sellQuantity; } /// @notice Checks whether data exists for a given asset pair /// @dev Prices are only upated against QUOTE_ASSET /// @param sellAsset Asset for which check to be done if data exists /// @param buyAsset Asset for which check to be done if data exists /// @return Whether assets exist for given asset pair function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent) { return hasRecentPrice(sellAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data hasRecentPrice(buyAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data (buyAsset == QUOTE_ASSET || sellAsset == QUOTE_ASSET) && // One asset must be QUOTE_ASSET (buyAsset != QUOTE_ASSET || sellAsset != QUOTE_ASSET); // Pair must consists of diffrent assets } /// @return Sparse array of addresses of owned pricefeeds function getPriceFeedsByOwner(address _owner) view returns(address[]) { address[] memory ofPriceFeeds = new address[](numStakers); if (numStakers == 0) return ofPriceFeeds; uint current = stakeNodes[0].next; for (uint i; i < numStakers; i++) { StakingPriceFeed stakingFeed = StakingPriceFeed(stakeNodes[current].data.staker); if (stakingFeed.owner() == _owner) { ofPriceFeeds[i] = address(stakingFeed); } current = stakeNodes[current].next; } return ofPriceFeeds; } function getHistoryLength() returns (uint) { return priceHistory.length; } function getHistoryAt(uint id) returns (address[], uint[], uint) { address[] memory assets = priceHistory[id].assets; uint[] memory prices = priceHistory[id].prices; uint timestamp = priceHistory[id].timestamp; return (assets, prices, timestamp); } } interface VersionInterface { // EVENTS event FundUpdated(uint id); // PUBLIC METHODS function shutDown() external; function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ); function shutDownFund(address ofFund); // PUBLIC VIEW METHODS function getNativeAsset() view returns (address); function getFundById(uint withId) view returns (address); function getLastFundId() view returns (uint); function getFundByManager(address ofManager) view returns (address); function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed); } contract Version is DBC, Owned, VersionInterface { // FIELDS bytes32 public constant TERMS_AND_CONDITIONS = 0xAA9C907B0D6B4890E7225C09CBC16A01CB97288840201AA7CDCB27F4ED7BF159; // Hashed terms and conditions as displayed on IPFS, decoded from base 58 // Constructor fields string public VERSION_NUMBER; // SemVer of Melon protocol version address public MELON_ASSET; // Address of Melon asset contract address public NATIVE_ASSET; // Address of Fixed quote asset address public GOVERNANCE; // Address of Melon protocol governance contract address public CANONICAL_PRICEFEED; // Address of the canonical pricefeed // Methods fields bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened address public COMPLIANCE; // restrict to Competition compliance module for this version address[] public listOfFunds; // A complete list of fund addresses created using this version mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version // EVENTS event FundUpdated(address ofFund); // METHODS // CONSTRUCTOR /// @param versionNumber SemVer of Melon protocol version /// @param ofGovernance Address of Melon governance contract /// @param ofMelonAsset Address of Melon asset contract function Version( string versionNumber, address ofGovernance, address ofMelonAsset, address ofNativeAsset, address ofCanonicalPriceFeed, address ofCompetitionCompliance ) { VERSION_NUMBER = versionNumber; GOVERNANCE = ofGovernance; MELON_ASSET = ofMelonAsset; NATIVE_ASSET = ofNativeAsset; CANONICAL_PRICEFEED = ofCanonicalPriceFeed; COMPLIANCE = ofCompetitionCompliance; } // EXTERNAL METHODS function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; } // PUBLIC METHODS /// @param ofFundName human-readable descriptive name (not necessarily unique) /// @param ofQuoteAsset Asset against which performance fee is measured against /// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15 /// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15 /// @param ofCompliance Address of participation module /// @param ofRiskMgmt Address of risk management module /// @param ofExchanges Addresses of exchange on which this fund can trade /// @param ofDefaultAssets Enable invest/redeem with these assets (quote asset already enabled) /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s function setupFund( bytes32 ofFundName, address ofQuoteAsset, uint ofManagementFee, uint ofPerformanceFee, address ofCompliance, address ofRiskMgmt, address[] ofExchanges, address[] ofDefaultAssets, uint8 v, bytes32 r, bytes32 s ) { require(!isShutDown); require(termsAndConditionsAreSigned(v, r, s)); require(CompetitionCompliance(COMPLIANCE).isCompetitionAllowed(msg.sender)); require(managerToFunds[msg.sender] == address(0)); // Add limitation for simpler migration process of shutting down and setting up fund address[] memory melonAsDefaultAsset = new address[](1); melonAsDefaultAsset[0] = MELON_ASSET; // Melon asset should be in default assets address ofFund = new Fund( msg.sender, ofFundName, NATIVE_ASSET, 0, 0, COMPLIANCE, ofRiskMgmt, CANONICAL_PRICEFEED, ofExchanges, melonAsDefaultAsset ); listOfFunds.push(ofFund); managerToFunds[msg.sender] = ofFund; emit FundUpdated(ofFund); } /// @dev Dereference Fund and shut it down /// @param ofFund Address of the fund to be shut down function shutDownFund(address ofFund) pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund) { Fund fund = Fund(ofFund); delete managerToFunds[msg.sender]; fund.shutDown(); emit FundUpdated(ofFund); } // PUBLIC VIEW METHODS /// @dev Proof that terms and conditions have been read and understood /// @param v ellipitc curve parameter v /// @param r ellipitc curve parameter r /// @param s ellipitc curve parameter s /// @return signed Whether or not terms and conditions have been read and understood function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) { return ecrecover( // Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing. // Signature order has also been changed in 1.6.7 and upcoming 1.7.x, // it will return rsv (same as geth; where v is [27, 28]). // Note that if you are using ecrecover, v will be either "00" or "01". // As a result, in order to use this value, you will have to parse it to an // integer and then add 27. This will result in either a 27 or a 28. // https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS), v, r, s ) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS } function getNativeAsset() view returns (address) { return NATIVE_ASSET; } function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; } function getLastFundId() view returns (uint) { return listOfFunds.length - 1; } function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; } }
override inherited update function to prevent manual update from authority
function update(address[] ofAssets, uint[] newPrices) external { revert(); }
196,360
pragma solidity ^0.4.4; import "./zeppelin-solidity/contracts/math/SafeMath.sol"; import "./zeppelin-solidity/contracts/token/StandardToken.sol"; import "./zeppelin-solidity/contracts/token/BasicToken.sol"; import "./Upgradable.sol"; contract ProductManagerV1 is Upgradable, BasicToken { using SafeMath for uint256; /* * The author of an iteration may claim knowledge of their iteration for later * use in plagiarism claims or dispute edjudication by the community by * registering a claim with their address, a keccak hash of their iteration * and a keccak hash of the parent iteration. * TODO audit this claim chain for security and functionality */ event AuthorshipClaim(address author, bytes32 proof); /* * Once an iteration has been claimed and the author in confident that it has * included in the blockchain, the author may propose their iteration by * revealing a URL containing the iteration that the community and owner can * verify against the proof. */ event IterationProposal(address author, bytes32 proof, string location); /* * Keep track of the production release and provide evidence to users that * they are using software whose authors have been compensated */ bytes32 public proofOfProductionRelease; /* * anyone may claim an iteration */ function claimAuthorship(address _author, bytes32 _proof) public { AuthorshipClaim(_author, _proof); } /* * anyone may propose an iteration */ function proposeIteration(address _author, bytes32 _proof, string _location) public { IterationProposal(_author, _proof, _location); } /* * The owner may accept proposals */ function acceptProposal(address _author, bytes32 _proof, uint256 _amount) onlyOwner public { balances[_author] = balances[_author].add(_amount); totalSupply = totalSupply.add(_amount); proofOfProductionRelease = _proof; } /* * The value of each share (coin, token, TODO work on the language) is the * proportion of value held by the contract to total supply * TODO confirm that the share value rounds down. */ function shareValue() constant public returns (uint256) { require(totalSupply > 0); return this.balance / totalSupply; } /* * Product tokens can be redemed for their share of the revenue (Ether for * now) held by the Product contract. */ function redeem(uint256 _amount) public { // make sure share holders have had enough time to upgrade if they want to // if the new contract is making a lot of money, early upgraders shouldn't // have an advantage uint256 value = shareValue(); balances[msg.sender] = balances[msg.sender].sub(_amount); totalSupply = totalSupply.sub(_amount); msg.sender.transfer(value * _amount); } /* * When a user upgrades to the next version it will call this to remove * the user from this contract */ function removeUser(address user, address _nextVersion) public { // only the next version can call this (done in upgrade) require(msg.sender == nextVersion); uint256 balance = balanceOf(user); uint256 claim = shareValue() * balance; balances[user] = balances[user].sub(balance); totalSupply = totalSupply.sub(balance); _nextVersion.send(claim); } function () public payable { } } // dummy next version for testing contract ProductManagerV2 is ProductManagerV1, StandardToken { function upgrade() public { require(previousVersion != address(0)); ProductManagerV1 pv = ProductManagerV1(previousVersion); require(pv.nextVersion() == address(this)); uint256 balance = pv.balanceOf(msg.sender); require(balance != 0); balances[msg.sender] = balances[msg.sender].add(balance); totalSupply = totalSupply.add(balance); pv.removeUser(msg.sender, address(this)); } }
The author of an iteration may claim knowledge of their iteration for later use in plagiarism claims or dispute edjudication by the community by registering a claim with their address, a keccak hash of their iteration and a keccak hash of the parent iteration. TODO audit this claim chain for security and functionality/ Once an iteration has been claimed and the author in confident that it has included in the blockchain, the author may propose their iteration by revealing a URL containing the iteration that the community and owner can verify against the proof./ Keep track of the production release and provide evidence to users that they are using software whose authors have been compensated/ anyone may claim an iteration/
function claimAuthorship(address _author, bytes32 _proof) public { AuthorshipClaim(_author, _proof); }
2,483,385
pragma solidity 0.4.24; //@Dev this Contract sole purpose is to contain functions that will aid other contracts with certain //Tasks like checking if a string is null or empty //Created for abstraction purposes //Also keep common data structures contract HelperFunctions { //@Dev represents grower Data struct Data { string data; uint256 Index; } //@Dev Represents a Contract as well as what version its currently on struct Contract { address ID; uint256 version; bool Activated; } //@Dev constructor constructor() public { } //@Dev represents an object that can be used to keep track of the different versions of a contract struct ContractVersions { address LatestContractAddress; bool Activated; uint Index;//@Dev represents the number of contract versions we've had mapping(uint256=> Contract) PreviousVersions; } //@Dev Used to log messages returned by functions event GeneralLogger(string message); //@Dev Converts bytes32 to string function bytes32ToString(bytes32 x) pure public returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } //@Dev Converts a string to bytes 32 function stringToBytes32(string memory x) pure public returns (bytes32 result) { require(!isStringNullorEmpty(x));//@Dev ensure that the string is not null bytes memory newString = bytes(x); assembly { result := mload(add(newString, 32)) } } //@Dev this functions tests if a given string is null or empty by converting it to a type bytes and checking //if the length of the bytes is greater than zero function isStringNullorEmpty(string value) pure public returns (bool success) { bytes memory tester = bytes(value); //@Dev Uses memory success=tester.length==0; return success; } }
@Dev Converts bytes32 to string
function bytes32ToString(bytes32 x) pure public returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); }
2,538,949
// SPDX-License-Identifier: MIT //o 8 o o o //8 8 `b d' 8 //8 .oPYo. .oPYo. .oPYo. 8 .oPYo. `bd' 8 //8 8oooo8 8 8 .oooo8 8 .oooo8 .PY. 8 //8 8. 8 8 8 8 8 8 8 .P Y. 8 //8oooo `Yooo' `YooP8 `YooP8 8 `YooP8 .P Y. 8 //......:.....::....8 :.....:..:.....:..::::..:.. //:::::::::::::::ooP'.::::::::::::::::::::::::::: //:::::::::::::::...::::::::::::::::::::::::::::: // LegalaXI /* Sceptres are being sharpened. Swords polished.A new league of super warriors are gearing up to Protect. Fight. Win. They may not be one of us, but they’re here for us. The planets seem to be gearing up for the unknown, yet again. And so should we. An army of 10,000 super warriors being prepped for the new war. They’re each unique, with their own set of features and super powers. Each one has his or her own strength, derived from the powers of their planet. Start minting your super warriors and get your army ready. The war is around the corner. This time around, the war will be in cyberspace. Well, we may be exaggerating a bit. But what if we’re not? Are you ready? **/ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/ERC721Mod.sol // Creator: Chiru Labs pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Does not support burning tokens to address(0). * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721Mod is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal currentIndex; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), 'ERC721Mod: global index out of bounds'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), 'ERC721Mod: owner index out of bounds'); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('ERC721Mod: unable to get token of owner by index'); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), 'ERC721Mod: balance query for the zero address'); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require(owner != address(0), 'ERC721Mod: number minted query for the zero address'); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'ERC721Mod: owner query for nonexistent token'); unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('ERC721Mod: unable to determine the owner of token'); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { 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 override { address owner = ERC721Mod.ownerOf(tokenId); require(to != owner, 'ERC721Mod: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721Mod: approve caller is not owner nor approved for all' ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'ERC721Mod: approved query for nonexistent token'); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), 'ERC721Mod: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721Mod: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = currentIndex; require(to != address(0), 'ERC721Mod: mint to the zero address'); require(quantity != 0, 'ERC721Mod: quantity must be greater than 0'); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe) { require( _checkOnERC721Received(address(0), to, updatedIndex, _data), 'ERC721Mod: transfer to non ERC721Receiver implementer' ); } updatedIndex++; } currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require(isApprovedOrOwner, 'ERC721Mod: transfer caller is not owner nor approved'); require(prevOwnership.addr == from, 'ERC721Mod: transfer from incorrect owner'); require(to != address(0), 'ERC721Mod: transfer to the zero address'); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @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('ERC721Mod: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/LegalaXICollectible.sol // LegalaXI pragma solidity >=0.7.0 <0.9.0; contract LegalaXICollectible is ERC721Mod, Ownable { using Strings for uint256; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0.05 ether; uint256 public maxSupply = 10001; uint256 public maxMintAmountPerTx = 15; bool public paused = true; bool public revealed = false; constructor() ERC721Mod("LegalaXI", "LXI") { setHiddenMetadataUri("ipfs://QmQ6M8VCRSAd88zamM3ndNUp7RA8JgwBK5d8a7rStLJ3X9/hidden.json"); } modifier mintCompliance(uint256 _mintQuantity) { require(_mintQuantity > 0 && _mintQuantity <= maxMintAmountPerTx, "Invalid mint amount!"); require(totalSupply() + _mintQuantity <= maxSupply, "Max supply exceeded!"); _; } function mintbyPublic(uint256 _mintQuantity) public payable mintCompliance(_mintQuantity) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintQuantity, "Insufficient funds!"); _mintLegoAliens(msg.sender, _mintQuantity); } function mintbyOwner(uint256 _mintQuantity) public mintCompliance(_mintQuantity) onlyOwner{ _mintLegoAliens(msg.sender, _mintQuantity); } function mintForAddress(uint256 _mintQuantity, address _receiver) public mintCompliance(_mintQuantity) onlyOwner { _mintLegoAliens(_receiver, _mintQuantity); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } function _mintLegoAliens(address _receiver, uint256 _quantity) internal { _safeMint(_receiver, _quantity); } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _data bytes optional data to send along with the call return bool whether the call correctly returned the expected magic value/
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert('ERC721Mod: transfer to non ERC721Receiver implementer'); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
1,395,926
./full_match/1/0x62A541a62AFB6afa8ED6081Dec283dF9D5fe2c01/sources/WatchecksEngine.sol
less than 86401 this function setTimeZone for specific Watchecks, can be called only by token owner id is the token that you want set time zone for time is the offset with respect to UTC + 1 sec , time should be less than 86400
function setTimeZone(uint256 id, uint256 time) public { require(time < 86401, "Invalid time"); require(time >0,"very Invalid time"); require(msg.sender == Imini721(targetContract).ownerOf(id),"you are not the owner"); _offsets[id] = time; }
2,912,432
// SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./interfaces/IWnD.sol"; import "./interfaces/ITower.sol"; import "./interfaces/ITraits.sol"; import "./interfaces/IGP.sol"; contract WnD is IWnD, ERC721Enumerable, Ownable, Pausable { struct LastWrite { uint64 time; uint64 blockNum; } // max number of tokens that can be minted: 60000 in production uint256 public maxTokens; // number of tokens that can be claimed for a fee: 15,000 uint256 public PAID_TOKENS; // number of tokens have been minted so far uint16 public override minted; uint16 private numWizards; uint16 private numDragons; uint16 private numWizardsStolen; uint16 private numDragonsStolen; uint16 private numWizardsBurned; uint16 private numDragonsBurned; // mapping from tokenId to a struct containing the token's traits mapping(uint256 => WizardDragon) public override tokenTraits; // mapping from hashed(tokenTrait) to the tokenId it's associated with // used to ensure there are no duplicates mapping(uint256 => uint256) public existingCombinations; // Tracks the last block and timestamp that a caller has written to state. // Disallow some access to functions if they occur while a change is being written. mapping(address => LastWrite) private lastWrite; // list of probabilities for each trait type // 0 - 9 are associated with Wizard, 10 - 18 are associated with Dragons uint8[][18] public rarities; // list of aliases for Walker's Alias algorithm // 0 - 9 are associated with Wizard, 10 - 18 are associated with Dragons uint8[][18] public aliases; // reference to the Tower contract to allow transfers to it without approval ITower public tower; // reference to Traits ITraits public traits; // address => allowedToCallFunctions mapping(address => bool) private admins; constructor(uint256 _maxTokens) ERC721("Contract2", "Contract2") { maxTokens = _maxTokens; PAID_TOKENS = _maxTokens / 4; _pause(); // A.J. Walker's Alias Algorithm // Wizards // body rarities[0] = [80, 150, 200, 250, 255]; aliases[0] = [4, 4, 4, 4, 4]; // head rarities[1] = [150, 40, 240, 90, 115, 135, 40, 199, 100]; aliases[1] = [3, 7, 4, 0, 5, 6, 8, 5, 0]; // spell rarities[2] = [255, 135, 60, 130, 190, 156, 250, 120, 60, 25, 190]; aliases[2] = [0, 0, 0, 6, 6, 0, 0, 0, 6, 8, 0]; // eyes rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254]; aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 0]; // neck rarities[4] = [175, 100, 40, 250, 115, 100, 80, 110, 180, 255, 210, 180]; aliases[4] = [3, 0, 4, 1, 11, 7, 8, 10, 9, 9, 8, 8]; // mouth rarities[5] = [80, 225, 220, 35, 100, 240, 70, 160, 175, 217, 175, 60]; aliases[5] = [1, 2, 5, 8, 2, 8, 8, 9, 9, 10, 7, 10]; // neck rarities[6] = [255]; aliases[6] = [0]; // wand rarities[7] = [243, 189, 50, 30, 55, 180, 80, 90, 155, 30, 222, 255]; aliases[7] = [1, 7, 5, 2, 11, 11, 0, 10, 0, 0, 11, 3]; // rankIndex rarities[8] = [255]; aliases[8] = [0]; // Dragons // body rarities[9] = [100, 80, 177, 199, 255, 40, 211, 177, 25, 230, 90, 130, 199, 230]; aliases[9] = [4, 3, 3, 4, 4, 13, 9, 1, 2, 5, 13, 0, 6, 12]; // head rarities[10] = [255]; aliases[10] = [0]; // spell rarities[11] = [255]; aliases[11] = [0]; // eyes rarities[12] = [90, 40, 219, 80, 183, 225, 40, 120, 60, 220]; aliases[12] = [1, 8, 3, 2, 5, 6, 5, 9, 4, 3]; // nose rarities[13] = [255]; aliases[13] = [0]; // mouth rarities[14] = [239, 244, 255, 234, 234, 234, 234, 234, 234, 234, 234, 234, 234, 234]; aliases[14] = [1, 2, 2, 0, 2, 2, 9, 0, 5, 4, 4, 4, 4, 4]; // tails rarities[15] = [80, 200, 144, 145, 80, 140, 120]; aliases[15] = [1, 8, 0, 0, 3, 0, 3]; // wand rarities[16] = [255]; aliases[16] = [0]; // rankIndex rarities[17] = [14, 155, 80, 255]; aliases[17] = [2, 3, 3, 3]; } /** CRITICAL TO SETUP / MODIFIERS */ modifier requireContractsSet() { require(address(traits) != address(0) && address(tower) != address(0), "Contracts not set"); _; } modifier disallowIfStateIsChanging() { // frens can always call whenever they want :) require(admins[_msgSender()] || lastWrite[tx.origin].blockNum < block.number, "hmmmm what doing?"); _; } function setContracts(address _traits, address _tower) external onlyOwner { traits = ITraits(_traits); tower = ITower(_tower); } /** EXTERNAL */ function getNumWizards() external view disallowIfStateIsChanging returns (uint16) { return numWizards; } function getNumWizardsStolen() external view disallowIfStateIsChanging returns (uint16) { return numWizardsStolen; } function getNumDragons() external view disallowIfStateIsChanging returns (uint16) { return numDragons; } function getNumDragonsStolen() external view disallowIfStateIsChanging returns (uint16) { return numDragonsStolen; } function getNumWizardsBurned() external view disallowIfStateIsChanging returns (uint16) { return numWizardsBurned; } function getNumDragonsBurned() external view disallowIfStateIsChanging returns (uint16) { return numDragonsBurned; } /** * Mint a token - any payment / game logic should be handled in the game contract. * This will just generate random traits and mint a token to a designated address. */ function mint(address recipient, uint256 seed) external override whenNotPaused { require(admins[_msgSender()], "Only admins can call this"); require(minted + 1 <= maxTokens, "All tokens minted"); minted++; generate(minted, seed, lastWrite[tx.origin]); if(tx.origin != recipient && recipient != address(tower)) { // Stolen! if(tokenTraits[minted].isWizard) { numWizardsStolen += 1; } else { numDragonsStolen += 1; } } _safeMint(recipient, minted); } /** * Burn a token - any game logic should be handled before this function. */ function burn(uint256 tokenId) external override whenNotPaused { require(admins[_msgSender()], "Only admins can call this"); require(ownerOf(tokenId) == tx.origin, "Oops you don't own that"); if(tokenTraits[minted].isWizard) { numWizardsBurned += 1; } else { numDragonsBurned += 1; } _burn(tokenId); } function updateOriginAccess() external override { require(admins[_msgSender()], "Only admins can call this"); lastWrite[tx.origin].blockNum = uint64(block.number); lastWrite[tx.origin].time = uint64(block.number); } function transferFrom( address from, address to, uint256 tokenId ) public virtual override(ERC721, IERC721) { // allow admin contracts to be send without approval if(!admins[_msgSender()]) { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); } _transfer(from, to, tokenId); } /** INTERNAL */ /** * generates traits for a specific token, checking to make sure it's unique * @param tokenId the id of the token to generate traits for * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of traits for the given token ID */ function generate(uint256 tokenId, uint256 seed, LastWrite memory lw) internal returns (WizardDragon memory t) { t = selectTraits(seed); if (existingCombinations[structToHash(t)] == 0) { tokenTraits[tokenId] = t; existingCombinations[structToHash(t)] = tokenId; if(t.isWizard) { numWizards += 1; } else { numDragons += 1; } return t; } return generate(tokenId, random(seed, lw.time, lw.blockNum), lw); } /** * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup * ensuring O(1) instead of O(n) reduces mint cost by more than 50% * probability & alias tables are generated off-chain beforehand * @param seed portion of the 256 bit seed to remove trait correlation * @param traitType the trait type to select a trait for * @return the ID of the randomly selected trait */ function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) { uint8 trait = uint8(seed) % uint8(rarities[traitType].length); // If a selected random trait probability is selected (biased coin) return that trait if (seed >> 8 < rarities[traitType][trait]) return trait; return aliases[traitType][trait]; } /** * selects the species and all of its traits based on the seed value * @param seed a pseudorandom 256 bit number to derive traits from * @return t - a struct of randomly selected traits */ function selectTraits(uint256 seed) internal view returns (WizardDragon memory t) { t.isWizard = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isWizard ? 0 : 9; seed >>= 16; t.body = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.spell = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.eyes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.neck = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.mouth = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.tail = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.wand = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.rankIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); } /** * converts a struct to a 256 bit hash to check for uniqueness * @param s the struct to pack into a hash * @return the 256 bit hash of the struct */ function structToHash(WizardDragon memory s) internal pure returns (uint256) { return uint256(keccak256( abi.encodePacked( s.isWizard, s.body, s.head, s.spell, s.eyes, s.neck, s.mouth, s.tail, s.wand, s.rankIndex ) )); } /** * generates a pseudorandom number for picking traits. Uses point in time randomization to prevent abuse. */ function random(uint256 seed, uint64 timestamp, uint64 blockNumber) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(blockNumber > 1 ? blockNumber - 2 : blockNumber),// Different block than WnDGame to ensure if needing to re-randomize that it goes down a different path timestamp, seed ))); } /** READ */ function getMaxTokens() external view override returns (uint256) { return maxTokens; } function getPaidTokens() external view override returns (uint256) { return PAID_TOKENS; } /** ADMIN */ /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { payable(owner()).transfer(address(this).balance); } /** * updates the number of tokens for sale */ function setPaidTokens(uint256 _paidTokens) external onlyOwner { PAID_TOKENS = uint16(_paidTokens); } /** * enables owner to pause / unpause minting */ function setPaused(bool _paused) external requireContractsSet onlyOwner { if (_paused) _pause(); else _unpause(); } /** * enables an address to mint / burn * @param addr the address to enable */ function addAdmin(address addr) external onlyOwner { admins[addr] = true; } /** * disables an address from minting / burning * @param addr the address to disbale */ function removeAdmin(address addr) external onlyOwner { admins[addr] = false; } /** Traits */ function getTokenTraits(uint256 tokenId) external view override disallowIfStateIsChanging returns (WizardDragon memory) { return tokenTraits[tokenId]; } function tokenURI(uint256 tokenId) public view override disallowIfStateIsChanging returns (string memory) { require(_exists(tokenId), "Token ID does not exist"); return traits.tokenURI(tokenId); } /** OVERRIDES FOR SAFETY */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override(ERC721Enumerable, IERC721Enumerable) disallowIfStateIsChanging returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[owner].blockNum < block.number, "hmmmm what doing?"); return super.tokenOfOwnerByIndex(owner, index); } function balanceOf(address owner) public view virtual override(ERC721, IERC721) disallowIfStateIsChanging returns (uint256) { // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[owner].blockNum < block.number, "hmmmm what doing?"); return super.balanceOf(owner); } function ownerOf(uint256 tokenId) public view virtual override(ERC721, IERC721) disallowIfStateIsChanging returns (address) { address addr = super.ownerOf(tokenId); // Y U checking on this address in the same block it's being modified... hmmmm require(admins[_msgSender()] || lastWrite[addr].blockNum < block.number, "hmmmm what doing?"); return addr; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; interface IWnD is IERC721Enumerable { // game data storage struct WizardDragon { bool isWizard; uint8 body; uint8 head; uint8 spell; uint8 eyes; uint8 neck; uint8 mouth; uint8 wand; uint8 tail; uint8 rankIndex; } function minted() external returns (uint16); function updateOriginAccess() external; function mint(address recipient, uint256 seed) external; function burn(uint256 tokenId) external; function getMaxTokens() external view returns (uint256); function getPaidTokens() external view returns (uint256); function getTokenTraits(uint256 tokenId) external view returns (WizardDragon memory); function tokenTraits(uint256 tokenId) external view returns (bool a, uint8 b, uint8 c, uint8 d, uint8 e, uint8 f, uint8 g, uint8 h, uint8 i, uint8 j); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITower { function addManyToTowerAndFlight(address account, uint16[] calldata tokenIds) external; function randomDragonOwner(uint256 seed) external view returns (address); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface ITraits { function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT LICENSE pragma solidity ^0.8.0; interface IGP { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function updateOriginAccess() external; function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
selects the species and all of its traits based on the seed value seed a pseudorandom 256 bit number to derive traits from return t - a struct of randomly selected traits/
function selectTraits(uint256 seed) internal view returns (WizardDragon memory t) { t.isWizard = (seed & 0xFFFF) % 10 != 0; uint8 shift = t.isWizard ? 0 : 9; seed >>= 16; t.body = selectTrait(uint16(seed & 0xFFFF), 0 + shift); seed >>= 16; t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift); seed >>= 16; t.spell = selectTrait(uint16(seed & 0xFFFF), 2 + shift); seed >>= 16; t.eyes = selectTrait(uint16(seed & 0xFFFF), 3 + shift); seed >>= 16; t.neck = selectTrait(uint16(seed & 0xFFFF), 4 + shift); seed >>= 16; t.mouth = selectTrait(uint16(seed & 0xFFFF), 5 + shift); seed >>= 16; t.tail = selectTrait(uint16(seed & 0xFFFF), 6 + shift); seed >>= 16; t.wand = selectTrait(uint16(seed & 0xFFFF), 7 + shift); seed >>= 16; t.rankIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift); }
1,286,064
// File: contracts/interfaces/ISaffronBase.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.1; interface ISaffronBase { enum Tranche {S, AA, A} enum LPTokenType {dsec, principal} // Store values (balances, dsec, vdsec) with TrancheUint256 struct TrancheUint256 { uint256 S; uint256 AA; uint256 A; } struct epoch_params { uint256 start_date; // Time when the platform launched uint256 duration; // Duration of epoch } } // File: contracts/interfaces/ISaffronStrategy.sol pragma solidity ^0.7.1; interface ISaffronStrategy is ISaffronBase{ function deploy_all_capital() external; function select_adapter_for_liquidity_removal() external returns(address); function add_adapter(address adapter_address) external; function add_pool(address pool_address) external; function delete_adapters() external; function set_governance(address to) external; function get_adapter_address(uint256 adapter_index) external view returns(address); function set_pool_SFI_reward(uint256 poolIndex, uint256 reward) external; } // File: contracts/interfaces/ISaffronPool.sol pragma solidity ^0.7.1; interface ISaffronPool is ISaffronBase { function add_liquidity(uint256 amount, Tranche tranche) external; function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external; function get_base_asset_address() external view returns(address); function hourly_strategy(address adapter_address) external; function wind_down_epoch(uint256 epoch, uint256 amount_sfi) external; function set_governance(address to) external; function get_epoch_cycle_params() external view returns (uint256, uint256); function shutdown() external; } // File: contracts/interfaces/ISaffronAdapter.sol pragma solidity ^0.7.1; interface ISaffronAdapter is ISaffronBase { function deploy_capital(uint256 amount) external; function return_capital(uint256 base_asset_amount, address to) external; function approve_transfer(address addr,uint256 amount) external; function get_base_asset_address() external view returns(address); function set_base_asset(address addr) external; function get_holdings() external returns(uint256); function get_interest(uint256 principal) external returns(uint256); function set_governance(address to) external; } // File: contracts/lib/SafeMath.sol pragma solidity ^0.7.1; /** * @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/lib/IERC20.sol pragma solidity ^0.7.1; /** * @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/lib/Context.sol pragma solidity ^0.7.1; /* * @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/lib/Address.sol pragma solidity ^0.7.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 * ==== */ 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.3._ */ 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.3._ */ 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/lib/ERC20.sol pragma solidity ^0.7.1; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/lib/SafeERC20.sol pragma solidity ^0.7.1; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/SFI.sol pragma solidity ^0.7.1; contract SFI is ERC20 { using SafeERC20 for IERC20; address public governance; address public SFI_minter; uint256 public MAX_TOKENS = 100000 ether; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Initial governance is Saffron Deployer governance = msg.sender; } function mint_SFI(address to, uint256 amount) public { require(msg.sender == SFI_minter, "must be SFI_minter"); require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS"); _mint(to, amount); } function set_minter(address to) external { require(msg.sender == governance, "must be governance"); SFI_minter = to; } function set_governance(address to) external { require(msg.sender == governance, "must be governance"); governance = to; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } } // File: contracts/SaffronLPBalanceToken.sol pragma solidity ^0.7.1; contract SaffronLPBalanceToken is ERC20 { address public pool_address; constructor (string memory name, string memory symbol) ERC20(name, symbol) { // Set pool_address to saffron pool that created token pool_address = msg.sender; } // Allow creating new tranche tokens function mint(address to, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _mint(to, amount); } function burn(address account, uint256 amount) public { require(msg.sender == pool_address, "must be pool"); _burn(account, amount); } function set_governance(address to) external { require(msg.sender == pool_address, "must be pool"); pool_address = to; } } // File: contracts/SaffronPool.sol pragma solidity ^0.7.1; contract SaffronPool is ISaffronPool { using SafeMath for uint256; using SafeERC20 for IERC20; address public governance; // Governance (v3: add off-chain/on-chain governance) address public base_asset_address; // Base asset managed by the pool (DAI, USDT, YFI...) address public SFI_address; // SFI token uint256 public pool_principal; // Current principal balance (added minus removed) uint256 public pool_interest; // Current interest balance (redeemable by dsec tokens) uint256 public tranche_A_multiplier; // Current yield multiplier for tranche A uint256 public SFI_ratio; // Ratio of base asset to SFI necessary to join tranche A bool public _shutdown = false; // v0, v1: shutdown the pool after the final capital deploy to prevent burning funds /**** ADAPTERS ****/ address public best_adapter_address; // Current best adapter selected by strategy uint256 public adapter_total_principal; // v0, v1: only one adapter ISaffronAdapter[] private adapters; // v2: list of adapters mapping(address=>uint256) private adapter_index; // v1: adapter contract address lookup for array indexes /**** STRATEGY ****/ address public strategy; /**** EPOCHS ****/ epoch_params public epoch_cycle = epoch_params({ start_date: 1604239200, // 11/01/2020 @ 2:00pm (UTC) duration: 14 days // 1210000 seconds }); /**** EPOCH INDEXED STORAGE ****/ uint256[] public epoch_principal; // Total principal owned by the pool (all tranches) mapping(uint256=>bool) public epoch_wound_down; // True if epoch has been wound down already (governance) /**** EPOCH-TRANCHE INDEXED STORAGE ****/ // Array of arrays, example: tranche_SFI_earned[epoch][Tranche.S] address[3][] public dsec_token_addresses; // Address for each dsec token address[3][] public principal_token_addresses; // Address for each principal token uint256[3][] public tranche_total_dsec; // Total dsec (tokens + vdsec) uint256[3][] public tranche_total_principal; // Total outstanding principal tokens uint256[3][] public tranche_total_utilized; // Total utilized balance in each tranche uint256[3][] public tranche_total_unutilized; // Total unutilized balance in each tranche uint256[3][] public tranche_S_virtual_utilized; // Total utilized virtual balance taken from tranche S (first index unused) uint256[3][] public tranche_S_virtual_unutilized; // Total unutilized virtual balance taken from tranche S (first index unused) uint256[3][] public tranche_interest_earned; // Interest earned (calculated at wind_down_epoch) uint256[3][] public tranche_SFI_earned; // Total SFI earned (minted at wind_down_epoch) /**** SFI GENERATION ****/ // v0: pool generates SFI based on subsidy schedule // v1: pool is distributed SFI generated by the strategy contract // v1: pools each get an amount of SFI generated depending on the total liquidity added within each interval TrancheUint256 public TRANCHE_SFI_MULTIPLIER = TrancheUint256({ S: 90000, AA: 0, A: 10000 }); /**** TRANCHE BALANCES ****/ // (v0 & v1: epochs are hard-forks) // (v2: epoch rollover implemented) // TrancheUint256 private eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms) // TrancheUint256 private eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter /**** SAFFRON LP TOKENS ****/ // If we just have a token address then we can look up epoch and tranche balance tokens using a mapping(address=>SaffronLPdsecInfo) // LP tokens are dsec (redeemable for interest+SFI) and principal (redeemable for base asset) tokens struct SaffronLPTokenInfo { bool exists; uint256 epoch; Tranche tranche; LPTokenType token_type; } mapping(address=>SaffronLPTokenInfo) private saffron_LP_token_info; constructor(address _strategy, address _base_asset, address _SFI_address, uint256 _SFI_ratio, bool epoch_cycle_reset) { governance = msg.sender; base_asset_address = _base_asset; strategy = _strategy; SFI_address = _SFI_address; tranche_A_multiplier = 10; // v1: start enhanced yield at 10X SFI_ratio = _SFI_ratio; // v1: constant ratio epoch_cycle.duration = (epoch_cycle_reset ? 20 minutes : 14 days); // Make testing previous epochs easier epoch_cycle.start_date = (epoch_cycle_reset ? (block.timestamp) - (4 * epoch_cycle.duration) : 1604239200); // Make testing previous epochs easier } function new_epoch(uint256 epoch, address[] memory saffron_LP_dsec_token_addresses, address[] memory saffron_LP_principal_token_addresses) public { require(tranche_total_principal.length == epoch, "improper new epoch"); require(governance == msg.sender, "must be governance"); epoch_principal.push(0); tranche_total_dsec.push([0,0,0]); tranche_total_principal.push([0,0,0]); tranche_total_utilized.push([0,0,0]); tranche_total_unutilized.push([0,0,0]); tranche_S_virtual_utilized.push([0,0,0]); tranche_S_virtual_unutilized.push([0,0,0]); tranche_interest_earned.push([0,0,0]); tranche_SFI_earned.push([0,0,0]); dsec_token_addresses.push([ // Address for each dsec token saffron_LP_dsec_token_addresses[uint256(Tranche.S)], saffron_LP_dsec_token_addresses[uint256(Tranche.AA)], saffron_LP_dsec_token_addresses[uint256(Tranche.A)] ]); principal_token_addresses.push([ // Address for each principal token saffron_LP_principal_token_addresses[uint256(Tranche.S)], saffron_LP_principal_token_addresses[uint256(Tranche.AA)], saffron_LP_principal_token_addresses[uint256(Tranche.A)] ]); // Token info for looking up epoch and tranche of dsec tokens by token contract address saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.S)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: LPTokenType.dsec }); saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.AA)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: LPTokenType.dsec }); saffron_LP_token_info[saffron_LP_dsec_token_addresses[uint256(Tranche.A)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: LPTokenType.dsec }); // for looking up epoch and tranche of PRINCIPAL tokens by token contract address saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.S)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.S, token_type: LPTokenType.principal }); saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.AA)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.AA, token_type: LPTokenType.principal }); saffron_LP_token_info[saffron_LP_principal_token_addresses[uint256(Tranche.A)]] = SaffronLPTokenInfo({ exists: true, epoch: epoch, tranche: Tranche.A, token_type: LPTokenType.principal }); } struct BalanceVars { // Tranche balance uint256 deposit; // User deposit uint256 capacity; // Capacity for user's intended tranche uint256 change; // Change from deposit - capacity // S tranche specific vars uint256 consumed; // Total consumed uint256 utilized_consumed; uint256 unutilized_consumed; uint256 available_utilized; uint256 available_unutilized; } event TrancheBalance(uint256 tranche, uint256 amount, uint256 deposit, uint256 capacity, uint256 change, uint256 consumed, uint256 utilized_consumed, uint256 unutilized_consumed, uint256 available_utilized, uint256 available_unutilized); event DsecGeneration(uint256 time_remaining, uint256 amount, uint256 dsec, address dsec_address, uint256 epoch, uint256 tranche, address user_address, address principal_token_addr); event AddLiquidity(uint256 new_pool_principal, uint256 new_epoch_principal, uint256 new_eternal_balance, uint256 new_tranche_principal, uint256 new_tranche_dsec); // LP user adds liquidity to the pool // Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S || tranche == Tranche.A, "v1: can't add_liquidity into AA tranche"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 13, "v1.13: only epoch 13 only"); BalanceVars memory bv = BalanceVars({ deposit: 0, capacity: 0, change: 0, consumed: 0, utilized_consumed: 0, unutilized_consumed: 0, available_utilized: 0, available_unutilized: 0 }); (bv.available_utilized, bv.available_unutilized) = get_available_S_balances(); if (tranche == Tranche.S) { tranche_total_unutilized[epoch][uint256(Tranche.S)] = tranche_total_unutilized[epoch][uint256(Tranche.S)].add(amount); bv.deposit = amount; } // if (tranche == Tranche.AA) {} // v1: AA tranche disabled (S tranche is effectively AA) if (tranche == Tranche.A) { // Find capacity for S tranche to facilitate a deposit into A. Deposit is min(principal, capacity): restricted by the user's capital or S tranche capacity bv.capacity = (bv.available_utilized.add(bv.available_unutilized)).div(tranche_A_multiplier); bv.deposit = (amount < bv.capacity) ? amount : bv.capacity; bv.consumed = bv.deposit.mul(tranche_A_multiplier); if (bv.consumed <= bv.available_utilized) { // Take capacity from tranche S utilized first and give virtual utilized balance to AA bv.utilized_consumed = bv.consumed; } else { // Take capacity from tranche S utilized and tranche S unutilized and give virtual utilized/unutilized balances to AA bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed); } tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(bv.utilized_consumed); if (bv.deposit < amount) bv.change = amount.sub(bv.deposit); } // Calculate the dsec for deposited DAI uint256 dsec = bv.deposit.mul(get_seconds_until_epoch_end(epoch)); // Update pool principal eternal and epoch state pool_principal = pool_principal.add(bv.deposit); // Add DAI to principal totals epoch_principal[epoch] = epoch_principal[epoch].add(bv.deposit); // Add DAI total balance for epoch // Update dsec and principal balance state tranche_total_dsec[epoch][uint256(tranche)] = tranche_total_dsec[epoch][uint256(tranche)].add(dsec); tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(bv.deposit); // Transfer DAI from LP to pool IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), bv.deposit); if (tranche == Tranche.A) IERC20(SFI_address).safeTransferFrom(msg.sender, address(this), bv.deposit * 1 ether / SFI_ratio); // Mint Saffron LP epoch 1 tranche dsec tokens and transfer them to sender SaffronLPBalanceToken(dsec_token_addresses[epoch][uint256(tranche)]).mint(msg.sender, dsec); // Mint Saffron LP epoch 1 tranche principal tokens and transfer them to sender SaffronLPBalanceToken(principal_token_addresses[epoch][uint256(tranche)]).mint(msg.sender, bv.deposit); emit TrancheBalance(uint256(tranche), bv.deposit, bv.deposit, bv.capacity, bv.change, bv.consumed, bv.utilized_consumed, bv.unutilized_consumed, bv.available_utilized, bv.available_unutilized); emit DsecGeneration(get_seconds_until_epoch_end(epoch), bv.deposit, dsec, dsec_token_addresses[epoch][uint256(tranche)], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch][uint256(tranche)]); emit AddLiquidity(pool_principal, epoch_principal[epoch], 0, tranche_total_principal[epoch][uint256(tranche)], tranche_total_dsec[epoch][uint256(tranche)]); } event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI); event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A); struct WindDownVars { uint256 previous_epoch; uint256 epoch_interest; uint256 epoch_dsec; uint256 tranche_A_interest_ratio; uint256 tranche_A_interest; uint256 tranche_S_interest; } function wind_down_epoch(uint256 epoch, uint256 amount_sfi) public override { require(msg.sender == strategy, "must be strategy"); require(!epoch_wound_down[epoch], "epoch already wound down"); uint256 current_epoch = get_current_epoch(); require(epoch < current_epoch, "cannot wind down future epoch"); WindDownVars memory wind_down = WindDownVars({ previous_epoch: 0, epoch_interest: 0, epoch_dsec: 0, tranche_A_interest_ratio: 0, tranche_A_interest: 0, tranche_S_interest: 0 }); wind_down.previous_epoch = current_epoch - 1; require(block.timestamp >= get_epoch_end(wind_down.previous_epoch), "can't call before epoch ended"); // Calculate SFI earnings per tranche tranche_SFI_earned[epoch][uint256(Tranche.S)] = TRANCHE_SFI_MULTIPLIER.S.mul(amount_sfi).div(100000); tranche_SFI_earned[epoch][uint256(Tranche.AA)] = TRANCHE_SFI_MULTIPLIER.AA.mul(amount_sfi).div(100000); tranche_SFI_earned[epoch][uint256(Tranche.A)] = TRANCHE_SFI_MULTIPLIER.A.mul(amount_sfi).div(100000); emit WindDownEpochSFI(wind_down.previous_epoch, tranche_SFI_earned[epoch][uint256(Tranche.S)], tranche_SFI_earned[epoch][uint256(Tranche.AA)], tranche_SFI_earned[epoch][uint256(Tranche.A)]); // Calculate interest earnings per tranche // Wind down will calculate interest and SFI earned by each tranche for the epoch which has ended // Liquidity cannot be removed until wind_down_epoch is called and epoch_wound_down[epoch] is set to true // Calculate pool_interest // v0, v1: we only have one adapter ISaffronAdapter adapter = ISaffronAdapter(best_adapter_address); wind_down.epoch_interest = adapter.get_interest(adapter_total_principal); pool_interest = pool_interest.add(wind_down.epoch_interest); // Total dsec // TODO: assert (dsec.totalSupply == epoch_dsec) wind_down.epoch_dsec = tranche_total_dsec[epoch][uint256(Tranche.S)].add(tranche_total_dsec[epoch][uint256(Tranche.A)]); wind_down.tranche_A_interest_ratio = tranche_total_dsec[epoch][uint256(Tranche.A)].mul(1 ether).div(wind_down.epoch_dsec); // Calculate tranche share of interest wind_down.tranche_A_interest = (wind_down.epoch_interest.mul(wind_down.tranche_A_interest_ratio).div(1 ether)).mul(tranche_A_multiplier); wind_down.tranche_S_interest = wind_down.epoch_interest.sub(wind_down.tranche_A_interest); // Update state for remove_liquidity tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest; tranche_interest_earned[epoch][uint256(Tranche.AA)] = 0; tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest; // Distribute SFI earnings to S tranche based on S tranche % share of dsec via vdsec emit WindDownEpochState(epoch, wind_down.tranche_S_interest, 0, wind_down.tranche_A_interest, uint256(tranche_SFI_earned[epoch][uint256(Tranche.S)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.AA)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.A)])); epoch_wound_down[epoch] = true; delete wind_down; } event RemoveLiquidityDsec(uint256 dsec_percent, uint256 interest_owned, uint256 SFI_owned); event RemoveLiquidityPrincipal(uint256 principal); function remove_liquidity(address dsec_token_address, uint256 dsec_amount, address principal_token_address, uint256 principal_amount) external override { require(dsec_amount > 0 || principal_amount > 0, "can't remove 0"); ISaffronAdapter best_adapter = ISaffronAdapter(best_adapter_address); uint256 interest_owned; uint256 SFI_earn; uint256 SFI_return; uint256 dsec_percent; // Update state for removal via dsec token if (dsec_token_address != address(0x0) && dsec_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[dsec_token_address]; require(token_info.exists, "balance token lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.dsec, "bad dsec address"); require(token_epoch == 13, "v1.13: bal token epoch must be 13"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); uint256 tranche_dsec = tranche_total_dsec[token_epoch][uint256(token_info.tranche)]; // Dsec gives user claim over a tranche's earned SFI and interest dsec_percent = (tranche_dsec == 0) ? 0 : dsec_amount.mul(1 ether).div(tranche_dsec); interest_owned = tranche_interest_earned[token_epoch][uint256(token_info.tranche)].mul(dsec_percent) / 1 ether; SFI_earn = tranche_SFI_earned[token_epoch][uint256(token_info.tranche)].mul(dsec_percent) / 1 ether; tranche_interest_earned[token_epoch][uint256(token_info.tranche)] = tranche_interest_earned[token_epoch][uint256(token_info.tranche)].sub(interest_owned); tranche_SFI_earned[token_epoch][uint256(token_info.tranche)] = tranche_SFI_earned[token_epoch][uint256(token_info.tranche)].sub(SFI_earn); tranche_total_dsec[token_epoch][uint256(token_info.tranche)] = tranche_total_dsec[token_epoch][uint256(token_info.tranche)].sub(dsec_amount); pool_interest = pool_interest.sub(interest_owned); } // Update state for removal via principal token if (principal_token_address != address(0x0) && principal_amount > 0) { // Get info about the v1 dsec token from its address and check that it exists SaffronLPTokenInfo memory token_info = saffron_LP_token_info[principal_token_address]; require(token_info.exists, "balance token info lookup failed"); SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); // Token epoch must be a past epoch uint256 token_epoch = token_info.epoch; require(token_info.token_type == LPTokenType.principal, "bad balance token address"); require(token_epoch == 13, "v1.13: bal token epoch must be 13"); require(epoch_wound_down[token_epoch], "can't remove from wound up epoch"); tranche_total_principal[token_epoch][uint256(token_info.tranche)] = tranche_total_principal[token_epoch][uint256(token_info.tranche)].sub(principal_amount); epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount); pool_principal = pool_principal.sub(principal_amount); adapter_total_principal = adapter_total_principal.sub(principal_amount); if (token_info.tranche == Tranche.A) SFI_return = principal_amount * 1 ether / SFI_ratio; } // Transfer if (dsec_token_address != address(0x0) && dsec_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(dsec_token_address); require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance"); sbt.burn(msg.sender, dsec_amount); if (interest_owned > 0) { best_adapter.return_capital(interest_owned, msg.sender); } IERC20(SFI_address).safeTransfer(msg.sender, SFI_earn); emit RemoveLiquidityDsec(dsec_percent, interest_owned, SFI_earn); } if (principal_token_address != address(0x0) && principal_amount > 0) { SaffronLPBalanceToken sbt = SaffronLPBalanceToken(principal_token_address); require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance"); sbt.burn(msg.sender, principal_amount); best_adapter.return_capital(principal_amount, msg.sender); IERC20(SFI_address).safeTransfer(msg.sender, SFI_return); emit RemoveLiquidityPrincipal(principal_amount); } require((dsec_token_address != address(0x0) && dsec_amount > 0) || (principal_token_address != address(0x0) && principal_amount > 0), "no action performed"); } // Strategy contract calls this to deploy capital to platforms event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch); function hourly_strategy(address adapter_address) external override { require(msg.sender == strategy, "must be strategy"); require(!_shutdown, "pool shutdown"); uint256 epoch = get_current_epoch(); best_adapter_address = adapter_address; ISaffronAdapter best_adapter = ISaffronAdapter(adapter_address); uint256 amount = IERC20(base_asset_address).balanceOf(address(this)); // Update utilized/unutilized epoch-tranche state tranche_total_utilized[epoch][uint256(Tranche.S)] = tranche_total_utilized[epoch][uint256(Tranche.S)].add(tranche_total_unutilized[epoch][uint256(Tranche.S)]); tranche_total_utilized[epoch][uint256(Tranche.A)] = tranche_total_utilized[epoch][uint256(Tranche.A)].add(tranche_total_unutilized[epoch][uint256(Tranche.A)]); tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)]); tranche_total_unutilized[epoch][uint256(Tranche.S)] = 0; tranche_total_unutilized[epoch][uint256(Tranche.A)] = 0; tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = 0; // Add principal to adapter total adapter_total_principal = adapter_total_principal.add(amount); emit StrategicDeploy(adapter_address, amount, epoch); // Move base assets to adapter and deploy IERC20(base_asset_address).safeTransfer(adapter_address, amount); best_adapter.deploy_capital(amount); } function shutdown() external override { require(msg.sender == strategy || msg.sender == governance, "must be strategy"); require(block.timestamp > get_epoch_end(1) - 1 days, "trying to shutdown too early"); _shutdown = true; } /*** GOVERNANCE ***/ function set_governance(address to) external override { require(msg.sender == governance, "must be governance"); governance = to; } function set_best_adapter(address to) external { require(msg.sender == governance, "must be governance"); best_adapter_address = to; } /*** TIME UTILITY FUNCTIONS ***/ function get_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)); } function get_current_epoch() public view returns (uint256) { require(block.timestamp > epoch_cycle.start_date, "before epoch 0"); return (block.timestamp - epoch_cycle.start_date) / epoch_cycle.duration; } function get_seconds_until_epoch_end(uint256 epoch) public view returns (uint256) { return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp); } /*** GETTERS ***/ function get_available_S_balances() public view returns(uint256, uint256) { uint256 epoch = get_current_epoch(); uint256 AA_A_utilized = tranche_S_virtual_utilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)]); uint256 AA_A_unutilized = tranche_S_virtual_unutilized[epoch][uint256(Tranche.A)].add(tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)]); uint256 S_utilized = tranche_total_utilized[epoch][uint256(Tranche.S)]; uint256 S_unutilized = tranche_total_unutilized[epoch][uint256(Tranche.S)]; return ((S_utilized > AA_A_utilized ? S_utilized - AA_A_utilized : 0), (S_unutilized > AA_A_unutilized ? S_unutilized - AA_A_unutilized : 0)); } function get_epoch_cycle_params() external view override returns (uint256, uint256) { return (epoch_cycle.start_date, epoch_cycle.duration); } function get_base_asset_address() external view override returns(address) { return base_asset_address; } //***** ADAPTER FUNCTIONS *****// // Delete adapters (v0: for v0 wind-down) function delete_adapters() external { require(msg.sender == governance, "must be governance"); require(block.timestamp > get_epoch_end(13) + 10 weeks, "too soon"); delete adapters; } event ErcSwept(address who, address to, address token, uint256 amount); function erc_sweep(address _token, address _to) public { require(msg.sender == governance, "must be governance"); require(_token != base_asset_address && _token != SFI_address, "cannot sweep pool assets"); IERC20 tkn = IERC20(_token); uint256 tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); emit ErcSwept(msg.sender, _to, _token, tBal); } event Swept(address who, address to, uint256 sfiBal, uint256 baseBal); function sweep(address _to) public { require(msg.sender == governance, "must be governance"); IERC20 tkn = IERC20(address(SFI_address)); uint256 sfiBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, sfiBal); IERC20 base = IERC20(address(base_asset_address)); uint256 baseBal = base.balanceOf(address(this)); base.safeTransfer(_to, baseBal); emit Swept(msg.sender, _to, sfiBal, baseBal); } function set_strategy(address to) external { require(msg.sender == governance, "must be governance"); strategy = to; } }
LP user adds liquidity to the pool Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address if (tranche == Tranche.AA) {} v1: AA tranche disabled (S tranche is effectively AA) Find capacity for S tranche to facilitate a deposit into A. Deposit is min(principal, capacity): restricted by the user's capital or S tranche capacity Take capacity from tranche S utilized first and give virtual utilized balance to AA Take capacity from tranche S utilized and tranche S unutilized and give virtual utilized/unutilized balances to AA
function add_liquidity(uint256 amount, Tranche tranche) external override { require(!_shutdown, "pool shutdown"); require(tranche == Tranche.S || tranche == Tranche.A, "v1: can't add_liquidity into AA tranche"); uint256 epoch = get_current_epoch(); require(amount != 0, "can't add 0"); require(epoch == 13, "v1.13: only epoch 13 only"); BalanceVars memory bv = BalanceVars({ deposit: 0, capacity: 0, change: 0, consumed: 0, utilized_consumed: 0, unutilized_consumed: 0, available_utilized: 0, available_unutilized: 0 }); (bv.available_utilized, bv.available_unutilized) = get_available_S_balances(); if (tranche == Tranche.S) { tranche_total_unutilized[epoch][uint256(Tranche.S)] = tranche_total_unutilized[epoch][uint256(Tranche.S)].add(amount); bv.deposit = amount; } if (tranche == Tranche.A) { bv.capacity = (bv.available_utilized.add(bv.available_unutilized)).div(tranche_A_multiplier); bv.deposit = (amount < bv.capacity) ? amount : bv.capacity; bv.consumed = bv.deposit.mul(tranche_A_multiplier); if (bv.consumed <= bv.available_utilized) { bv.utilized_consumed = bv.consumed; bv.utilized_consumed = bv.available_utilized; bv.unutilized_consumed = bv.consumed.sub(bv.utilized_consumed); tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_unutilized[epoch][uint256(Tranche.AA)].add(bv.unutilized_consumed); } tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)] = tranche_S_virtual_utilized[epoch][uint256(Tranche.AA)].add(bv.utilized_consumed); if (bv.deposit < amount) bv.change = amount.sub(bv.deposit); } tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(bv.deposit); if (tranche == Tranche.A) IERC20(SFI_address).safeTransferFrom(msg.sender, address(this), bv.deposit * 1 ether / SFI_ratio); emit TrancheBalance(uint256(tranche), bv.deposit, bv.deposit, bv.capacity, bv.change, bv.consumed, bv.utilized_consumed, bv.unutilized_consumed, bv.available_utilized, bv.available_unutilized); emit DsecGeneration(get_seconds_until_epoch_end(epoch), bv.deposit, dsec, dsec_token_addresses[epoch][uint256(tranche)], epoch, uint256(tranche), msg.sender, principal_token_addresses[epoch][uint256(tranche)]); emit AddLiquidity(pool_principal, epoch_principal[epoch], 0, tranche_total_principal[epoch][uint256(tranche)], tranche_total_dsec[epoch][uint256(tranche)]); } event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI); event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A);
1,292,589
/** *Submitted for verification at Etherscan.io on 2021-03-27 */ /* https://powerpool.finance/ wrrrw r wrr ppwr rrr wppr0 prwwwrp prwwwrp wr0 rr 0rrrwrrprpwp0 pp pr prrrr0 pp 0r prrrr0 0rwrrr pp pr prrrr0 prrrr0 r0 rrp pr wr00rrp prwww0 pp wr pp w00r prwwwpr 0rw prwww0 pp wr pp wr r0 r0rprprwrrrp pr0 pp wr pr pp rwwr wr 0r pp wr pr wr pr r0 prwr wrr0wpwr 00 www0 0w0ww www0 0w 00 www0 www0 0www0 wrr ww0rrrr */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/interfaces/ILpTokenMigrator.sol pragma solidity 0.6.12; // note "contracts-ethereum-package" (but not "contracts") version of the package interface ILpTokenMigrator { // Perform LP token migration from legacy UniswapV2 to PowerSwap. // 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 UniswapV2 LP tokens. // PowerSwap must mint EXACTLY the same amount of PowerSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token, uint8 poolType) external returns (IERC20); } // File: contracts/interfaces/IVestedLPMining.sol pragma solidity 0.6.12; /** * @notice */ interface IVestedLPMining { /** * @notice Initializes the storage of the contract * @dev "constructor" to be called on a new proxy deployment * @dev Sets the contract `owner` account to the deploying account */ function initialize( IERC20 _cvp, address _reservoir, uint256 _cvpPerBlock, uint256 _startBlock, uint256 _cvpVestingPeriodInBlocks ) external; function poolLength() external view returns (uint256); /// @notice Add a new pool (only the owner may call) function add( uint256 _allocPoint, IERC20 _lpToken, uint8 _poolType, bool _votesEnabled, uint256 _lpBoostRate, uint256 _cvpBoostRate, uint256 _lpBoostMinRatio, uint256 _lpBoostMaxRatio ) external; /// @notice Update parameters of the given pool (only the owner may call) function set( uint256 _pid, uint256 _allocPoint, uint8 _poolType, bool _votesEnabled, uint256 _lpBoostRate, uint256 _cvpBoostRate, uint256 _lpBoostMinRatio, uint256 _lpBoostMaxRatio ) external; /// @notice Set the migrator contract (only the owner may call) function setMigrator(ILpTokenMigrator _migrator) external; /// @notice Set CVP reward per block (only the owner may call) /// @dev Consider updating pool before calling this function function setCvpPerBlock(uint256 _cvpPerBlock) external; /// @notice Set CVP vesting period in blocks (only the owner may call) function setCvpVestingPeriodInBlocks(uint256 _cvpVestingPeriodInBlocks) external; function setCvpPoolByMetaPool(address _metaPool, address _cvpPool) external; /// @notice Return the amount of pending CVPs entitled to the given user of the pool function pendingCvp(uint256 _pid, address _user) external view returns (uint256); /// @notice Return the amount of CVP tokens which may be vested to a user of a pool in the current block function vestableCvp(uint256 _pid, address user) external view returns (uint256); /// @notice Return `true` if the LP Token is added to created pools function isLpTokenAdded(IERC20 _lpToken) external view returns (bool); /// @notice Update reward computation params for all pools /// @dev Be careful of gas spending function massUpdatePools() external; /// @notice Update CVP tokens allocation for the given pool function updatePool(uint256 _pid) external; /// @notice Deposit the given amount of LP tokens to the given pool function deposit( uint256 _pid, uint256 _amount, uint256 _boostAmount ) external; /// @notice Withdraw the given amount of LP tokens from the given pool function withdraw( uint256 _pid, uint256 _amount, uint256 _boostAmount ) external; /// @notice Withdraw LP tokens without caring about pending CVP tokens. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external; /// @notice Write votes of the given user at the current block function checkpointVotes(address _user) external; /// @notice Get CVP amount and the share of CVPs in LP pools for the given account and the checkpoint function getCheckpoint(address account, uint32 checkpointId) external view returns ( uint32 fromBlock, uint96 cvpAmount, uint96 pooledCvpShare ); event AddLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint); event SetLpToken(address indexed lpToken, uint256 indexed pid, uint256 allocPoint); event SetMigrator(address indexed migrator); event SetCvpPerBlock(uint256 cvpPerBlock); event SetCvpVestingPeriodInBlocks(uint256 cvpVestingPeriodInBlocks); event SetCvpPoolByMetaPool(address indexed metaPool, address indexed cvpPool); event MigrateLpToken(address indexed oldLpToken, address indexed newLpToken, uint256 indexed pid); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 boostAmount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 boostAmount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 boostAmount); event CheckpointTotalLpVotes(uint256 lpVotes); event CheckpointUserLpVotes(address indexed user, uint256 indexed pid, uint256 lpVotes); event CheckpointUserVotes(address indexed user, uint256 pendedVotes, uint256 lpVotesShare); } // File: contracts/lib/ReservedSlots.sol pragma solidity 0.6.12; /// @dev Slots reserved for possible storage layout changes (it neither spends gas nor adds extra bytecode) contract ReservedSlots { uint256[100] private __gap; } // File: contracts/lib/SafeMath96.sol pragma solidity 0.6.12; library SafeMath96 { function add(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function add(uint96 a, uint96 b) internal pure returns (uint96) { return add(a, b, "SafeMath96: addition overflow"); } function sub(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function sub(uint96 a, uint96 b) internal pure returns (uint96) { return sub(a, b, "SafeMath96: subtraction overflow"); } function average(uint96 a, uint96 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function fromUint(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function fromUint(uint n) internal pure returns (uint96) { return fromUint(n, "SafeMath96: exceeds 96 bits"); } } // File: contracts/lib/SafeMath32.sol pragma solidity 0.6.12; library SafeMath32 { function add(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, errorMessage); return c; } function add(uint32 a, uint32 b) internal pure returns (uint32) { return add(a, b, "SafeMath32: addition overflow"); } function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); return a - b; } function sub(uint32 a, uint32 b) internal pure returns (uint32) { return sub(a, b, "SafeMath32: subtraction overflow"); } function fromUint(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function fromUint(uint n) internal pure returns (uint32) { return fromUint(n, "SafeMath32: exceeds 32 bits"); } } // File: contracts/lib/DelegatableCheckpoints.sol pragma solidity 0.6.12; library DelegatableCheckpoints { /// @dev A checkpoint storing some data effective from a given block struct Checkpoint { uint32 fromBlock; uint192 data; // uint32 __reserved; } /// @dev A set of checkpoints and a 'delegatee' struct Record { uint32 numCheckpoints; uint32 lastCheckpointBlock; address delegatee; // uint32 __reserved; // Checkpoints by IDs mapping (uint32 => Checkpoint) checkpoints; // Checkpoint IDs get counted from 1 (but not from 0) - // the 1st checkpoint has ID of 1, and the last checkpoint' ID is `numCheckpoints` } function getCheckpoint(Record storage record, uint checkpointId) internal view returns (uint32 fromBlock, uint192 data) { return checkpointId == 0 || checkpointId > record.numCheckpoints ? (0, 0) : _getCheckpoint(record, uint32(checkpointId)); } function _getCheckpoint(Record storage record, uint32 checkpointId) internal view returns (uint32 fromBlock, uint192 data) { return (record.checkpoints[checkpointId].fromBlock, record.checkpoints[checkpointId].data); } /** * @dev Gets the data recorded in the latest checkpoint of the given record */ function getLatestData(Record storage record) internal view returns (uint192, uint32) { Record memory _record = record; return _record.numCheckpoints == 0 ? (0, 0) : (record.checkpoints[_record.numCheckpoints].data, record.checkpoints[_record.numCheckpoints].fromBlock); } /** * @dev Returns the prior data written in the given record' checkpoints as of a block number * (reverts if the requested block has not been finalized) * @param record The record with checkpoints * @param blockNumber The block number to get the data at * @param checkpointId Optional ID of a checkpoint to first look into * @return The data effective as of the given block */ function getPriorData(Record storage record, uint blockNumber, uint checkpointId) internal view returns (uint192, uint32) { uint32 blockNum = _safeMinedBlockNum(blockNumber); Record memory _record = record; Checkpoint memory cp; // First check specific checkpoint, if it's provided if (checkpointId != 0) { require(checkpointId <= _record.numCheckpoints, "ChPoints: invalid checkpoint id"); uint32 cpId = uint32(checkpointId); cp = record.checkpoints[cpId]; if (cp.fromBlock == blockNum) { return (cp.data, cp.fromBlock); } else if (cp.fromBlock < cp.fromBlock) { if (cpId == _record.numCheckpoints) { return (cp.data, cp.fromBlock); } uint32 nextFromBlock = record.checkpoints[cpId + 1].fromBlock; if (nextFromBlock > blockNum) { return (cp.data, cp.fromBlock); } } } // Finally, search trough all checkpoints (uint32 checkpointId, uint192 data) = _findCheckpoint(record, _record.numCheckpoints, blockNum); return (data, record.checkpoints[checkpointId].fromBlock); } /** * @dev Finds a checkpoint in the given record for the given block number * (reverts if the requested block has not been finalized) * @param record The record with checkpoints * @param blockNumber The block number to get the checkpoint at * @return id The checkpoint ID * @return data The checkpoint data */ function findCheckpoint(Record storage record, uint blockNumber) internal view returns (uint32 id, uint192 data) { uint32 blockNum = _safeMinedBlockNum(blockNumber); uint32 numCheckpoints = record.numCheckpoints; (id, data) = _findCheckpoint(record, numCheckpoints, blockNum); } /** * @dev Writes a checkpoint with given data to the given record and returns the checkpoint ID */ function writeCheckpoint(Record storage record, uint192 data) internal returns (uint32 id) { uint32 blockNum = _safeBlockNum(block.number); Record memory _record = record; uint192 oldData = _record.numCheckpoints > 0 ? record.checkpoints[_record.numCheckpoints].data : 0; bool isChanged = data != oldData; if (_record.lastCheckpointBlock != blockNum) { _record.numCheckpoints = _record.numCheckpoints + 1; // overflow chance ignored record.numCheckpoints = _record.numCheckpoints; record.lastCheckpointBlock = blockNum; isChanged = true; } if (isChanged) { record.checkpoints[_record.numCheckpoints] = Checkpoint(blockNum, data); } id = _record.numCheckpoints; } /** * @dev Gets the given record properties (w/o mappings) */ function getProperties(Record storage record) internal view returns (uint32, uint32, address) { return (record.numCheckpoints, record.lastCheckpointBlock, record.delegatee); } /** * @dev Writes given delegatee to the given record */ function writeDelegatee(Record storage record, address delegatee) internal { record.delegatee = delegatee; } function _safeBlockNum(uint256 blockNumber) private pure returns (uint32) { require(blockNumber < 2**32, "ChPoints: blockNum >= 2**32"); return uint32(blockNumber); } function _safeMinedBlockNum(uint256 blockNumber) private view returns (uint32) { require(blockNumber < block.number, "ChPoints: block not yet mined"); return _safeBlockNum(blockNumber); } function _findCheckpoint(Record storage record, uint32 numCheckpoints, uint32 blockNum) private view returns (uint32, uint192) { Checkpoint memory cp; // Check special cases first if (numCheckpoints == 0) { return (0, 0); } cp = record.checkpoints[numCheckpoints]; if (cp.fromBlock <= blockNum) { return (numCheckpoints, cp.data); } if (record.checkpoints[1].fromBlock > blockNum) { return (0, 0); } uint32 lower = 1; uint32 upper = numCheckpoints; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow cp = record.checkpoints[center]; if (cp.fromBlock == blockNum) { return (center, cp.data); } else if (cp.fromBlock < blockNum) { lower = center; } else { upper = center - 1; } } return (lower, record.checkpoints[lower].data); } } // File: contracts/powerindex-mining/DelegatableVotes.sol pragma solidity 0.6.12; abstract contract DelegatableVotes { using SafeMath96 for uint96; using DelegatableCheckpoints for DelegatableCheckpoints.Record; /** * @notice Votes computation data for each account * @dev Data adjusted to account "delegated" votes * @dev For the contract address, stores shared for all accounts data */ mapping(address => DelegatableCheckpoints.Record) public book; /** * @dev Data on votes which an account may delegate or has already delegated */ mapping(address => uint192) internal delegatables; /// @notice The event is emitted when a delegate account' vote balance changes event CheckpointBalanceChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /// @notice An event that's emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @notice Get the "delegatee" account for the message sender */ function delegatee() public view returns (address) { return book[msg.sender].delegatee; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee_ The address to delegate votes to */ function delegate(address delegatee_) public { require(delegatee_ != address(this), "delegate: can't delegate to the contract address"); return _delegate(msg.sender, delegatee_); } /** * @notice Get 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) internal view returns (uint96) { (uint192 userData, uint32 userDataBlockNumber) = book[account].getLatestData(); if (userData == 0) return 0; (uint192 sharedData, ) = book[address(this)].getLatestData(); (uint192 sharedDataAtUserSave, ) = book[address(this)].getPriorData(userDataBlockNumber, 0); return _computeUserVotes(userData, sharedData, sharedDataAtUserSave); } /** * @notice Determine the prior number of votes for the given account as of the given block * @dev To prevent misinformation, the call reverts if the block requested is not finalized * @param account The address of the account to get votes for * @param blockNumber The block number to get votes at * @return The number of votes the account had as of the given block */ function _getPriorVotes(address account, uint256 blockNumber) internal view returns (uint96) { return _getPriorVotes(account, blockNumber, 0, 0); } /** * @notice Gas-optimized version of the `getPriorVotes` function - * it accepts IDs of checkpoints to look for votes data as of the given block in * (if the checkpoints miss the data, it get searched through all checkpoints recorded) * @dev Call (off-chain) the `findCheckpoints` function to get needed IDs * @param account The address of the account to get votes for * @param blockNumber The block number to get votes at * @param userCheckpointId ID of the checkpoint to look for the user data first * @param userCheckpointId ID of the checkpoint to look for the shared data first * @return The number of votes the account had as of the given block */ function _getPriorVotes( address account, uint256 blockNumber, uint32 userCheckpointId, uint32 sharedCheckpointId ) internal view returns (uint96) { (uint192 userData, uint32 userDataBlockNumber) = book[account].getPriorData(blockNumber, userCheckpointId); if (userData == 0) return 0; (uint192 sharedData, ) = book[address(this)].getPriorData(blockNumber, sharedCheckpointId); (uint192 sharedDataAtUserSave, ) = book[address(this)].getPriorData(userDataBlockNumber, 0); return _computeUserVotes(userData, sharedData, sharedDataAtUserSave); } /// @notice Returns IDs of checkpoints which store the given account' votes computation data /// @dev Intended for off-chain use (by UI) function findCheckpoints(address account, uint256 blockNumber) external view returns (uint32 userCheckpointId, uint32 sharedCheckpointId) { require(account != address(0), "findCheckpoints: zero account"); (userCheckpointId, ) = book[account].findCheckpoint(blockNumber); (sharedCheckpointId, ) = book[address(this)].findCheckpoint(blockNumber); } function _getCheckpoint(address account, uint32 checkpointId) internal view returns (uint32 fromBlock, uint192 data) { (fromBlock, data) = book[account].getCheckpoint(checkpointId); } function _writeSharedData(uint192 data) internal { book[address(this)].writeCheckpoint(data); } function _writeUserData(address account, uint192 data) internal { DelegatableCheckpoints.Record storage src = book[account]; address _delegatee = src.delegatee; DelegatableCheckpoints.Record storage dst = _delegatee == address(0) ? src : book[_delegatee]; (uint192 latestData, ) = dst.getLatestData(); dst.writeCheckpoint( // keep in mind votes which others could have delegated _computeUserData(latestData, data, delegatables[account]) ); delegatables[account] = data; } function _moveUserData( address account, address from, address to ) internal { DelegatableCheckpoints.Record storage src; DelegatableCheckpoints.Record storage dst; if (from == address(0)) { // no former delegatee src = book[account]; dst = book[to]; } else if (to == address(0)) { // delegation revoked src = book[from]; dst = book[account]; } else { src = book[from]; dst = book[to]; } uint192 delegatable = delegatables[account]; (uint192 srcPrevData, ) = src.getLatestData(); uint192 srcData = _computeUserData(srcPrevData, 0, delegatable); if (srcPrevData != srcData) src.writeCheckpoint(srcData); (uint192 dstPrevData, ) = dst.getLatestData(); uint192 dstData = _computeUserData(dstPrevData, delegatable, 0); if (dstPrevData != dstData) dst.writeCheckpoint(dstData); } function _delegate(address delegator, address delegatee_) internal { address currentDelegate = book[delegator].delegatee; book[delegator].delegatee = delegatee_; emit DelegateChanged(delegator, currentDelegate, delegatee_); _moveUserData(delegator, currentDelegate, delegatee_); } function _computeUserVotes( uint192 userData, uint192 sharedData, uint192 sharedDataAtUserSave ) internal pure virtual returns (uint96 votes); function _computeUserData( uint192 prevData, uint192 newDelegated, uint192 prevDelegated ) internal pure virtual returns (uint192 userData) { (uint96 prevA, uint96 prevB) = _unpackData(prevData); (uint96 newDelegatedA, uint96 newDelegatedB) = _unpackData(newDelegated); (uint96 prevDelegatedA, uint96 prevDelegatedB) = _unpackData(prevDelegated); userData = _packData( _getNewValue(prevA, newDelegatedA, prevDelegatedA), _getNewValue(prevB, newDelegatedB, prevDelegatedB) ); } function _unpackData(uint192 data) internal pure virtual returns (uint96 valA, uint96 valB) { return (uint96(data >> 96), uint96((data << 96) >> 96)); } function _packData(uint96 valA, uint96 valB) internal pure virtual returns (uint192 data) { return ((uint192(valA) << 96) | uint192(valB)); } function _getNewValue( uint96 val, uint96 more, uint96 less ) internal pure virtual returns (uint96 newVal) { if (more == less) { newVal = val; } else if (more > less) { newVal = val.add(more.sub(less)); } else { uint96 decrease = less.sub(more); newVal = val > decrease ? val.sub(decrease) : 0; } } uint256[50] private _gap; // reserved } // File: contracts/powerindex-mining/VestedLPMining.sol pragma solidity 0.6.12; contract VestedLPMining is OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe, ReservedSlots, DelegatableVotes, IVestedLPMining { using SafeMath for uint256; using SafeMath96 for uint96; using SafeMath32 for uint32; using SafeERC20 for IERC20; /// @dev properties grouped to optimize storage costs struct User { uint32 lastUpdateBlock; // block when the params (below) were updated uint32 vestingBlock; // block by when all entitled CVP tokens to be vested uint96 pendedCvp; // amount of CVPs tokens entitled but not yet vested to the user uint96 cvpAdjust; // adjustments for pended CVP tokens amount computation // (with regard to LP token deposits/withdrawals in the past) uint256 lptAmount; // amount of LP tokens the user has provided to a pool /** @dev * At any time, the amount of CVP tokens entitled to a user but not yet vested is the sum of: * (1) CVP token amount entitled after the user last time deposited or withdrawn LP tokens * = (user.lptAmount * pool.accCvpPerLpt) - user.cvpAdjust * (2) CVP token amount entitled before the last deposit or withdrawal but not yet vested * = user.pendedCvp * * Whenever a user deposits or withdraws LP tokens to a pool: * 1. `pool.accCvpPerLpt` for the pool gets updated; * 2. CVP token amounts to be entitled and vested to the user get computed; * 3. Token amount which may be vested get sent to the user; * 3. User' `lptAmount`, `cvpAdjust` and `pendedCvp` get updated. * * Note comments on vesting rules in the `function _computeCvpVesting` code bellow. */ } struct Pool { IERC20 lpToken; // address of the LP token contract bool votesEnabled; // if the pool is enabled to write votes uint8 poolType; // pool type (1 - Uniswap, 2 - Balancer) uint32 allocPoint; // points assigned to the pool, which affect CVPs distribution between pools uint32 lastUpdateBlock; // latest block when the pool params which follow was updated uint256 accCvpPerLpt; // accumulated distributed CVPs per one deposited LP token, times 1e12 } // scale factor for `accCvpPerLpt` uint256 internal constant SCALE = 1e12; // The CVP TOKEN IERC20 public cvp; // Total amount of CVP tokens pended (not yet vested to users) uint96 public cvpVestingPool; // Reservoir address address public reservoir; // Vesting duration in blocks uint32 public cvpVestingPeriodInBlocks; // The block number when CVP powerindex-mining starts uint32 public startBlock; // The amount of CVP tokens rewarded to all pools every block uint96 public cvpPerBlock; // The migrator contract (only the owner may assign it) ILpTokenMigrator public migrator; // Params of each pool Pool[] public pools; // Pid (i.e. the index in `pools`) of each pool by its LP token address mapping(address => uint256) public poolPidByAddress; // Params of each user that stakes LP tokens, by the Pid and the user address mapping(uint256 => mapping(address => User)) public users; // Sum of allocation points for all pools uint256 public totalAllocPoint = 0; mapping(address => address) public cvpPoolByMetaPool; mapping(address => uint256) public lastSwapBlock; struct PoolBoost { uint256 lpBoostRate; uint256 cvpBoostRate; uint32 lastUpdateBlock; uint256 accCvpPerLpBoost; uint256 accCvpPerCvpBoost; } struct UserPoolBoost { uint256 balance; uint32 lastUpdateBlock; } mapping(uint256 => PoolBoost) public poolBoostByLp; mapping(uint256 => mapping(address => UserPoolBoost)) public usersPoolBoost; mapping(address => uint256) public lpBoostRatioByToken; mapping(address => uint256) public lpBoostMaxRatioByToken; mapping(address => bool) public votingEnabled; mapping(address => uint256) public boostBalanceByLp; /// @inheritdoc IVestedLPMining function initialize( IERC20 _cvp, address _reservoir, uint256 _cvpPerBlock, uint256 _startBlock, uint256 _cvpVestingPeriodInBlocks ) external override initializer { __Ownable_init(); __ReentrancyGuard_init_unchained(); cvp = _cvp; reservoir = _reservoir; startBlock = SafeMath32.fromUint(_startBlock, "VLPMining: too big startBlock"); cvpVestingPeriodInBlocks = SafeMath32.fromUint(_cvpVestingPeriodInBlocks, "VLPMining: too big vest period"); setCvpPerBlock(_cvpPerBlock); } /// @inheritdoc IVestedLPMining function poolLength() external view override returns (uint256) { return pools.length; } /// @inheritdoc IVestedLPMining function add( uint256 _allocPoint, IERC20 _lpToken, uint8 _poolType, bool _votesEnabled, uint256 _lpBoostRate, uint256 _cvpBoostRate, uint256 _lpBoostMinRatio, uint256 _lpBoostMaxRatio ) public override onlyOwner { require(!isLpTokenAdded(_lpToken), "VLPMining: token already added"); massUpdatePools(); uint32 blockNum = _currBlock(); uint32 lastUpdateBlock = blockNum > startBlock ? blockNum : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); uint256 pid = pools.length; pools.push( Pool({ lpToken: _lpToken, votesEnabled: _votesEnabled, poolType: _poolType, allocPoint: SafeMath32.fromUint(_allocPoint, "VLPMining: too big allocation"), lastUpdateBlock: lastUpdateBlock, accCvpPerLpt: 0 }) ); poolPidByAddress[address(_lpToken)] = pid; poolBoostByLp[pid].lpBoostRate = _lpBoostRate; poolBoostByLp[pid].cvpBoostRate = _cvpBoostRate; poolBoostByLp[pid].lastUpdateBlock = lastUpdateBlock; lpBoostRatioByToken[address(_lpToken)] = _lpBoostMinRatio; lpBoostMaxRatioByToken[address(_lpToken)] = _lpBoostMaxRatio; emit AddLpToken(address(_lpToken), pid, _allocPoint); } /// @inheritdoc IVestedLPMining function set( uint256 _pid, uint256 _allocPoint, uint8 _poolType, bool _votesEnabled, uint256 _lpBoostRate, uint256 _cvpBoostRate, uint256 _lpBoostMinRatio, uint256 _lpBoostMaxRatio ) public override onlyOwner { massUpdatePools(); totalAllocPoint = totalAllocPoint.sub(uint256(pools[_pid].allocPoint)).add(_allocPoint); pools[_pid].allocPoint = SafeMath32.fromUint(_allocPoint, "VLPMining: too big allocation"); pools[_pid].votesEnabled = _votesEnabled; pools[_pid].poolType = _poolType; poolBoostByLp[_pid].lpBoostRate = _lpBoostRate; poolBoostByLp[_pid].cvpBoostRate = _cvpBoostRate; lpBoostRatioByToken[address(pools[_pid].lpToken)] = _lpBoostMinRatio; lpBoostMaxRatioByToken[address(pools[_pid].lpToken)] = _lpBoostMaxRatio; emit SetLpToken(address(pools[_pid].lpToken), _pid, _allocPoint); } /// @inheritdoc IVestedLPMining function setMigrator(ILpTokenMigrator _migrator) public override onlyOwner { migrator = _migrator; emit SetMigrator(address(_migrator)); } /// @inheritdoc IVestedLPMining function setCvpPerBlock(uint256 _cvpPerBlock) public override onlyOwner { cvpPerBlock = SafeMath96.fromUint(_cvpPerBlock, "VLPMining: too big cvpPerBlock"); emit SetCvpPerBlock(_cvpPerBlock); } /// @inheritdoc IVestedLPMining function setCvpVestingPeriodInBlocks(uint256 _cvpVestingPeriodInBlocks) public override onlyOwner { cvpVestingPeriodInBlocks = SafeMath32.fromUint( _cvpVestingPeriodInBlocks, "VLPMining: too big cvpVestingPeriodInBlocks" ); emit SetCvpVestingPeriodInBlocks(_cvpVestingPeriodInBlocks); } /// @inheritdoc IVestedLPMining function setCvpPoolByMetaPool(address _metaPool, address _cvpPool) public override onlyOwner { cvpPoolByMetaPool[_metaPool] = _cvpPool; emit SetCvpPoolByMetaPool(_metaPool, _cvpPool); } function updateBoostBalance() public onlyOwner { uint256 boostPoolId = 10; Pool memory _pool = pools[boostPoolId]; require(boostBalanceByLp[address(_pool.lpToken)] == 0, "ALREADY_UPDATED"); boostBalanceByLp[address(_pool.lpToken)] = cvp.balanceOf(address(this)); } /// @inheritdoc IVestedLPMining function pendingCvp(uint256 _pid, address _user) external view override returns (uint256) { if (_pid >= pools.length) return 0; Pool memory _pool = pools[_pid]; PoolBoost memory _poolBoost = poolBoostByLp[_pid]; User memory user = users[_pid][_user]; UserPoolBoost memory userPB = usersPoolBoost[_pid][_user]; _computePoolReward(_pool); _computePoolBoostReward(_poolBoost, _pool.lpToken); _pool.lastUpdateBlock = pools[_pid].lastUpdateBlock; _computePoolRewardByBoost(_pool, _poolBoost); uint96 newlyEntitled = _computeCvpToEntitle(user, _pool, userPB, _poolBoost); return uint256(newlyEntitled.add(user.pendedCvp)); } /// @inheritdoc IVestedLPMining function vestableCvp(uint256 _pid, address user) external view override returns (uint256) { Pool memory _pool = pools[_pid]; PoolBoost memory _poolBoost = poolBoostByLp[_pid]; User memory _user = users[_pid][user]; UserPoolBoost memory _userPB = usersPoolBoost[_pid][user]; _computePoolReward(_pool); _computePoolBoostReward(_poolBoost, _pool.lpToken); _pool.lastUpdateBlock = pools[_pid].lastUpdateBlock; _computePoolRewardByBoost(_pool, _poolBoost); (, uint256 newlyVested) = _computeCvpVesting(_user, _pool, _userPB, _poolBoost); return newlyVested; } /// @inheritdoc IVestedLPMining function isLpTokenAdded(IERC20 _lpToken) public view override returns (bool) { uint256 pid = poolPidByAddress[address(_lpToken)]; return pools.length > pid && address(pools[pid].lpToken) == address(_lpToken); } /// @inheritdoc IVestedLPMining function massUpdatePools() public override { uint256 length = pools.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } /// @inheritdoc IVestedLPMining function updatePool(uint256 _pid) public override nonReentrant { _doPoolUpdate(pools[_pid], poolBoostByLp[_pid]); } /// @inheritdoc IVestedLPMining function deposit( uint256 _pid, uint256 _amount, uint256 _boostAmount ) public override nonReentrant { _validatePoolId(_pid); _preventSameTxOriginAndMsgSender(); Pool storage pool = pools[_pid]; PoolBoost storage poolBoost = poolBoostByLp[_pid]; User storage user = users[_pid][msg.sender]; UserPoolBoost storage userPB = usersPoolBoost[_pid][msg.sender]; _doPoolUpdate(pool, poolBoost); _vestUserCvp(user, pool, userPB, poolBoost); if (_amount != 0) { pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); user.lptAmount = user.lptAmount.add(_amount); } if (_boostAmount != 0) { cvp.safeTransferFrom(msg.sender, address(this), _boostAmount); userPB.balance = userPB.balance.add(_boostAmount); boostBalanceByLp[address(pool.lpToken)] = boostBalanceByLp[address(pool.lpToken)].add(_boostAmount); } if (userPB.balance != 0) { require(!cvpAmountNotInBoundsToBoost(userPB.balance, user.lptAmount, address(pool.lpToken)), "BOOST_BOUNDS"); } user.cvpAdjust = _computeCvpAdjustmentWithBoost(user.lptAmount, pool, userPB, poolBoost); emit Deposit(msg.sender, _pid, _amount, _boostAmount); if (votingEnabled[msg.sender]) { _doCheckpointVotes(msg.sender); } } /// @inheritdoc IVestedLPMining function withdraw( uint256 _pid, uint256 _amount, uint256 _boostAmount ) public override nonReentrant { _validatePoolId(_pid); _preventSameTxOriginAndMsgSender(); Pool storage pool = pools[_pid]; PoolBoost storage poolBoost = poolBoostByLp[_pid]; User storage user = users[_pid][msg.sender]; UserPoolBoost storage userPB = usersPoolBoost[_pid][msg.sender]; require(user.lptAmount >= _amount, "VLPMining: amount exceeds balance"); _doPoolUpdate(pool, poolBoost); _vestUserCvp(user, pool, userPB, poolBoost); if (_amount != 0) { user.lptAmount = user.lptAmount.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); } if (_boostAmount != 0) { userPB.balance = userPB.balance.sub(_boostAmount); cvp.safeTransfer(msg.sender, _boostAmount); boostBalanceByLp[address(pool.lpToken)] = boostBalanceByLp[address(pool.lpToken)].sub(_boostAmount); } if (userPB.balance != 0) { require(!cvpAmountNotInBoundsToBoost(userPB.balance, user.lptAmount, address(pool.lpToken)), "BOOST_BOUNDS"); } user.cvpAdjust = _computeCvpAdjustmentWithBoost(user.lptAmount, pool, userPB, poolBoost); emit Withdraw(msg.sender, _pid, _amount, _boostAmount); if (votingEnabled[msg.sender]) { _doCheckpointVotes(msg.sender); } } /// @inheritdoc IVestedLPMining function emergencyWithdraw(uint256 _pid) public override nonReentrant { _validatePoolId(_pid); _preventSameTxOriginAndMsgSender(); Pool storage pool = pools[_pid]; User storage user = users[_pid][msg.sender]; UserPoolBoost storage userPB = usersPoolBoost[_pid][msg.sender]; pool.lpToken.safeTransfer(msg.sender, user.lptAmount); if (userPB.balance != 0) { cvp.safeTransfer(msg.sender, userPB.balance); } emit EmergencyWithdraw(msg.sender, _pid, user.lptAmount, userPB.balance); if (user.pendedCvp > 0) { // TODO: Make user.pendedCvp be updated as of the pool' lastUpdateBlock cvpVestingPool = user.pendedCvp > cvpVestingPool ? 0 : cvpVestingPool.sub(user.pendedCvp); } user.lptAmount = 0; user.cvpAdjust = 0; user.pendedCvp = 0; user.vestingBlock = 0; userPB.balance = 0; if (votingEnabled[msg.sender]) { _doCheckpointVotes(msg.sender); } } function setVotingEnabled(bool _isEnabled) public nonReentrant { votingEnabled[msg.sender] = _isEnabled; if (_isEnabled) { _doCheckpointVotes(msg.sender); } } /// @inheritdoc IVestedLPMining function checkpointVotes(address _user) public override nonReentrant { _doCheckpointVotes(_user); } function getCurrentVotes(address account) external view returns (uint96) { if (!votingEnabled[account]) { return 0; } return _getCurrentVotes(account); } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) { if (!votingEnabled[account]) { return 0; } return _getPriorVotes(account, blockNumber); } function getPriorVotes( address account, uint256 blockNumber, uint32 userCheckpointId, uint32 sharedCheckpointId ) external view returns (uint96) { if (!votingEnabled[account]) { return 0; } return _getPriorVotes(account, blockNumber, userCheckpointId, sharedCheckpointId); } /// @inheritdoc IVestedLPMining function getCheckpoint(address account, uint32 checkpointId) external view override returns ( uint32 fromBlock, uint96 cvpAmount, uint96 pooledCvpShare ) { uint192 data; (fromBlock, data) = _getCheckpoint(account, checkpointId); (cvpAmount, pooledCvpShare) = _unpackData(data); } function _doCheckpointVotes(address _user) internal { uint256 length = pools.length; uint96 userPendedCvp = 0; uint256 userTotalLpCvp = 0; uint96 totalLpCvp = 0; for (uint256 pid = 0; pid < length; ++pid) { userPendedCvp = userPendedCvp.add(users[pid][_user].pendedCvp); Pool storage pool = pools[pid]; uint96 lpCvp; address lpToken = address(pool.lpToken); address cvpPoolByMeta = cvpPoolByMetaPool[lpToken]; if (cvpPoolByMeta == address(0)) { lpCvp = SafeMath96.fromUint(cvp.balanceOf(lpToken), "VLPMining::_doCheckpointVotes:1"); totalLpCvp = totalLpCvp.add(lpCvp); } else { uint256 poolTotalSupply = IERC20(cvpPoolByMeta).totalSupply(); uint256 poolBalance = IERC20(cvpPoolByMeta).balanceOf(lpToken); uint256 lpShare = uint256(poolBalance).mul(SCALE).div(poolTotalSupply); uint256 metaPoolCvp = cvp.balanceOf(cvpPoolByMeta); lpCvp = SafeMath96.fromUint(metaPoolCvp.mul(lpShare).div(SCALE), "VLPMining::_doCheckpointVotes:1"); } if (!pool.votesEnabled) { continue; } uint256 lptTotalSupply = pool.lpToken.totalSupply(); uint256 lptAmount = users[pid][_user].lptAmount; if (lptAmount != 0 && lptTotalSupply != 0) { uint256 cvpPerLpt = uint256(lpCvp).mul(SCALE).div(lptTotalSupply); uint256 userLpCvp = lptAmount.mul(cvpPerLpt).div(SCALE); userTotalLpCvp = userTotalLpCvp.add(userLpCvp); emit CheckpointUserLpVotes(_user, pid, userLpCvp); } } uint96 lpCvpUserShare = (userTotalLpCvp == 0 || totalLpCvp == 0) ? 0 : SafeMath96.fromUint(userTotalLpCvp.mul(SCALE).div(totalLpCvp), "VLPMining::_doCheckpointVotes:2"); emit CheckpointTotalLpVotes(totalLpCvp); emit CheckpointUserVotes(_user, uint256(userPendedCvp), lpCvpUserShare); _writeUserData(_user, _packData(userPendedCvp, lpCvpUserShare)); _writeSharedData(_packData(totalLpCvp, 0)); } function _transferCvp(address _to, uint256 _amount) internal { SafeERC20.safeTransferFrom(cvp, reservoir, _to, _amount); } /// @dev must be guarded for reentrancy function _doPoolUpdate(Pool storage pool, PoolBoost storage poolBoost) internal { Pool memory _pool = pool; uint32 prevBlock = _pool.lastUpdateBlock; uint256 prevAcc = _pool.accCvpPerLpt; uint256 cvpReward = _computePoolReward(_pool); if (poolBoost.lpBoostRate != 0) { PoolBoost memory _poolBoost = poolBoost; uint32 prevBoostBlock = poolBoost.lastUpdateBlock; uint256 prevCvpBoostAcc = poolBoost.accCvpPerCvpBoost; uint256 prevLpBoostAcc = poolBoost.accCvpPerLpBoost; cvpReward = cvpReward.add(_computePoolBoostReward(_poolBoost, _pool.lpToken)); _pool.lastUpdateBlock = prevBlock; cvpReward = cvpReward.add(_computePoolRewardByBoost(_pool, _poolBoost)); if (_poolBoost.accCvpPerCvpBoost > prevCvpBoostAcc) { poolBoost.accCvpPerCvpBoost = _poolBoost.accCvpPerCvpBoost; } if (_poolBoost.accCvpPerLpBoost > prevLpBoostAcc) { poolBoost.accCvpPerLpBoost = _poolBoost.accCvpPerLpBoost; } if (_poolBoost.lastUpdateBlock > prevBoostBlock) { poolBoost.lastUpdateBlock = _poolBoost.lastUpdateBlock; } } if (_pool.accCvpPerLpt > prevAcc) { pool.accCvpPerLpt = _pool.accCvpPerLpt; } if (_pool.lastUpdateBlock > prevBlock) { pool.lastUpdateBlock = _pool.lastUpdateBlock; } if (cvpReward != 0) { cvpVestingPool = cvpVestingPool.add( SafeMath96.fromUint(cvpReward, "VLPMining::_doPoolUpdate:1"), "VLPMining::_doPoolUpdate:2" ); } } function _vestUserCvp( User storage user, Pool storage pool, UserPoolBoost storage userPB, PoolBoost storage poolBoost ) internal { User memory _user = user; UserPoolBoost memory _userPB = userPB; uint32 prevVestingBlock = _user.vestingBlock; uint32 prevUpdateBlock = _user.lastUpdateBlock; (uint256 newlyEntitled, uint256 newlyVested) = _computeCvpVesting(_user, pool, _userPB, poolBoost); if (newlyEntitled != 0 || newlyVested != 0) { user.pendedCvp = _user.pendedCvp; } if (newlyVested != 0) { if (newlyVested > cvpVestingPool) newlyVested = uint256(cvpVestingPool); cvpVestingPool = cvpVestingPool.sub( SafeMath96.fromUint(newlyVested, "VLPMining::_vestUserCvp:1"), "VLPMining::_vestUserCvp:2" ); _transferCvp(msg.sender, newlyVested); } if (_user.vestingBlock > prevVestingBlock) { user.vestingBlock = _user.vestingBlock; } if (_user.lastUpdateBlock > prevUpdateBlock) { user.lastUpdateBlock = _user.lastUpdateBlock; } } /* @dev Compute the amount of CVP tokens to be entitled and vested to a user of a pool * ... and update the `_user` instance (in the memory): * `_user.pendedCvp` gets increased by `newlyEntitled - newlyVested` * `_user.vestingBlock` set to the updated value * `_user.lastUpdateBlock` set to the current block * * @param _user - user to compute tokens for * @param accCvpPerLpt - value of the pool' `pool.accCvpPerLpt` * @return newlyEntitled - CVP amount to entitle (on top of tokens entitled so far) * @return newlyVested - CVP amount to vest (on top of tokens already vested) */ function _computeCvpVesting( User memory _user, Pool memory pool, UserPoolBoost memory _userPB, PoolBoost memory _poolBoost ) internal view returns (uint256 newlyEntitled, uint256 newlyVested) { uint32 prevBlock = _user.lastUpdateBlock; _user.lastUpdateBlock = _currBlock(); if (prevBlock >= _user.lastUpdateBlock) { return (0, 0); } uint32 age = _user.lastUpdateBlock - prevBlock; // Tokens which are to be entitled starting from the `user.lastUpdateBlock`, shall be // vested proportionally to the number of blocks already minted within the period between // the `user.lastUpdateBlock` and `cvpVestingPeriodInBlocks` following the current block newlyEntitled = uint256(_computeCvpToEntitle(_user, pool, _userPB, _poolBoost)); uint256 newToVest = newlyEntitled == 0 ? 0 : (newlyEntitled.mul(uint256(age)).div(uint256(age + cvpVestingPeriodInBlocks))); // Tokens which have been pended since the `user.lastUpdateBlock` shall be vested: // - in full, if the `user.vestingBlock` has been mined // - otherwise, proportionally to the number of blocks already mined so far in the period // between the `user.lastUpdateBlock` and the `user.vestingBlock` (not yet mined) uint256 pended = uint256(_user.pendedCvp); age = _user.lastUpdateBlock >= _user.vestingBlock ? cvpVestingPeriodInBlocks : _user.lastUpdateBlock - prevBlock; uint256 pendedToVest = pended == 0 ? 0 : ( age >= cvpVestingPeriodInBlocks ? pended : pended.mul(uint256(age)).div(uint256(_user.vestingBlock - prevBlock)) ); newlyVested = pendedToVest.add(newToVest); _user.pendedCvp = SafeMath96.fromUint( uint256(_user.pendedCvp).add(newlyEntitled).sub(newlyVested), "VLPMining::computeCvpVest:1" ); // Amount of CVP token pended (i.e. not yet vested) from now uint256 remainingPended = pended == 0 ? 0 : pended.sub(pendedToVest); uint256 unreleasedNewly = newlyEntitled == 0 ? 0 : newlyEntitled.sub(newToVest); uint256 pending = remainingPended.add(unreleasedNewly); // Compute the vesting block (i.e. when the pended tokens to be all vested) uint256 period = 0; if (remainingPended == 0 || pending == 0) { // newly entitled CVPs only or nothing remain pended period = cvpVestingPeriodInBlocks; } else { // "old" CVPs and, perhaps, "new" CVPs are pending - the weighted average applied age = _user.vestingBlock - _user.lastUpdateBlock; period = ((remainingPended.mul(age)).add(unreleasedNewly.mul(cvpVestingPeriodInBlocks))).div(pending); } _user.vestingBlock = _user.lastUpdateBlock + (cvpVestingPeriodInBlocks > uint32(period) ? uint32(period) : cvpVestingPeriodInBlocks); return (newlyEntitled, newlyVested); } function _computePoolReward(Pool memory _pool) internal view returns (uint256 poolCvpReward) { (poolCvpReward, _pool.accCvpPerLpt, _pool.lastUpdateBlock) = _computeReward( _pool.lastUpdateBlock, _pool.accCvpPerLpt, _pool.lpToken, _pool.lpToken, SCALE.mul(uint256(cvpPerBlock)).mul(uint256(_pool.allocPoint)).div(totalAllocPoint) ); } function _computePoolRewardByBoost(Pool memory _pool, PoolBoost memory _poolBoost) internal view returns (uint256 poolCvpReward) { (poolCvpReward, _poolBoost.accCvpPerLpBoost, _pool.lastUpdateBlock) = _computeReward( _pool.lastUpdateBlock, _poolBoost.accCvpPerLpBoost, _pool.lpToken, _pool.lpToken, _poolBoost.lpBoostRate ); } function _computePoolBoostReward(PoolBoost memory _poolBoost, IERC20 _lpToken) internal view returns (uint256 poolCvpReward) { (poolCvpReward, _poolBoost.accCvpPerCvpBoost, _poolBoost.lastUpdateBlock) = _computeReward( _poolBoost.lastUpdateBlock, _poolBoost.accCvpPerCvpBoost, cvp, _lpToken, _poolBoost.cvpBoostRate ); } function _computeReward( uint256 _lastUpdateBlock, uint256 _accumulated, IERC20 _token, IERC20 _lpToken, uint256 _cvpPoolRate ) internal view returns ( uint256 poolCvpReward, uint256 newAccumulated, uint32 newLastUpdateBlock ) { newAccumulated = _accumulated; newLastUpdateBlock = _currBlock(); if (newLastUpdateBlock > _lastUpdateBlock) { uint256 multiplier = uint256(newLastUpdateBlock - _lastUpdateBlock); // can't overflow uint256 tokenBalance; if (address(_token) == address(cvp)) { tokenBalance = boostBalanceByLp[address(_lpToken)]; } else { tokenBalance = _token.balanceOf(address(this)); } if (tokenBalance != 0) { poolCvpReward = multiplier.mul(_cvpPoolRate).div(SCALE); newAccumulated = newAccumulated.add(poolCvpReward.mul(SCALE).div(tokenBalance)); } } } function _computeUserVotes( uint192 userData, uint192 sharedData, uint192 sharedDataAtUserSave ) internal pure override returns (uint96 votes) { (uint96 ownCvp, uint96 pooledCvpShare) = _unpackData(userData); (uint96 currentTotalPooledCvp, ) = _unpackData(sharedData); (uint96 totalPooledCvpAtUserSave, ) = _unpackData(sharedDataAtUserSave); if (pooledCvpShare == 0) { votes = ownCvp; } else { uint256 pooledCvp = uint256(pooledCvpShare).mul(currentTotalPooledCvp).div(SCALE); if (currentTotalPooledCvp != totalPooledCvpAtUserSave) { uint256 totalCvpDiffRatio = uint256(currentTotalPooledCvp).mul(SCALE).div(uint256(totalPooledCvpAtUserSave)); if (totalCvpDiffRatio > SCALE) { pooledCvp = pooledCvp.mul(SCALE).div(totalCvpDiffRatio); } } votes = ownCvp.add(SafeMath96.fromUint(pooledCvp, "VLPMining::_computeVotes")); } } function _computeCvpToEntitle( User memory user, Pool memory pool, UserPoolBoost memory userPB, PoolBoost memory poolBoost ) private view returns (uint96 cvpResult) { if (user.lptAmount == 0) { return 0; } return _computeCvpAdjustmentWithBoost(user.lptAmount, pool, userPB, poolBoost).sub( user.cvpAdjust, "VLPMining::computeCvp:2" ); } function _computeCvpAdjustmentWithBoost( uint256 lptAmount, Pool memory pool, UserPoolBoost memory userPB, PoolBoost memory poolBoost ) private view returns (uint96 cvpResult) { cvpResult = _computeCvpAdjustment(lptAmount, pool.accCvpPerLpt); if (poolBoost.cvpBoostRate == 0 || poolBoost.lpBoostRate == 0 || userPB.balance == 0) { return cvpResult; } return cvpResult.add(_computeCvpAdjustment(userPB.balance, poolBoost.accCvpPerCvpBoost)).add( _computeCvpAdjustment(lptAmount, poolBoost.accCvpPerLpBoost) ); } function _computeCvpAdjustment(uint256 lptAmount, uint256 accCvpPerLpt) private pure returns (uint96) { return SafeMath96.fromUint(lptAmount.mul(accCvpPerLpt).div(SCALE), "VLPMining::_computeCvpAdj"); } function cvpAmountNotInBoundsToBoost( uint256 _cvpAmount, uint256 _lpAmount, address _lpToken ) public view returns (bool) { return _cvpAmount < cvpBalanceToBoost(_lpAmount, _lpToken, true) || _cvpAmount > cvpBalanceToBoost(_lpAmount, _lpToken, false); } function cvpBalanceToBoost( uint256 _lpAmount, address _lpToken, bool _min ) public view returns (uint256) { return _lpAmount.mul(_min ? lpBoostRatioByToken[_lpToken] : lpBoostMaxRatioByToken[_lpToken]).div(SCALE); } function _validatePoolId(uint256 pid) private view { require(pid < pools.length, "VLPMining: invalid pool id"); } function _currBlock() private view returns (uint32) { return SafeMath32.fromUint(block.number, "VLPMining::_currBlock:overflow"); } function _preventSameTxOriginAndMsgSender() internal { require(block.number > lastSwapBlock[tx.origin], "SAME_TX_ORIGIN"); lastSwapBlock[tx.origin] = block.number; if (msg.sender != tx.origin) { require(block.number > lastSwapBlock[msg.sender], "SAME_MSG_SENDER"); lastSwapBlock[msg.sender] = block.number; } } }
Perform LP token migration from legacy UniswapV2 to PowerSwap. 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 UniswapV2 LP tokens. PowerSwap must mint EXACTLY the same amount of PowerSwap LP tokens or else something bad will happen. Traditional UniswapV2 does not do that so be careful!
interface ILpTokenMigrator { function migrate(IERC20 token, uint8 poolType) external returns (IERC20); }
2,399,237
pragma solidity ^0.7.5; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity 0.7.6; import "@openzeppelin/contracts/proxy/TransparentUpgradeableProxy.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "./vaults/StakingData.sol"; contract ITrustVaultFactory is Initializable { address[] internal _VaultProxies; mapping (address => bool) internal _AdminList; mapping (address => bool) internal _TrustedSigners; mapping(address => bool) internal _VaultStatus; address internal _roundDataImplementationAddress; address internal _stakeDataImplementationAddress; address internal _stakingDataAddress; address internal _burnAddress; address internal _governanceDistributionAddress; address internal _governanceTokenAddress; address internal _stakingCalculationAddress; function initialize( address admin, address trustedSigner, address roundDataImplementationAddress, address stakeDataImplementationAddress, address governanceTokenAddress, address stakingCalculationAddress ) initializer external { require(admin != address(0)); _AdminList[admin] = true; _AdminList[msg.sender] = true; _TrustedSigners[trustedSigner] = true; _roundDataImplementationAddress = roundDataImplementationAddress; _stakeDataImplementationAddress = stakeDataImplementationAddress; _governanceTokenAddress = governanceTokenAddress; _stakingCalculationAddress = stakingCalculationAddress; } modifier onlyAdmin() { require(_AdminList[msg.sender] == true, "Not Factory Admin"); _; } function createVault( address contractAddress, bytes memory data ) external onlyAdmin { TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(contractAddress, msg.sender, data ); require(address(proxy) != address(0)); _VaultProxies.push(address(proxy)); _VaultStatus[address(proxy)] = true; StakingData stakingDataContract = StakingData(_stakingDataAddress); stakingDataContract.addVault(address(proxy)); } function getVaultaddresses() external view returns (address[] memory vaults, bool[] memory status) { vaults = _VaultProxies; status = new bool[](vaults.length); for(uint i = 0; i < vaults.length; i++){ status[i] = _VaultStatus[vaults[i]]; } return (vaults, status); } function pauseVault(address vaultAddress) external onlyAdmin { _VaultStatus[vaultAddress] = false; } function unPauseVault(address vaultAddress) external onlyAdmin { _VaultStatus[vaultAddress] = true; } function addAdminAddress(address newAddress) external onlyAdmin { require(_AdminList[newAddress] == false, "Already Admin"); _AdminList[newAddress] = true; } /** * @dev revoke admin */ function revokeAdminAddress(address newAddress) external onlyAdmin { require(msg.sender != newAddress); _AdminList[newAddress] = false; } function addTrustedSigner(address newAddress) external onlyAdmin{ require(_TrustedSigners[newAddress] == false); _TrustedSigners[newAddress] = true; } function isTrustedSignerAddress(address account) external view returns (bool) { return _TrustedSigners[account] == true; } function updateRoundDataImplementationAddress(address newAddress) external onlyAdmin { _roundDataImplementationAddress = newAddress; } function getRoundDataImplementationAddress() external view returns(address){ return _roundDataImplementationAddress; } function updateStakeDataImplementationAddress(address newAddress) external onlyAdmin { _stakeDataImplementationAddress = newAddress; } function getStakeDataImplementationAddress() external view returns(address){ return _stakeDataImplementationAddress; } function updateStakingDataAddress(address newAddress) external onlyAdmin { _stakingDataAddress = newAddress; } function getStakingDataAddress() external view returns(address){ return _stakingDataAddress; } function isStakingDataAddress(address addressToCheck) external view returns (bool) { return _stakingDataAddress == addressToCheck; } function updateBurnAddress(address newAddress) external onlyAdmin { _burnAddress = newAddress; } function getBurnAddress() external view returns(address){ return _burnAddress; } function isBurnAddress(address addressToCheck) external view returns (bool) { return _burnAddress == addressToCheck; } function updateGovernanceDistributionAddress(address newAddress) external onlyAdmin { _governanceDistributionAddress = newAddress; } function getGovernanceDistributionAddress() external view returns(address){ return _governanceDistributionAddress; } function updateGovernanceTokenAddress(address newAddress) external onlyAdmin { _governanceTokenAddress = newAddress; } function getGovernanceTokenAddress() external view returns(address){ return _governanceTokenAddress; } function updateStakingCalculationsAddress(address newAddress) external onlyAdmin { _stakingCalculationAddress = newAddress; } function getStakingCalculationsAddress() external view returns(address){ return _stakingCalculationAddress; } /** * @dev revoke admin */ function revokeTrustedSigner(address newAddress) external onlyAdmin { require(msg.sender != newAddress); _TrustedSigners[newAddress] = false; } function isAdmin() external view returns (bool) { return isAddressAdmin(msg.sender); } function isAddressAdmin(address account) public view returns (bool) { return _AdminList[account] == true; } function isActiveVault(address vaultAddress) external view returns (bool) { return _VaultStatus[vaultAddress] == true; } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/math/SafeMath.sol"; library ITrustVaultLib { using SafeMath for uint; struct RewardTokenRoundData{ address tokenAddress; uint amount; uint commissionAmount; uint tokenPerBlock; uint totalSupply; bool ignoreUnstakes; } struct RewardTokenRound{ mapping(address => RewardTokenRoundData) roundData; uint startBlock; uint endBlock; } struct AccountStaking { uint32 startRound; uint endDate; uint total; Staking[] stakes; } struct Staking { uint startTime; uint startBlock; uint amount; uint total; } struct UnStaking { address account; uint amount; uint startDateTime; uint startBlock; uint endBlock; } struct ClaimedReward { uint amount; uint lastClaimedRound; } function divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) { return numerator*(uint(10)**uint(precision))/denominator; } function getUnstakingsForBlockRange( UnStaking[] memory unStakes, uint startBlock, uint endBlock) internal pure returns (uint){ // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || unStakes.length == 0 || unStakes[0].startBlock > endBlock) { return 0; } uint lastIndex = unStakes.length - 1; uint diff = 0; uint stakeEnd; uint stakeStart; uint total; diff = 0; stakeEnd = 0; stakeStart = 0; //last index should now be in our range so loop through until all block numbers are covered while(lastIndex >= 0) { if( (unStakes[lastIndex].endBlock != 0 && unStakes[lastIndex].endBlock < startBlock) || unStakes[lastIndex].startBlock > endBlock) { if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); continue; } stakeEnd = unStakes[lastIndex].endBlock == 0 ? endBlock : unStakes[lastIndex].endBlock; stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd); stakeStart = unStakes[lastIndex].startBlock < startBlock ? startBlock : unStakes[lastIndex].startBlock; diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart)); total = total.add(unStakes[lastIndex].amount.mul(diff)); if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } return total; } function getHoldingsForBlockRange( Staking[] memory stakes, uint startBlock, uint endBlock) internal pure returns (uint){ // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || stakes.length == 0 || stakes[0].startBlock > endBlock){ return 0; } uint lastIndex = stakes.length - 1; uint diff; // If the last total supply is before the start we are looking for we can take the last value if(stakes[lastIndex].startBlock <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); return stakes[lastIndex].total.mul(diff); } // working our way back we need to get the first index that falls into our range // This could be large so need to think of a better way to get here while(lastIndex > 0 && stakes[lastIndex].startBlock > endBlock){ lastIndex = lastIndex.sub(1); } uint total; diff = 0; //last index should now be in our range so loop through until all block numbers are covered while(stakes[lastIndex].startBlock >= startBlock ) { diff = 1; if(stakes[lastIndex].startBlock <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); break; } diff = endBlock.sub(stakes[lastIndex].startBlock) == 0 ? 1 : endBlock.sub(stakes[lastIndex].startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); endBlock = stakes[lastIndex].startBlock; if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } // If the last total supply is before the start we are looking for we can take the last value if(stakes[lastIndex].startBlock <= startBlock && startBlock <= endBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(stakes[lastIndex].total.mul(diff)); } return total; } function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = splitSignature(sig); return ecrecover(message, v, r, s); } function prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20CappedUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; contract iTrustGovernanceToken is ERC20CappedUpgradeable, OwnableUpgradeable, PausableUpgradeable { using SafeMathUpgradeable for uint; address internal _treasuryAddress; uint internal _yearOneSupply; uint internal _yearTwoSupply; uint internal _yearThreeSupply; uint internal _yearFourSupply; uint internal _yearFiveSupply; function initialize( address payable treasuryAddress, uint cap_, uint yearOneSupply, uint yearTwoSupply, uint yearThreeSupply, uint yearFourSupply, uint yearFiveSupply) initializer public { require(yearOneSupply.add(yearTwoSupply).add(yearThreeSupply).add(yearFourSupply).add(yearFiveSupply) == cap_); __ERC20_init("iTrust Governance Token", "$ITG"); __ERC20Capped_init(cap_); __Ownable_init(); __Pausable_init(); _treasuryAddress = treasuryAddress; _yearOneSupply = yearOneSupply; _yearTwoSupply = yearTwoSupply; _yearThreeSupply = yearThreeSupply; _yearFourSupply = yearFourSupply; _yearFiveSupply = yearFiveSupply; } function mintYearOne() external onlyOwner { require(totalSupply() == 0); _mint(_treasuryAddress, _yearOneSupply); } function mintYearTwo() external onlyOwner { require(totalSupply() == _yearOneSupply); _mint(_treasuryAddress, _yearTwoSupply); } function mintYearThree() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply)); _mint(_treasuryAddress, _yearThreeSupply); } function mintYearFour() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply)); _mint(_treasuryAddress, _yearFourSupply); } function mintYearFive() external onlyOwner { require(totalSupply() == _yearOneSupply.add(_yearTwoSupply).add(_yearThreeSupply).add(_yearFourSupply)); _mint(_treasuryAddress, _yearFiveSupply); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; abstract contract BaseContract is Initializable, ContextUpgradeable { uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _locked; address internal _iTrustFactoryAddress; mapping (address => uint32) internal _CurrentRoundNumbers; mapping (address => uint) internal _TotalUnstakedWnxm; mapping (address => uint[]) internal _TotalSupplyKeys; mapping (address => uint[]) internal _TotalUnstakingKeys; mapping (address => uint[]) internal _TotalSupplyForDayKeys; mapping (address => address[]) public totalRewardTokenAddresses; mapping (address => address[]) internal _UnstakingAddresses; mapping (address => address[]) internal _AccountStakesAddresses; mapping (address => VaultLib.UnStaking[]) internal _UnstakingRequests; mapping (address => mapping (address => uint32)) internal _RewardStartingRounds; mapping (address => mapping (address => VaultLib.AccountStaking)) internal _AccountStakes; mapping (address => mapping (address => VaultLib.UnStaking[])) internal _AccountUnstakings; mapping (address => mapping (address => uint8)) internal _RewardTokens; mapping (address => mapping (address => uint)) internal _AccountUnstakingTotals; mapping (address => mapping (address => uint)) internal _AccountUnstakedTotals; mapping (address => mapping (uint => uint)) internal _TotalSupplyHistory; mapping (address => mapping (address => mapping (address => VaultLib.ClaimedReward))) internal _AccountRewards; mapping (address => mapping (uint => VaultLib.RewardTokenRound)) internal _Rounds; mapping (address => mapping (uint => uint)) internal _TotalSupplyForDayHistory; mapping (address => mapping (uint => VaultLib.UnStaking)) internal _TotalUnstakingHistory; function _nonReentrant() internal view { require(_locked == FALSE); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../iTrustVaultFactory.sol"; import "./../tokens/iTrustGovernanceToken.sol"; import "./Vault.sol"; import { BokkyPooBahsDateTimeLibrary as DateTimeLib } from "./../3rdParty/BokkyPooBahsDateTimeLibrary.sol"; contract GovernanceDistribution is Initializable, ContextUpgradeable { using SafeMathUpgradeable for uint; uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _locked; uint internal _tokenPerHour; address internal _iTrustFactoryAddress; uint[] internal _totalSupplyKeys; mapping (uint => uint) internal _totalSupplyHistory; mapping (address => uint[]) internal _totalStakedKeys; mapping (address => mapping (uint => uint)) internal _totalStakedHistory; mapping (address => uint) internal _lastClaimedTimes; mapping(address => mapping(string => bool)) _UsedNonces; function initialize( address iTrustFactoryAddress, uint tokenPerDay ) initializer external { _iTrustFactoryAddress = iTrustFactoryAddress; _tokenPerHour = tokenPerDay.div(24); } /** * Public functions */ function totalStaked(address account) external view returns(uint) { _onlyAdmin(); if(_totalStakedKeys[account].length == 0){ return 0; } return _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)]]; } function totalSupply() external view returns(uint) { _onlyAdmin(); if(_totalSupplyKeys.length == 0){ return 0; } return _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(1)]]; } function calculateRewards() external view returns(uint amount, uint claimedUntil) { (amount, claimedUntil) = _calculateRewards(_msgSender()); return(amount, claimedUntil); } function calculateRewardsForAccount(address account) external view returns(uint amount, uint claimedUntil) { _isTrustedSigner(_msgSender()); (amount, claimedUntil) = _calculateRewards(account); return(amount, claimedUntil); } function removeStake(address account, uint value) external { _validateStakingDataAddress(); require(_totalStakedKeys[account].length != 0); uint currentTime = _getStartOfHourTimeStamp(block.timestamp); uint lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)]; if(lastStakedIndex > currentTime){ if(_totalStakedKeys[account].length == 1 || _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)] != currentTime){ _totalStakedKeys[account][_totalStakedKeys[account].length.sub(1)] = currentTime; _totalStakedHistory[account][currentTime] = _totalStakedKeys[account].length == 1 ? 0 : _totalStakedHistory[account][_totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)]]; _totalStakedKeys[account].push(lastStakedIndex); } _totalStakedHistory[account][lastStakedIndex] = _totalStakedHistory[account][lastStakedIndex].sub(value); lastStakedIndex = _totalStakedKeys[account][_totalStakedKeys[account].length.sub(2)]; } require(value <= _totalStakedHistory[account][lastStakedIndex]); uint newValue = _totalStakedHistory[account][lastStakedIndex].sub(value); if(lastStakedIndex != currentTime){ _totalStakedKeys[account].push(currentTime); } _totalStakedHistory[account][currentTime] = newValue; require(_totalSupplyKeys.length != 0); uint lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(1)]; if(lastSupplyIndex > currentTime){ if(_totalSupplyKeys.length == 1 || _totalSupplyKeys[_totalSupplyKeys.length.sub(2)] != currentTime){ _totalSupplyKeys[_totalSupplyKeys.length.sub(1)] = currentTime; _totalSupplyHistory[currentTime] = _totalSupplyKeys.length == 1 ? 0 : _totalSupplyHistory[_totalSupplyKeys[_totalSupplyKeys.length.sub(2)]]; _totalSupplyKeys.push(lastSupplyIndex); } _totalSupplyHistory[lastSupplyIndex] = _totalSupplyHistory[lastSupplyIndex].sub(value); lastSupplyIndex = _totalSupplyKeys[_totalSupplyKeys.length.sub(2)]; } if(lastSupplyIndex != currentTime){ _totalSupplyKeys.push(currentTime); } _totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyIndex].sub(value); } function addStake(address account, uint value) external { _validateStakingDataAddress(); uint currentTime = _getStartOfNextHourTimeStamp(block.timestamp); if(_totalStakedKeys[account].length == 0){ _totalStakedKeys[account].push(currentTime); _totalStakedHistory[account][currentTime] = value; } else { uint lastStakedIndex = _totalStakedKeys[account].length.sub(1); uint lastTimestamp = _totalStakedKeys[account][lastStakedIndex]; if(lastTimestamp != currentTime){ _totalStakedKeys[account].push(currentTime); } _totalStakedHistory[account][currentTime] = _totalStakedHistory[account][lastTimestamp].add(value); } if(_totalSupplyKeys.length == 0){ _totalSupplyKeys.push(currentTime); _totalSupplyHistory[currentTime] = value; } else { uint lastSupplyIndex = _totalSupplyKeys.length.sub(1); uint lastSupplyTimestamp = _totalSupplyKeys[lastSupplyIndex]; if(lastSupplyTimestamp != currentTime){ _totalSupplyKeys.push(currentTime); } _totalSupplyHistory[currentTime] = _totalSupplyHistory[lastSupplyTimestamp].add(value); } } function withdrawTokens(uint amount, uint claimedUntil, string memory nonce, bytes memory sig) external { _nonReentrant(); require(amount != 0); require(claimedUntil != 0); require(!_UsedNonces[_msgSender()][nonce]); _locked = TRUE; bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), amount, claimedUntil, nonce, address(this))); bytes32 message = _prefixed(abiBytes); address signer = _recoverSigner(message, sig); _isTrustedSigner(signer); _lastClaimedTimes[_msgSender()] = claimedUntil; _UsedNonces[_msgSender()][nonce] = true; _getiTrustGovernanceToken().transfer(_msgSender(), amount); _locked = FALSE; } /** * Internal functions */ function _calculateRewards(address account) internal view returns(uint, uint) { if(_totalStakedKeys[account].length == 0 || _totalSupplyKeys.length == 0){ return (0, 0); } uint currentTime = _getStartOfHourTimeStamp(block.timestamp); uint claimedUntil = _getStartOfHourTimeStamp(block.timestamp); uint lastClaimedTimestamp = _lastClaimedTimes[account]; // if 0 they have never staked go back to the first stake if(lastClaimedTimestamp == 0){ lastClaimedTimestamp = _totalStakedKeys[account][0]; } uint totalRewards = 0; uint stakedStartingIndex = _totalStakedKeys[account].length.sub(1); uint supplyStartingIndex = _totalSupplyKeys.length.sub(1); uint hourReward = 0; while(currentTime > lastClaimedTimestamp) { (hourReward, stakedStartingIndex, supplyStartingIndex) = _getTotalRewardHour(account, currentTime, stakedStartingIndex, supplyStartingIndex); totalRewards = totalRewards.add(hourReward); currentTime = DateTimeLib.subHours(currentTime, 1); } return (totalRewards, claimedUntil); } function _getTotalRewardHour(address account, uint hourTimestamp, uint stakedStartingIndex, uint supplyStartingIndex) internal view returns(uint, uint, uint) { (uint totalStakedForHour, uint returnedStakedStartingIndex) = _getTotalStakedForHour(account, hourTimestamp, stakedStartingIndex); (uint totalSupplyForHour, uint returnedSupplyStartingIndex) = _getTotalSupplyForHour(hourTimestamp, supplyStartingIndex); uint reward = 0; if(totalSupplyForHour > 0 && totalStakedForHour > 0){ uint govTokenPerTokenPerHour = _divider(_tokenPerHour, totalSupplyForHour, 18); // _tokenPerHour.div(totalSupplyForHour); reward = reward.add(totalStakedForHour.mul(govTokenPerTokenPerHour).div(1e18)); } return (reward, returnedStakedStartingIndex, returnedSupplyStartingIndex); } function _getTotalStakedForHour(address account, uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) { while(startingIndex != 0 && hourTimestamp <= _totalStakedKeys[account][startingIndex]) { startingIndex = startingIndex.sub(1); } // We never got far enough back before hitting 0, meaning we staked after the hour we are looking up if(hourTimestamp < _totalStakedKeys[account][startingIndex]){ return (0, startingIndex); } return (_totalStakedHistory[account][_totalStakedKeys[account][startingIndex]], startingIndex); } function _getTotalSupplyForHour(uint hourTimestamp, uint startingIndex) internal view returns(uint, uint) { while(startingIndex != 0 && hourTimestamp <= _totalSupplyKeys[startingIndex]) { startingIndex = startingIndex.sub(1); } // We never got far enough back before hitting 0, meaning we staked after the hour we are looking up if(hourTimestamp < _totalSupplyKeys[startingIndex]){ return (0, startingIndex); } return (_totalSupplyHistory[_totalSupplyKeys[startingIndex]], startingIndex); } function _getStartOfHourTimeStamp(uint nowDateTime) internal pure returns (uint) { (uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime); return DateTimeLib.timestampFromDateTime(year, month, day, hour, 0, 0); } function _getStartOfNextHourTimeStamp(uint nowDateTime) internal pure returns (uint) { (uint year, uint month, uint day, uint hour, ,) = DateTimeLib.timestampToDateTime(nowDateTime); return DateTimeLib.timestampFromDateTime(year, month, day, hour.add(1), 0, 0); } function _getITrustVaultFactory() internal view returns(ITrustVaultFactory) { return ITrustVaultFactory(_iTrustFactoryAddress); } function _governanceTokenAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getGovernanceTokenAddress(); } function _getiTrustGovernanceToken() internal view returns(iTrustGovernanceToken) { return iTrustGovernanceToken(_governanceTokenAddress()); } function _divider(uint numerator, uint denominator, uint precision) internal pure returns(uint) { return numerator*(uint(10)**uint(precision))/denominator; } /** * Validate functions */ function _nonReentrant() internal view { require(_locked == FALSE); } function _onlyAdmin() internal view { require( _getITrustVaultFactory().isAddressAdmin(_msgSender()), "Not admin" ); } function _isTrustedSigner(address signer) internal view { require( _getITrustVaultFactory().isTrustedSignerAddress(signer), "Not trusted signer" ); } function _validateStakingDataAddress() internal view { _validateStakingDataAddress(_msgSender()); } function _validateStakingDataAddress(address contractAddress) internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isStakingDataAddress(contractAddress)); } function _splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } return (v, r, s); } function _recoverSigner(bytes32 message, bytes memory sig) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; (v, r, s) = _splitSignature(sig); return ecrecover(message, v, r, s); } function _prefixed(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../iTrustVaultFactory.sol"; import "./BaseContract.sol"; import "./StakingDataController/StakeData.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; contract StakingCalculation { using SafeMath for uint; // function getRoundDataForAccount( // VaultLib.Staking[] memory stakes, // VaultLib.UnStaking[] memory unstakes, // uint startBlock, // uint endBlock) external pure // returns (uint totalHoldings, uint[] memory stakeBlocks, uint[] memory stakeAmounts, uint[] memory unstakeStartBlocks, uint[] memory unstakeEndBlocks, uint[] memory unstakeAmounts) // { // totalHoldings = VaultLib.getHoldingsForBlockRange(stakes, startBlock, endBlock); // (stakeBlocks, stakeAmounts) = VaultLib.getRoundDataStakesForAccount(stakes, startBlock, endBlock); // (unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts) = VaultLib.getRoundDataUnstakesForAccount(unstakes, startBlock, endBlock); // return (totalHoldings, stakeBlocks, stakeAmounts, unstakeStartBlocks, unstakeEndBlocks, unstakeAmounts); // } function getUnstakingsForBlockRange( VaultLib.UnStaking[] memory unStakes, uint startBlock, uint endBlock) external pure returns (uint){ return VaultLib.getUnstakingsForBlockRange( unStakes, startBlock, endBlock ); } function getHoldingsForBlockRange( VaultLib.Staking[] memory stakes, uint startBlock, uint endBlock) external pure returns (uint){ return VaultLib.getHoldingsForBlockRange( stakes, startBlock, endBlock); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../iTrustVaultFactory.sol"; import "./BaseContract.sol"; import "./StakingDataController/StakeData.sol"; import "./StakingCalculation.sol"; import "./StakingDataController/RoundData.sol"; contract StakingData is BaseContract { using SafeMathUpgradeable for uint; function initialize( address iTrustFactoryAddress ) initializer external { _iTrustFactoryAddress = iTrustFactoryAddress; _locked = FALSE; } /** * Public functions */ function _getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) { (bool success, bytes memory result) = _stakeDataImplementationAddress() .delegatecall( abi.encodeWithSelector( StakeData.getTotalSupplyForBlockRange.selector, vaultAddress, endBlock, startBlock ) ); require(success); return abi.decode(result, (uint256)); } function _getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) internal returns(uint) { (bool success, bytes memory result) = _stakeDataImplementationAddress() .delegatecall( abi.encodeWithSelector( StakeData.getTotalUnstakingsForBlockRange.selector, vaultAddress, endBlock, startBlock ) ); require(success); return abi.decode(result, (uint256)); } function addVault(address vaultAddress) external { _validateFactory(); _CurrentRoundNumbers[vaultAddress] = 1; _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number; _updateTotalSupplyForBlock(0); } function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes, uint commission) external returns(bool) { _validateVault(); address vaultAddress = _vaultAddress(); uint startBlock = _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock; (bool result, ) = _roundDataImplementationAddress() .delegatecall( abi.encodeWithSelector( RoundData.endRound.selector, vaultAddress, tokens, tokenAmounts, ignoreUnstakes, _getTotalSupplyForBlockRange( vaultAddress, block.number, startBlock ), _getTotalUnstakingsForBlockRange( vaultAddress, block.number, startBlock ), commission) ); require(result); return true; } function getCurrentRoundData() external view returns(uint, uint, uint) { _validateVault(); return _getRoundDataForAddress(_vaultAddress(), _CurrentRoundNumbers[_vaultAddress()]); } function getRoundData(uint roundNumberIn) external view returns(uint, uint, uint) { _validateVault(); return _getRoundDataForAddress(_vaultAddress(), roundNumberIn); } function getRoundRewards(uint roundNumber) external view returns( address[] memory rewardTokens, uint[] memory rewardAmounts, uint[] memory commisionAmounts, uint[] memory tokenPerBlock, uint[] memory totalSupply ) { _validateVault(); return _getRoundRewardsForAddress(_vaultAddress(), roundNumber); } function startUnstake(address account, uint256 value) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.startUnstakeForAddress.selector, _vaultAddress(), account, value)); return result; } function getAccountStakes(address account) external view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { _validateVault(); return _getAccountStakesForAddress(_vaultAddress(), account); } function getAccountStakingTotal(address account) external view returns (uint) { _validateVault(); return _AccountStakes[_vaultAddress()][account].total.sub(_AccountUnstakingTotals[_vaultAddress()][account]); } function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { _validateVault(); return _getAllAcountUnstakesForAddress(_vaultAddress()); } function getAccountUnstakedTotal(address account) external view returns (uint) { _validateVault(); return _AccountUnstakedTotals[_vaultAddress()][account]; } function authoriseUnstakes(address[] memory account, uint[] memory timestamp) external returns(bool) { _validateVault(); require(account.length <= 10); for(uint8 i = 0; i < account.length; i++) { _authoriseUnstake(_vaultAddress(), account[i], timestamp[i]); } return true; } function withdrawUnstakedToken(address account, uint amount) external returns(bool) { _validateVault(); _nonReentrant(); _locked = TRUE; address vaultAddress = _vaultAddress(); require(_AccountUnstakedTotals[vaultAddress][account] > 0); require(amount <= _AccountUnstakedTotals[vaultAddress][account]); _AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account].sub(amount); _TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].sub(amount); _locked = FALSE; return true; } function createStake(uint amount, address account) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.createStake.selector,_vaultAddress(),amount,account)); return result; } function removeStake(uint amount, address account) external returns(bool) { _validateVault(); (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.removeStake.selector, _vaultAddress(), amount, account)); return result; } function calculateRewards(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) { _validateVault(); return _calculateRewards(account); } function withdrawRewards(address account, address[] memory rewardTokens, uint[] memory rewards) external returns(bool) { _validateVault(); _nonReentrant(); _locked = TRUE; _withdrawRewards(_vaultAddress(), rewardTokens, rewards, account); _locked = FALSE; return true; } function updateTotalSupplyForDayAndBlock(uint totalSupply) external returns(bool) { _validateVault(); _updateTotalSupplyForBlock(totalSupply); return true; } function getTotalSupplyForAccountBlock(address vaultAddress, uint date) external view returns(uint) { _validateBurnContract(); return _getTotalSupplyForAccountBlock(vaultAddress, date); } function getHoldingsForIndexAndBlockForVault(address vaultAddress, uint index, uint blockNumber) external view returns(address indexAddress, uint addressHoldings) { _validateBurnContract(); return _getHoldingsForIndexAndBlock(vaultAddress, index, blockNumber); } function getNumberOfStakingAddressesForVault(address vaultAddress) external view returns(uint) { _validateBurnContract(); return _AccountStakesAddresses[vaultAddress].length; } /** * Internal functions */ function _getHoldingsForIndexAndBlock(address vaultAddress, uint index, uint blockNumber) internal view returns(address indexAddress, uint addressHoldings) { require(_AccountStakesAddresses[vaultAddress].length - 1 >= index); indexAddress = _AccountStakesAddresses[vaultAddress][index]; bytes memory data = abi.encodeWithSelector(StakingCalculation.getHoldingsForBlockRange.selector, _AccountStakes[vaultAddress][indexAddress].stakes, blockNumber, blockNumber); (, bytes memory resultData) = _stakingCalculationsAddress().staticcall(data); addressHoldings = abi.decode(resultData, (uint256)); return(indexAddress, addressHoldings); } function _getTotalSupplyForAccountBlock(address vaultAddress, uint blockNumber) internal view returns(uint) { uint index = _getIndexForBlock(vaultAddress, blockNumber, 0); return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][index]]; } function _authoriseUnstake(address vaultAddress, address account, uint timestamp) internal { (bool result, ) = _stakeDataImplementationAddress() .delegatecall(abi.encodeWithSelector(StakeData.authoriseUnstake.selector, vaultAddress, account, timestamp)); require(result); } function _updateTotalSupplyForBlock(uint totalSupply) public returns(bool) { if(_TotalSupplyHistory[_vaultAddress()][block.number] == 0){ // Assumes there will never be 0, could use the array itself to check will look at this again _TotalSupplyKeys[_vaultAddress()].push(block.number); } _TotalSupplyHistory[_vaultAddress()][block.number] = totalSupply; return true; } function _getRoundDataForAddress(address vaultAddress, uint roundNumberIn) internal view returns(uint roundNumber, uint startBlock, uint endBlock) { roundNumber = roundNumberIn; startBlock = _Rounds[vaultAddress][roundNumber].startBlock; endBlock = _Rounds[vaultAddress][roundNumber].endBlock; return( roundNumber, startBlock, endBlock ); } function _getRoundRewardsForAddress(address vaultAddress, uint roundNumber) internal view returns( address[] memory rewardTokens, uint[] memory rewardAmounts, uint[] memory commissionAmounts, uint[] memory tokenPerBlock, uint[] memory totalSupply ) { rewardTokens = new address[](totalRewardTokenAddresses[vaultAddress].length); rewardAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length); commissionAmounts = new uint[](totalRewardTokenAddresses[vaultAddress].length); tokenPerBlock = new uint[](totalRewardTokenAddresses[vaultAddress].length); totalSupply = new uint[](totalRewardTokenAddresses[vaultAddress].length); for(uint i = 0; i < totalRewardTokenAddresses[vaultAddress].length; i++){ rewardTokens[i] = totalRewardTokenAddresses[vaultAddress][i]; rewardAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].amount; commissionAmounts[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].commissionAmount; tokenPerBlock[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].tokenPerBlock; totalSupply[i] = _Rounds[vaultAddress][roundNumber].roundData[totalRewardTokenAddresses[vaultAddress][i]].totalSupply; } return( rewardTokens, rewardAmounts, commissionAmounts, tokenPerBlock, totalSupply ); } function _getIndexForBlock(address vaultAddress, uint startBlock, uint startIndex) internal view returns(uint) { uint i = startIndex == 0 ? _TotalSupplyKeys[vaultAddress].length.sub(1) : startIndex; uint blockForIndex = _TotalSupplyKeys[vaultAddress][i]; if(_TotalSupplyKeys[vaultAddress][0] > startBlock){ return 0; } if(blockForIndex < startBlock){ return i; } while(blockForIndex > startBlock){ i = i.sub(1); blockForIndex = _TotalSupplyKeys[vaultAddress][i]; } return i; } function _getAccountStakesForAddress(address vaultAddress, address account) internal view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { unStakingAmounts = new uint[](_AccountUnstakings[vaultAddress][account].length); unStakingStarts = new uint[](_AccountUnstakings[vaultAddress][account].length); for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){ if(_AccountUnstakings[vaultAddress][account][i].endBlock == 0){ unStakingAmounts[i] = _AccountUnstakings[vaultAddress][account][i].amount; unStakingStarts[i] = _AccountUnstakings[vaultAddress][account][i].startDateTime; } } return( _AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]), _AccountUnstakingTotals[vaultAddress][account], unStakingAmounts, unStakingStarts ); } function _getAllAcountUnstakesForAddress(address vaultAddress) internal view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { accounts = new address[](_UnstakingRequests[vaultAddress].length); startTimes = new uint[](_UnstakingRequests[vaultAddress].length); values = new uint[](_UnstakingRequests[vaultAddress].length); for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++) { if(_UnstakingRequests[vaultAddress][i].endBlock == 0 ) { accounts[i] = _UnstakingRequests[vaultAddress][i].account; startTimes[i] = _UnstakingRequests[vaultAddress][i].startDateTime; values[i] = _UnstakingRequests[vaultAddress][i].amount; } } return(accounts, startTimes, values); } function getUnstakedWxnmTotal() external view returns(uint total) { _validateVault(); total = _TotalUnstakedWnxm[_vaultAddress()]; } function _calculateRewards(address account) internal view returns (address[] memory rewardTokens, uint[] memory rewards) { rewardTokens = totalRewardTokenAddresses[_vaultAddress()]; rewards = new uint[](rewardTokens.length); for(uint x = 0; x < totalRewardTokenAddresses[_vaultAddress()].length; x++){ (rewards[x]) = _calculateReward(_vaultAddress(), account, rewardTokens[x]); rewards[x] = rewards[x].div(1 ether); } return (rewardTokens, rewards); } function _calculateReward(address vaultAddress, address account, address rewardTokenAddress) internal view returns (uint reward){ VaultLib.ClaimedReward memory claimedReward = _AccountRewards[vaultAddress][account][rewardTokenAddress]; if(_RewardStartingRounds[vaultAddress][rewardTokenAddress] == 0){ return(0); } uint futureRoundNumber = _CurrentRoundNumbers[vaultAddress] - 1;// one off as the current hasnt closed address calcContract = _stakingCalculationsAddress(); while(claimedReward.lastClaimedRound < futureRoundNumber && _RewardStartingRounds[vaultAddress][rewardTokenAddress] <= futureRoundNumber && futureRoundNumber != 0 ) { if(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount == 0){ futureRoundNumber--; continue; } (, bytes memory resultData) = calcContract.staticcall(abi.encodeWithSignature( "getHoldingsForBlockRange((uint256,uint256,uint256,uint256)[],uint256,uint256)", _AccountStakes[vaultAddress][account].stakes, _Rounds[vaultAddress][futureRoundNumber].startBlock, _Rounds[vaultAddress][futureRoundNumber].endBlock )); uint holdingsForRound = abi.decode(resultData, (uint256)); if (!(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].ignoreUnstakes)) { (, bytes memory unstakedResultData) = calcContract.staticcall(abi.encodeWithSignature( "getUnstakingsForBlockRange((address,uint256,uint256,uint256,uint256)[],uint256,uint256)", _AccountUnstakings[vaultAddress][account], _Rounds[vaultAddress][futureRoundNumber].startBlock, _Rounds[vaultAddress][futureRoundNumber].endBlock )); holdingsForRound = holdingsForRound.sub(abi.decode(unstakedResultData, (uint256))); } holdingsForRound = VaultLib.divider( holdingsForRound, _Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].totalSupply, 18) .mul(_Rounds[vaultAddress][futureRoundNumber].roundData[rewardTokenAddress].amount); reward = reward.add(holdingsForRound); futureRoundNumber--; } return (reward); } function _withdrawRewards(address vaultAddress, address[] memory rewardTokens, uint[] memory rewards, address account) internal { for (uint x = 0; x < rewardTokens.length; x++){ _AccountRewards[vaultAddress][account][rewardTokens[x]].amount = _AccountRewards[vaultAddress][account][rewardTokens[x]].amount + rewards[x]; _AccountRewards[vaultAddress][account][rewardTokens[x]].lastClaimedRound = _CurrentRoundNumbers[vaultAddress] - 1; } } function _vaultAddress() internal view returns(address) { return _msgSender(); } function _roundDataImplementationAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getRoundDataImplementationAddress(); } function _stakeDataImplementationAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getStakeDataImplementationAddress(); } function _stakingCalculationsAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return address(vaultFactory.getStakingCalculationsAddress()); } /** * Validate functions */ function _validateVault() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isActiveVault(_vaultAddress())); } function _validateBurnContract() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require(vaultFactory.isBurnAddress(_msgSender())); } function _validateFactory() internal view { require(_msgSender() == _iTrustFactoryAddress); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../BaseContract.sol"; contract RoundData is BaseContract { using SafeMathUpgradeable for uint; function endRound( address vaultAddress, address[] memory tokens, uint[] memory tokenAmounts, bool[] memory ignoreUnstakes, uint totalSupplyForBlockRange, uint totalUnstakings, uint commissionValue) external { require( _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock < block.number); uint32 roundNumber = _CurrentRoundNumbers[vaultAddress]; uint rewardAmount; uint commissionAmount; uint tokensPerBlock; //Amoun for (uint i=0; i < tokens.length; i++) { rewardAmount = tokenAmounts[i].sub(tokenAmounts[i].mul(commissionValue).div(10000)); commissionAmount = tokenAmounts[i].mul(commissionValue).div(10000); tokensPerBlock = VaultLib.divider(rewardAmount, _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]), 18); VaultLib.RewardTokenRoundData memory tokenData = VaultLib.RewardTokenRoundData( { tokenAddress: tokens[i], amount: rewardAmount, commissionAmount: commissionAmount, tokenPerBlock: tokensPerBlock,//.div(1e18), totalSupply: _getAdjustedTotalSupply(totalSupplyForBlockRange, totalUnstakings, ignoreUnstakes[i]), ignoreUnstakes: ignoreUnstakes[i] } ); _Rounds[vaultAddress][roundNumber].roundData[tokens[i]] = tokenData; if(_RewardTokens[vaultAddress][tokens[i]] != TRUE){ _RewardStartingRounds[vaultAddress][tokens[i]] = roundNumber; totalRewardTokenAddresses[vaultAddress].push(tokens[i]); _RewardTokens[vaultAddress][tokens[i]] = TRUE; } } //do this last _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].endBlock = block.number; _CurrentRoundNumbers[vaultAddress]++; _Rounds[vaultAddress][_CurrentRoundNumbers[vaultAddress]].startBlock = block.number; } function _getAdjustedTotalSupply(uint totalSupply, uint totalUnstaking, bool ignoreUnstaking) internal pure returns(uint) { if(ignoreUnstaking) { return totalSupply; } return (totalUnstaking > totalSupply ? 0 : totalSupply.sub(totalUnstaking)); } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./../BaseContract.sol"; import "./../GovernanceDistribution.sol"; contract StakeData is BaseContract { using SafeMathUpgradeable for uint; function startUnstakeForAddress(address vaultAddress, address account, uint256 value) external { require( ( _AccountStakes[vaultAddress][account].total.sub(_AccountUnstakingTotals[vaultAddress][account]) ) >= value); _AccountUnstakingTotals[vaultAddress][account] =_AccountUnstakingTotals[vaultAddress][account].add(value); VaultLib.UnStaking memory unstaking = VaultLib.UnStaking(account, value, block.timestamp, block.number, 0 ); _AccountUnstakings[vaultAddress][account].push(unstaking); _UnstakingRequests[vaultAddress].push(unstaking); _UnstakingAddresses[vaultAddress].push(account); _TotalUnstakingKeys[vaultAddress].push(block.number); _TotalUnstakingHistory[vaultAddress][block.number] = unstaking; } function authoriseUnstake(address vaultAddress, address account, uint timestamp) external { uint amount = 0; for(uint i = 0; i < _AccountUnstakings[vaultAddress][account].length; i++){ if(_AccountUnstakings[vaultAddress][account][i].startDateTime == timestamp) { amount = _AccountUnstakings[vaultAddress][account][i].amount; _AccountUnstakedTotals[vaultAddress][account] = _AccountUnstakedTotals[vaultAddress][account] + amount; _AccountUnstakings[vaultAddress][account][i].endBlock = block.number; _AccountUnstakingTotals[vaultAddress][account] = _AccountUnstakingTotals[vaultAddress][account] - amount; _TotalUnstakedWnxm[vaultAddress] = _TotalUnstakedWnxm[vaultAddress].add(amount); break; } } for(uint i = 0; i < _UnstakingRequests[vaultAddress].length; i++){ if(_UnstakingRequests[vaultAddress][i].startDateTime == timestamp && _UnstakingRequests[vaultAddress][i].amount == amount && _UnstakingRequests[vaultAddress][i].endBlock == 0 && _UnstakingAddresses[vaultAddress][i] == account) { delete _UnstakingAddresses[vaultAddress][i]; _UnstakingRequests[vaultAddress][i].endBlock = block.number; _TotalUnstakingHistory[vaultAddress] [_UnstakingRequests[vaultAddress][i].startBlock].endBlock = block.number; } } _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount); _AccountStakes[vaultAddress][account].stakes.push(VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total)); _governanceDistributionContract().removeStake(account, amount); } function createStake(address vaultAddress, uint amount, address account) external { if( _AccountStakes[vaultAddress][account].startRound == 0) { _AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress]; _AccountStakesAddresses[vaultAddress].push(account); } _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.add(amount); // block number is being used to record the block at which staking started for governance token distribution _AccountStakes[vaultAddress][account].stakes.push( VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total) ); _governanceDistributionContract().addStake(account, amount); } function removeStake(address vaultAddress, uint amount, address account) external { if( _AccountStakes[vaultAddress][account].startRound == 0) { _AccountStakes[vaultAddress][account].startRound = _CurrentRoundNumbers[vaultAddress]; _AccountStakesAddresses[vaultAddress].push(account); } require(_AccountStakes[vaultAddress][account].total >= amount); _AccountStakes[vaultAddress][account].total = _AccountStakes[vaultAddress][account].total.sub(amount); // block number is being used to record the block at which staking started for governance token distribution _AccountStakes[vaultAddress][account].stakes.push( VaultLib.Staking(block.timestamp, block.number, amount, _AccountStakes[vaultAddress][account].total) ); _governanceDistributionContract().removeStake(account, amount); } function _governanceDistributionAddress() internal view returns(address) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.getGovernanceDistributionAddress(); } function _governanceDistributionContract() internal view returns(GovernanceDistribution) { return GovernanceDistribution(_governanceDistributionAddress()); } function getTotalUnstakingsForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) { // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || _TotalUnstakingKeys[vaultAddress].length == 0 || _TotalUnstakingKeys[vaultAddress][0] > endBlock){ return 0; } uint lastIndex = _TotalUnstakingKeys[vaultAddress].length - 1; uint total; uint diff; uint stakeEnd; uint stakeStart; if(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock && lastIndex == 0) { return 0; } //last index should now be in our range so loop through until all block numbers are covered while( lastIndex >= 0 ) { if( _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock < startBlock && _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock != 0 ) { if (lastIndex == 0) { break; } lastIndex = lastIndex.sub(1); continue; } stakeEnd = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock == 0 ? endBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].endBlock; stakeEnd = (stakeEnd >= endBlock ? endBlock : stakeEnd); stakeStart = _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock < startBlock ? startBlock : _TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].startBlock; diff = (stakeEnd == stakeStart ? 1 : stakeEnd.sub(stakeStart)); total = total.add(_TotalUnstakingHistory[vaultAddress][_TotalUnstakingKeys[vaultAddress][lastIndex]].amount.mul(diff)); if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } return total; } function getTotalSupplyForBlockRange(address vaultAddress, uint endBlock, uint startBlock) external view returns(uint) { // If we have bad data, no supply data or it starts after the block we are looking for then we can return zero if(endBlock < startBlock || _TotalSupplyKeys[vaultAddress].length == 0 || _TotalSupplyKeys[vaultAddress][0] > endBlock){ return 0; } uint lastIndex = _TotalSupplyKeys[vaultAddress].length - 1; // If the last total supply is before the start we are looking for we can take the last value if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){ return _TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock)); } // working our way back we need to get the first index that falls into our range // This could be large so need to think of a better way to get here while(lastIndex > 0 && _TotalSupplyKeys[vaultAddress][lastIndex] > endBlock){ if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } uint total; uint diff; //last index should now be in our range so loop through until all block numbers are covered while(_TotalSupplyKeys[vaultAddress][lastIndex] >= startBlock) { diff = 0; if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock){ diff = endBlock.sub(startBlock) == 0 ? 1 : endBlock.sub(startBlock); total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff)); break; } diff = endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]) == 0 ? 1 : endBlock.sub(_TotalSupplyKeys[vaultAddress][lastIndex]); total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(diff)); endBlock = _TotalSupplyKeys[vaultAddress][lastIndex]; if(lastIndex == 0){ break; } lastIndex = lastIndex.sub(1); } // If the last total supply is before the start we are looking for we can take the last value if(_TotalSupplyKeys[vaultAddress][lastIndex] <= startBlock && startBlock < endBlock){ total = total.add(_TotalSupplyHistory[vaultAddress][_TotalSupplyKeys[vaultAddress][lastIndex]].mul(endBlock.sub(startBlock))); } return total; } } pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "./StakingData.sol"; import "./../iTrustVaultFactory.sol"; import { ITrustVaultLib as VaultLib } from "./../libraries/ItrustVaultLib.sol"; contract Vault is ERC20Upgradeable { using SafeMathUpgradeable for uint; uint8 internal constant FALSE = 0; uint8 internal constant TRUE = 1; uint8 internal _Locked; uint internal _RewardCommission; uint internal _AdminFee; address internal _NXMAddress; address internal _WNXMAddress; address payable internal _VaultWalletAddress; address payable internal _TreasuryAddress; address internal _StakingDataAddress; address internal _BurnDataAddress; address internal _iTrustFactoryAddress; mapping (address => uint256) internal _ReentrantCheck; mapping(address => mapping(string => bool)) internal _UsedNonces; event Stake(address indexed account, address indexed tokenAddress, uint amount, uint balance, uint totalStaked); event UnstakedRequest(address indexed account, uint amount, uint balance, uint totalStaked); event UnstakedApproved(address indexed account, uint amount, uint balance, uint totalStaked); event TransferITV( address indexed fromAccount, address indexed toAccount, uint amount, uint fromBalance, uint fromTotalStaked, uint toBalance, uint toTotalStaked); function initialize( address nxmAddress, address wnxmAddress, address vaultWalletAddress, address stakingDataAddress, address burnDataAddress, string memory tokenName, string memory tokenSymbol, uint adminFee, uint commission, address treasuryAddress ) initializer external { __ERC20_init(tokenName, tokenSymbol); _Locked = FALSE; _NXMAddress = nxmAddress; _WNXMAddress = wnxmAddress; _VaultWalletAddress = payable(vaultWalletAddress); _StakingDataAddress = stakingDataAddress; _BurnDataAddress = burnDataAddress; _AdminFee = adminFee; _iTrustFactoryAddress = _msgSender(); _RewardCommission = commission; _TreasuryAddress = payable(treasuryAddress); } /** * Public functions */ function getAdminFee() external view returns (uint) { return _AdminFee; } function SetAdminFee(uint newFee) external { _onlyAdmin(); _AdminFee = newFee; } function setCommission(uint newCommission) external { _onlyAdmin(); _RewardCommission = newCommission; } function setTreasury(address newTreasury) external { _onlyAdmin(); _TreasuryAddress = payable(newTreasury); } function depositNXM(uint256 value) external { _valueCheck(value); _nonReentrant(); _Locked = TRUE; IERC20Upgradeable nxmToken = IERC20Upgradeable(_NXMAddress); _mint( _msgSender(), value ); require(_getStakingDataContract().createStake(value, _msgSender())); require(nxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value)); emit Stake( _msgSender(), _NXMAddress, value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function _depositRewardToken(address token, uint amount) internal { require(token != address(0)); uint commission = 0; uint remain = amount; if (_RewardCommission != 0) { commission = amount.mul(_RewardCommission).div(10000); remain = amount.sub(commission); } IERC20Upgradeable tokenContract = IERC20Upgradeable(token); if (commission != 0) { require(tokenContract.transferFrom(msg.sender, _TreasuryAddress, commission)); } require(tokenContract.transferFrom(msg.sender, address(this), remain)); } function endRound(address[] calldata tokens, uint[] calldata tokenAmounts, bool[] calldata ignoreUnstakes) external { _onlyAdmin(); require(tokens.length == tokenAmounts.length); require(_getStakingDataContract().endRound(tokens, tokenAmounts, ignoreUnstakes, _RewardCommission)); for(uint i = 0; i < tokens.length; i++) { _depositRewardToken(tokens[i], tokenAmounts[i]); } } function getCurrentRoundData() external view returns(uint roundNumber, uint startBlock, uint endBlock) { _onlyAdmin(); return _getStakingDataContract().getCurrentRoundData(); } function getRoundData(uint roundNumberIn) external view returns(uint roundNumber, uint startBlock, uint endBlock) { _onlyAdmin(); return _getStakingDataContract().getRoundData(roundNumberIn); } function getRoundRewards(uint roundNumber) external view returns( address[] memory rewardTokens, uint[] memory rewardAmounts , uint[] memory commissionAmounts, uint[] memory tokenPerDay, uint[] memory totalSupply ) { _onlyAdmin(); return _getStakingDataContract().getRoundRewards(roundNumber); } function depositWNXM(uint256 value) external { _valueCheck(value); _nonReentrant(); _Locked = TRUE; IERC20Upgradeable wnxmToken = IERC20Upgradeable(_WNXMAddress); _mint( _msgSender(), value ); require(_getStakingDataContract().createStake(value, _msgSender())); require(wnxmToken.transferFrom(_msgSender(), _VaultWalletAddress, value)); emit Stake( _msgSender(), _WNXMAddress, value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function startUnstake(uint256 value) external payable { _nonReentrant(); _Locked = TRUE; uint adminFee = _AdminFee; if(adminFee != 0) { require(msg.value == _AdminFee); } require(_getStakingDataContract().startUnstake(_msgSender(), value)); if(adminFee != 0) { (bool sent, ) = _VaultWalletAddress.call{value: adminFee}(""); require(sent); } emit UnstakedRequest( _msgSender(), value, balanceOf(_msgSender()), _getStakingDataContract().getAccountStakingTotal(_msgSender())); _Locked = FALSE; } function getAccountStakes() external view returns( uint stakingTotal, uint unStakingTotal, uint[] memory unStakingAmounts, uint[] memory unStakingStarts ) { return _getStakingDataContract().getAccountStakes(_msgSender()); } function getAllAcountUnstakes() external view returns (address[] memory accounts, uint[] memory startTimes, uint[] memory values) { _onlyAdmin(); return _getStakingDataContract().getAllAcountUnstakes(); } function getAccountUnstakedTotal() external view returns (uint) { return _getStakingDataContract().getAccountUnstakedTotal(_msgSender()); } function getUnstakedwNXMTotal() external view returns (uint) { return _getStakingDataContract().getUnstakedWxnmTotal(); } function authoriseUnstakes(address[] memory account, uint[] memory timestamp, uint[] memory amounts) external { _onlyAdmin(); require(_getStakingDataContract().authoriseUnstakes(account, timestamp)); //for each unstake burn for(uint i = 0; i < account.length; i++) { _burn(account[i], amounts[i]); emit UnstakedApproved( account[i], amounts[i], balanceOf(account[i]), _getStakingDataContract().getAccountStakingTotal(account[i])); } } function withdrawUnstakedwNXM(uint amount) external { _nonReentrant(); _Locked = TRUE; IERC20Upgradeable wnxm = IERC20Upgradeable(_WNXMAddress); uint balance = wnxm.balanceOf(address(this)); require(amount <= balance); require(_getStakingDataContract().withdrawUnstakedToken(_msgSender(), amount)); require(wnxm.transfer(msg.sender, amount)); // emit ClaimUnstaked(msg.sender, amount); _Locked = FALSE; } function isAdmin() external view returns (bool) { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); return vaultFactory.isAddressAdmin(_msgSender()); } function calculateRewards() external view returns (address[] memory rewardTokens, uint[] memory rewards) { return _getStakingDataContract().calculateRewards(_msgSender()); } function calculateRewardsForAccount(address account) external view returns (address[] memory rewardTokens, uint[] memory rewards) { _isTrustedSigner(_msgSender()); return _getStakingDataContract().calculateRewards(account); } function withdrawRewards(address[] memory tokens, uint[] memory rewards, string memory nonce, bytes memory sig) external returns (bool) { require(!_UsedNonces[_msgSender()][nonce]); _nonReentrant(); _Locked = TRUE; bool toClaim = false; for(uint x = 0; x < tokens.length; x++){ if(rewards[x] != 0) { toClaim = true; } } require(toClaim == true); bytes32 abiBytes = keccak256(abi.encodePacked(_msgSender(), tokens, rewards, nonce, address(this))); bytes32 message = VaultLib.prefixed(abiBytes); address signer = VaultLib.recoverSigner(message, sig); _isTrustedSigner(signer); require(_getStakingDataContract().withdrawRewards(_msgSender(), tokens, rewards)); _UsedNonces[_msgSender()][nonce] = true; for(uint x = 0; x < tokens.length; x++){ if(rewards[x] != 0) { IERC20Upgradeable token = IERC20Upgradeable(tokens[x]); require(token.balanceOf(address(this)) >= rewards[x]); require(token.transfer(_msgSender() ,rewards[x])); } } _Locked = FALSE; return true; } function burnTokensForAccount(address account, uint tokensToBurn) external returns(bool) { _nonReentrant(); _validBurnSender(); require(tokensToBurn > 0); _Locked = TRUE; _burn(account, tokensToBurn); require(_getStakingDataContract().removeStake(tokensToBurn, account)); _Locked = FALSE; return true; } /** * @dev See {IERC20Upgradeable-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20Upgradeable-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance(_msgSender(), sender).sub(amount)); return true; } /** * @dev required to be allow for receiving ETH claim payouts */ receive() external payable {} /** * Private functions */ /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal override { super._mint(account, amount); _updateTotalSupplyForBlock(); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal override { super._burn(account, amount); _updateTotalSupplyForBlock(); } function _getStakingDataContract() internal view returns (StakingData){ return StakingData(_StakingDataAddress); } function _updateTotalSupplyForBlock() internal { require(_getStakingDataContract().updateTotalSupplyForDayAndBlock(totalSupply())); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal override { require(_getStakingDataContract().removeStake(amount, sender)); require(_getStakingDataContract().createStake(amount, recipient)); super._transfer(sender, recipient, amount); emit TransferITV( sender, recipient, amount, balanceOf(sender), _getStakingDataContract().getAccountStakingTotal(sender), balanceOf(recipient), _getStakingDataContract().getAccountStakingTotal(recipient)); _updateTotalSupplyForBlock(); } /** * Private validation functions */ function _valueCheck(uint value) internal pure { require(value != 0, "!"); } function _onlyAdmin() internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require( vaultFactory.isAddressAdmin(_msgSender()), "NTA" ); } function _validBurnSender() internal view { require( _BurnDataAddress == _msgSender(), "NTB" ); } function _isTrustedSigner(address signer) internal view { ITrustVaultFactory vaultFactory = ITrustVaultFactory(_iTrustFactoryAddress); require( vaultFactory.isTrustedSignerAddress(signer), "NTS" ); } function _nonReentrant() internal view { require(_Locked == FALSE); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { using SafeMathUpgradeable for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../GSN/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./UpgradeableProxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address admin_, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(admin_); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // solhint-disable-next-line avoid-low-level-calls (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @dev Returns the current admin. */ function _admin() internal view returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal override virtual { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success,) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal override view returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
revoke admin/
function revokeAdminAddress(address newAddress) external onlyAdmin { require(msg.sender != newAddress); _AdminList[newAddress] = false; }
11,785,386
pragma solidity ^0.5.16; //0.4.24; import "../coffeecore/Ownable.sol"; import "../coffeeaccesscontrol/FarmerRole.sol"; import "../coffeeaccesscontrol/DistributorRole.sol"; import "../coffeeaccesscontrol/RetailerRole.sol"; import "../coffeeaccesscontrol/ConsumerRole.sol"; // Define a contract 'Supplychain' contract SupplyChain is FarmerRole, DistributorRole, RetailerRole, ConsumerRole { // Define 'owner' address owner; // Define ItemCount uint itemCount = 0; // Define a variable called 'sku' for Stock Keeping Unit (SKU) uint sku = 0; // Define a public mapping 'items' that maps the UPC to an Item. mapping (uint => Item) items; // All upcs used in items uint[] usedUpcsInItems; // Track the items harvested by farmer //mapping (address => uint[]) itemCountHarvestedByFarmer; mapping (address => uint[]) itemHarvestedByFarmer; // Define a public mapping 'itemsHistory' that maps the UPC to an array of TxHash, // that track its journey through the supply chain -- to be sent from DApp. mapping (uint => string[]) itemsHistory; // Define enum 'State' with the following values: enum State { Harvested, // 0 Processed, // 1 Packed, // 2 ForSale, // 3 Sold, // 4 Shipped, // 5 Received, // 6 Purchased // 7 } State constant defaultState = State.Harvested; // Define a struct 'Item' with the following fields: struct Item { uint sku; // Stock Keeping Unit (SKU) uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages address originFarmerID; // Metamask-Ethereum address of the Farmer string originFarmName; // Farmer Name string originFarmInformation; // Farmer Information string originFarmLatitude; // Farm Latitude string originFarmLongitude; // Farm Longitude uint productID; // Product ID potentially a combination of upc + sku string productNotes; // Product Notes uint productPrice; // Product Price State itemState; // Product State as represented in the enum above address distributorID; // Metamask-Ethereum address of the Distributor address retailerID; // Metamask-Ethereum address of the Retailer address payable consumerID; // Metamask-Ethereum address of the Consumer } // Define 8 events with the same 8 state values and accept 'upc' as input argument event Harvested(uint upc); event Processed(uint upc); event Packed(uint upc); event ForSale(uint upc); event Sold(uint upc); event Shipped(uint upc); event Received(uint upc); event Purchased(uint upc); event FarmerResult(bool value); // Define a modifer that checks to see if msg.sender == owner of the contract //TODO; Commented out to avoid conflits with Ownable modifier onlyOwner() { require(msg.sender == owner); _; } // Define a modifier that verifies the owner of the item is the address specified in the second argument. modifier verifyRightCaller(uint _upc, address _address) { require (items[_upc].ownerID == _address); _; } // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint _upc) { _; uint _price = items[_upc].productPrice; uint amountToReturn = msg.value - _price; items[_upc].consumerID.transfer(amountToReturn); } // Define a modifier that checks if an item.state of a upc is Harvested modifier harvested(uint _upc) { require(items[_upc].itemState == State.Harvested); _; } // Define a modifier that checks if an item.state of a upc is Processed modifier processed(uint _upc) { require(items[_upc].itemState == State.Processed); _; } // Define a modifier that checks if an item.state of a upc is Packed modifier packed(uint _upc) { require(items[_upc].itemState == State.Packed); _; } // Define a modifier that checks if an item.state of a upc is ForSale modifier forSale(uint _upc) { require(items[_upc].itemState == State.ForSale); _; } // Define a modifier that checks if an item.state of a upc is Sold modifier sold(uint _upc) { require(items[_upc].itemState == State.Sold); _; } // Define a modifier that checks if an item.state of a upc is Shipped modifier shipped(uint _upc) { require(items[_upc].itemState == State.Shipped); _; } // Define a modifier that checks if an item.state of a upc is Received modifier received(uint _upc) { require(items[_upc].itemState == State.Received); _; } // Define a modifier that checks if an item.state of a upc is Purchased modifier purchased(uint _upc) { require(items[_upc].itemState == State.Purchased); _; } // In the constructor set 'owner' to the address that instantiated the contract // and set 'sku' to 1 constructor() public payable { owner = msg.sender; sku = 1; } // Define a function 'kill' if required function kill() public { if (msg.sender == owner) { selfdestruct(msg.sender); } } // Define a function 'harvestItem' that allows a farmer to mark an item 'Harvested' function harvestItem(uint _upc, address _originFarmerID, string memory _originFarmName, string memory _originFarmInformation, string memory _originFarmLatitude, string memory _originFarmLongitude, string memory _productNotes) public //Only registered farmers can harvest items. onlyFarmer() { // Add the new item as part of Harvest //items[sku] = Item(sku, items[_upc] = Item(sku, _upc, _originFarmerID, //The first owner is the FARMER. _originFarmerID, _originFarmName, _originFarmInformation, _originFarmLatitude, _originFarmLongitude, sku + _upc, _productNotes, 0, defaultState, address(0x0), address(0x0), address(0x0) ); // Track the items harvested by this farmer itemHarvestedByFarmer[_originFarmerID].push(_upc); // Increment sku sku = sku + 1; // Increment item count itemCount = itemCount + 1; // Add to the upcs list usedUpcsInItems.push(_upc); // Emit the appropriate event emit Harvested(_upc); } // Define a function 'processtItem' that allows a farmer to mark an item 'Processed' //function processItem(uint _upc) harvested(_upc) verifyCaller(items[_upc].originFarmerID) public function processItem(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage harvested(_upc) // Call modifier to verify caller of this function //verifyRightCaller(_upc, items[_upc].originFarmerID) onlyFarmer() { // Update the appropriate fields items[_upc].itemState = State.Processed; // Emit the appropriate event emit Processed(_upc); } // Define a function 'packItem' that allows a farmer to mark an item 'Packed' function packItem(uint _upc) processed(_upc) public // Call modifier to check if upc has passed previous supply chain stage processed(_upc) // Call modifier to verify caller of this function onlyFarmer() //verifyRightCaller(_upc, items[_upc].originFarmerID) { // Update the appropriate fields items[_upc].itemState = State.Packed; // Emit the appropriate event emit Packed(_upc); } // Define a function 'sellItem' that allows a farmer to mark an item 'ForSale' function sellItem(uint _upc, uint _price) public // Call modifier to check if upc has passed previous supply chain stage packed(_upc) // Call modifier to verify caller of this function onlyFarmer() //verifyRightCaller(_upc, items[_upc].originFarmerID) { // Update the appropriate fields items[_upc].itemState = State.ForSale; items[_upc].productPrice = _price; // Emit the appropriate event emit ForSale(_upc); } // Define a function 'buyItem' that allows the disributor to mark an item 'Sold' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer function buyItem(uint _upc) public payable // Call modifier to check if upc has passed previous supply chain stage forSale(_upc) // Call modifer to check if buyer has paid enough paidEnough(items[_upc].productPrice) // Call modifer to send any excess ether back to buyer (cannot be done in the signature) checkValue(_upc) //Make sure a distributor can only call this onlyDistributor() { // Update the appropriate fields - ownerID, distributorID, itemState address buyerAddress = msg.sender; items[_upc].ownerID = buyerAddress; items[_upc].distributorID = buyerAddress; items[_upc].itemState = State.Sold; // emit the appropriate event emit Sold(_upc); } // Define a function 'shipItem' that allows the distributor to mark an item 'Shipped' // Use the above modifers to check if the item is sold function shipItem(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage sold(_upc) // Call modifier to verify caller of this function //verifyRightCaller(_upc, items[_upc].distributorID) onlyDistributor() { // Update the appropriate fields items[_upc].itemState = State.Shipped; // Emit the appropriate event emit Shipped(_upc); } // Define a function 'receiveItem' that allows the retailer to mark an item 'Received' // Use the above modifiers to check if the item is shipped function receiveItem(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage shipped(_upc) // Access Control List enforced by calling Smart Contract / DApp //verifyRightCaller(_upc, items[_upc].retailer) onlyRetailer() { // Update the appropriate fields - ownerID, retailerID, itemState items[_upc].ownerID = msg.sender; items[_upc].retailerID = msg.sender; items[_upc].itemState = State.Received; // Emit the appropriate event emit Received(_upc); } // Define a function 'purchaseItem' that allows the consumer to mark an item 'Purchased' // Use the above modifiers to check if the item is received function purchaseItem(uint _upc) public // Call modifier to check if upc has passed previous supply chain stage received(_upc) // Access Control List enforced by calling Smart Contract / DApp //verifyRightCaller(_upc, items[_upc].retailerID) onlyConsumer() { // Update the appropriate fields - ownerID, consumerID, itemState items[_upc].ownerID = msg.sender; items[_upc].consumerID = msg.sender; items[_upc].itemState = State.Purchased; // Emit the appropriate event emit Purchased(_upc); } // Define a function 'fetchItemBufferOne' that fetches the data function fetchItemBufferOne(uint _upc) public view returns ( uint itemSKU, uint itemUPC, address ownerID, address originFarmerID, string memory originFarmName, string memory originFarmInformation, string memory originFarmLat, string memory originFarmLong ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.ownerID, item.originFarmerID, item.originFarmName, item.originFarmInformation, item.originFarmLatitude, item.originFarmLongitude ); } // Define a function 'fetchItemBufferTwo' that fetches the data function fetchItemBufferTwo(uint _upc) public view returns ( uint itemSKU, uint itemUPC, uint productID, string memory productNotes, uint productPrice, uint itemState, address distributorID, address retailerID, address payable consumerID ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.productID, item.productNotes, item.productPrice, uint(item.itemState), item.distributorID, item.retailerID, item.consumerID ); } function verifyCallerFc(address _address) public view returns (bool) { if (msg.sender == _address) { return true; } else { return false; } } function getSender() public view returns (address) { return msg.sender; } function isItemForSale(uint _upc) public view returns (bool) { return (items[_upc].itemState == State.ForSale); } function verifyCallerForUpc(uint _upc, address _address) public view returns (bool) { return (items[_upc].ownerID == _address); } function getOwnerByUpc(uint _upc) public view returns (address) { return items[_upc].ownerID; } function getStateByUpc(uint _upc) public view returns (uint) { return uint(items[_upc].itemState); } function requireRegistration(address _address) public view returns (bool) { if (isFarmer(_address)) { return false; } else if (isDistributor(_address)) { return false; } else if (isRetailer(_address)) { return false; } else if (isConsumer(_address)) { return false; } else { return true; } } function getHarvestedItemsCount(address _address) public view returns (uint) { return itemHarvestedByFarmer[_address].length; } function getHarvestedItemsByFarmer(address _address) public view returns (uint[] memory) { uint[] memory copiedIndexes = new uint[](itemHarvestedByFarmer[_address].length); for (uint i = 0; i < itemHarvestedByFarmer[_address].length; i++ ) { copiedIndexes[i] = itemHarvestedByFarmer[_address][i]; } return copiedIndexes; } function getItemListOnSaleCount() public view returns (uint) { uint itemsForSale = 0; for (uint i=0;i<itemCount;i++) { uint upc = usedUpcsInItems[i]; Item memory item = items[upc]; if (item.itemState == State.ForSale) { itemsForSale = itemsForSale + 1; } } return itemsForSale; } function getItemCountByRole() internal view returns (uint) { uint itemCountByRole = 0; for (uint i=0;i<itemCount;i++) { uint upc = usedUpcsInItems[i]; Item memory item = items[upc]; if (isDistributor(msg.sender)) { if (item.itemState == State.ForSale) { itemCountByRole++; } else if (item.itemState == State.Sold) { itemCountByRole++; } } else if (isRetailer(msg.sender)) { if (item.itemState == State.Shipped) { itemCountByRole++; } else if (item.itemState == State.Received) { itemCountByRole++; } } else if (isConsumer(msg.sender)) { if (item.itemState == State.Received) { itemCountByRole++; } else if (item.itemState == State.Purchased) { itemCountByRole++; } } } return itemCountByRole; } /** * Retrieve all the items in certain state depending on the role of the caller. * (DISTRIBUTOR,RETAILER,CONSUMER) */ function getItemsByRole() public view returns (uint[] memory) { uint itemCountByRole = getItemCountByRole(); uint[] memory selectedItems = new uint[](itemCountByRole); uint selectedItemIndex = 0; for (uint i=0;i<itemCount;i++) { uint upc = usedUpcsInItems[i]; Item memory item = items[upc]; if (isDistributor(msg.sender)) { if (item.itemState == State.ForSale) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } else if (item.itemState == State.Sold) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } } else if (isRetailer(msg.sender)) { if (item.itemState == State.Shipped) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } else if (item.itemState == State.Received) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } } else if (isConsumer(msg.sender)) { if (item.itemState == State.Received) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } else if (item.itemState == State.Purchased) { selectedItems[selectedItemIndex] = item.upc; selectedItemIndex++; } } } return selectedItems; } function getNextSku() public view returns (uint) { return sku; } function getOwner() public view returns (address) { return owner; } function getItemList() public view returns (uint[] memory) { uint[] memory copiedIndexes = new uint[](itemCount); for (uint i = 0; i < itemCount; i++ ) { copiedIndexes[i] = usedUpcsInItems[i]; } return copiedIndexes; } function getItemCount() public view returns (uint) { return itemCount; } }
Define a function 'fetchItemBufferTwo' that fetches the data
function fetchItemBufferTwo(uint _upc) public view returns ( uint itemSKU, uint itemUPC, uint productID, string memory productNotes, uint productPrice, uint itemState, address distributorID, address retailerID, address payable consumerID ) { Item memory item = items[_upc]; return ( item.sku, item.upc, item.productID, item.productNotes, item.productPrice, uint(item.itemState), item.distributorID, item.retailerID, item.consumerID ); }
5,515,926
./full_match/43113/0x1f4ca141e11d9abedbB52f0dfB89DB1E6f159aA8/sources/contracts/Management.sol
Transaction Wrapper for Pay Salary
function payIndividualWrapper(address payable addr, uint256 payment) public onlyOwner returns(bool){ transactions.push(Transaction({ to: addr, value: payment, type_:0, executed:false, nConfirmations:0, aboutTransaction:"Paying Individual" })); return true; }
7,176,918
pragma solidity ^0.4.18; import "./Owned.sol"; contract SellItPayment is Owned { uint private _offersCount; /////////////////////// // GENERAL STRUCTURE // /////////////////////// struct Offer { address seller; address buyer; string title; string description; uint price; string addressForShipment; bool accepted; bool shipped; bool confirmed; bool canceled; } mapping(uint => Offer) offers; mapping(address => uint[]) sellingOffersByAddr; mapping(address => uint[]) buyingOffersByAddr; mapping(address => uint) blockedInContractEth; mapping(address => uint) withdrawableFunds; //////////// // EVENTS // //////////// event DepositReceived(address indexed _from, uint _amount, uint _timestamp); event WithdrawalEth(address indexed _to, uint _amount, uint _timestamp); event OfferPublished(address indexed _seller, uint indexed _offerIndex); event OfferAccepted(address indexed _buyer, uint indexed _offerIndex); event OfferCanceledBySeller(address indexed _buyer, uint indexed _offerIndex); event OfferCanceledByBuyer(address indexed _buyer, uint indexed _offerIndex); event OfferConfirmed(address indexed _buyer, uint indexed _offerIndex); event OfferShipped(address indexed _seller, uint indexed _offerIndex); event TransactionConfirmed(address _from, address _to, uint _amount); ////////////// // MODIFERS // ////////////// modifier existing(uint index) { assert(_offersCount > 0); assert(index > 0); assert(index <= _offersCount); _; } modifier isSeller(uint index) { assert(msg.sender == offers[index].seller); _; } modifier isBuyer(uint index) { assert(msg.sender == offers[index].buyer); _; } //////////////////////// // MAIN FUNCTIONALITY // //////////////////////// // Constructor. Init offers count with 0 function SellItPayment() public { _offersCount = 0; } // Deposit some amount of eth function Deposit() public payable { require(withdrawableFunds[msg.sender] + msg.value >= withdrawableFunds[msg.sender]); withdrawableFunds[msg.sender] += msg.value; DepositReceived(msg.sender, msg.value, now); } // Withraw not blocked funds function Withdraw(uint amount) public { require(withdrawableFunds[msg.sender] - amount >= 0); require(withdrawableFunds[msg.sender] - amount <= withdrawableFunds[msg.sender]); withdrawableFunds[msg.sender] -= amount; msg.sender.transfer(amount); WithdrawalEth(msg.sender, amount, now); } // Everyone can create offer function PublishOffer(uint price, string title, string description) public { _offersCount += 1; Offer storage offer = offers[_offersCount]; offer.seller = msg.sender; offer.price = price; offer.title = title; offer.description = description; offer.shipped = false; sellingOffersByAddr[msg.sender].push(_offersCount); OfferPublished(msg.sender, _offersCount); } // Accept existing offer from user which is not seller. Buyer make payment to system or take from his deposit for the announced price. function AcceptOffer(uint offerIndex, string addressForShipment) public existing(offerIndex) { Offer storage offer = offers[offerIndex]; require(msg.sender != offer.seller); // check if someone has already accepted the offer require(offer.buyer == address(0)); // check if offer is not already canceled require(offer.canceled == false); // check is the transferred amount equal or higher to the price require(withdrawableFunds[msg.sender] >= offer.price); // transfer eth from withdrawable to blocked funds withdrawableFunds[msg.sender] -= offer.price; blockedInContractEth[msg.sender] += offer.price; offer.buyer = msg.sender; offer.accepted = true; offer.confirmed = false; offer.addressForShipment = addressForShipment; buyingOffersByAddr[msg.sender].push(offerIndex); OfferAccepted(msg.sender, offerIndex); } // Seller can cancel existing offer if this offer is not confirmed yet. System allow buyer to withdraw the amount. function CancelOfferBySeller(uint offerIndex) public existing(offerIndex) { Offer storage offer = offers[offerIndex]; require(msg.sender == offer.seller); // check if offer is not already confirmed require(offer.confirmed == false); // check if offer is not already canceled require(offer.canceled == false); offer.canceled = true; RefundBuyer(offer.buyer, offer.price); OfferCanceledBySeller(msg.sender, offerIndex); } // Buyer can cancel accepted offer if is accepted by him and offer is not shipped or confirmed yet. System will refund buyer. function CancelOfferByBuyer(uint offerIndex) public existing(offerIndex) { Offer storage offer = offers[offerIndex]; require(msg.sender == offer.buyer); // check if offer is not already shipped require(offer.shipped == false); // check if offer is not already confirmed require(offer.confirmed == false); // check if offer is not already canceled require(offer.canceled == false); offer.canceled = true; RefundBuyer(offer.buyer, offer.price); OfferCanceledByBuyer(msg.sender, offerIndex); } // Buyer confirm receiving of offered item or service and system make payment to seller. function ConfirmOffer(uint offerIndex) public existing(offerIndex) isBuyer(offerIndex) { Offer storage offer = offers[offerIndex]; // check if offer is not already confirmed require(offer.confirmed == false); // check if offer is not already canceled require(offer.canceled == false); offer.confirmed = true; PayToSeller(offer.buyer, offer.seller, offer.price); OfferConfirmed(msg.sender, offerIndex); } // Seller can confirm shippment function ConfirmShipping(uint offerIndex) public existing(offerIndex) isSeller(offerIndex) { Offer storage offer = offers[offerIndex]; require(offer.confirmed == false); require(offer.canceled == false); offer.shipped = true; OfferShipped(msg.sender, offerIndex); } // Only seller and buyer can get shipment address function GetShipmentAddress(uint offerIndex) public view existing(offerIndex) returns (string) { Offer storage offer = offers[offerIndex]; require(msg.sender == offer.seller || msg.sender == offer.buyer); return offer.addressForShipment; } // Only seller and buyer can see offer status function GetOfferStatus(uint offerIndex) public view existing(offerIndex) returns (bool, bool, bool){ Offer storage offer = offers[offerIndex]; require(msg.sender == offer.seller || msg.sender == offer.buyer); return (offer.shipped, offer.confirmed, offer.canceled); } // Return offer info by offer id function GetOfferById(uint offerIndex) public view existing(offerIndex) returns (uint, string, string, uint, bool) { Offer storage offer = offers[offerIndex]; return (offerIndex, offer.title, offer.description, offer.price, offer.accepted); } // Return selling offers of user function GetSellingOffers() public view returns (uint[]) { return sellingOffersByAddr[msg.sender]; } // Return buying offers of user function GetBuyingOffers() public view returns (uint[]) { return buyingOffersByAddr[msg.sender]; } // User can check blocked balances function GetBlockedBalance() public view returns (uint) { return blockedInContractEth[msg.sender]; } // User can check withdrawable balances function GetDepositBalance() public view returns (uint) { return withdrawableFunds[msg.sender]; } // Helper function to check offers total count function GetTotalNumberOfOffers() public view returns (uint) { return _offersCount; } // Unblock amount of eth for canceled order function RefundBuyer(address buyer, uint amount) private { withdrawableFunds[buyer] += amount; blockedInContractEth[buyer] -= amount; } // Transfer amount of eth from buyer to seller function PayToSeller(address from, address to, uint amount) private { blockedInContractEth[from] -= amount; withdrawableFunds[to] += amount; TransactionConfirmed(from, to, amount); } // Serialization of main structure function serializeOffer(uint offerIndex) private view returns (bytes data) { Offer storage offer = offers[offerIndex]; uint _size = 4 + bytes(offer.title).length; bytes memory _data = new bytes(_size); uint counter = 0; for (uint i = 0; i < 4; i++) { data[counter] = byte(offerIndex >> (8 * i) & uint32(255)); counter++; } for (i = 0; i < bytes(offer.title).length; i++) { _data[counter] = bytes(offer.title)[i]; counter++; } return (_data); } }
Seller can cancel existing offer if this offer is not confirmed yet. System allow buyer to withdraw the amount. check if offer is not already confirmed check if offer is not already canceled
function CancelOfferBySeller(uint offerIndex) public existing(offerIndex) { Offer storage offer = offers[offerIndex]; require(msg.sender == offer.seller); require(offer.confirmed == false); require(offer.canceled == false); offer.canceled = true; RefundBuyer(offer.buyer, offer.price); OfferCanceledBySeller(msg.sender, offerIndex); }
2,472,444
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // Contracts import { CONTROLLER, ADMIN, EXCHANGE_RATE_FACTOR, ONE_HUNDRED_PERCENT } from "./data.sol"; import { ITTokenStrategy } from "./strategies/ITTokenStrategy.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Utils import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // Interfaces import { ITToken } from "./ITToken.sol"; import { ICErc20 } from "../../shared/interfaces/ICErc20.sol"; // Libraries import { IERC20, SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import { RolesLib } from "../../contexts2/access-control/roles/RolesLib.sol"; import { NumbersLib } from "../../shared/libraries/NumbersLib.sol"; // Storage import "./storage.sol" as Storage; /** * @notice This contract represents a lending pool for an asset within Teller protocol. * @author [email protected] */ contract TToken_V1 is ITToken { function() pure returns (Storage.Store storage) private constant s = Storage.store; /* Modifiers */ /** * @notice Checks if the LP is restricted or has the CONTROLLER role. * * The LP being restricted means that only the Teller protocol may * lend/borrow funds. */ modifier notRestricted { require( !s().restricted || RolesLib.hasRole(CONTROLLER, _msgSender()), "Teller: platform restricted" ); _; } /* Public Functions */ /** * @notice it returns the decimal places of the respective TToken * @return decimals of the token */ function decimals() public view override returns (uint8) { return s().decimals; } /** * @notice The token that is the underlying assets for this Teller token. * @return ERC20 token that is the underl */ function underlying() public view override returns (ERC20) { return s().underlying; } /** * @notice The balance of an {account} denoted in underlying value. * @param account Address to calculate the underlying balance. * @return balance_ the balance of the account */ function balanceOfUnderlying(address account) public override returns (uint256) { return _valueInUnderlying(balanceOf(account), exchangeRate()); } /** * @notice It calculates the current exchange rate for a whole Teller Token based of the underlying token balance. * @return rate_ The current exchange rate. */ function exchangeRate() public override returns (uint256 rate_) { if (totalSupply() == 0) { return EXCHANGE_RATE_FACTOR; } rate_ = (currentTVL() * EXCHANGE_RATE_FACTOR) / totalSupply(); } /** * @notice It calculates the total supply of the underlying asset. * @return totalSupply_ the total supply denoted in the underlying asset. */ function totalUnderlyingSupply() public override returns (uint256) { bytes memory data = _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.totalUnderlyingSupply.selector ) ); return abi.decode(data, (uint256)); } /** * @notice It calculates the market state values across a given markets. * @notice Returns values that represent the global state across the market. * @return totalSupplied Total amount of the underlying asset supplied. * @return totalBorrowed Total amount borrowed through loans. * @return totalRepaid The total amount repaid till the current timestamp. * @return totalInterestRepaid The total amount interest repaid till the current timestamp. * @return totalOnLoan Total amount currently deployed in loans. */ function getMarketState() external override returns ( uint256 totalSupplied, uint256 totalBorrowed, uint256 totalRepaid, uint256 totalInterestRepaid, uint256 totalOnLoan ) { totalSupplied = totalUnderlyingSupply(); totalBorrowed = s().totalBorrowed; totalRepaid = s().totalRepaid; totalInterestRepaid = s().totalInterestRepaid; totalOnLoan = totalBorrowed - totalRepaid; } /** * @notice Calculates the current Total Value Locked, denoted in the underlying asset, in the Teller Token pool. * @return tvl_ The value locked in the pool. * * Note: This value includes the amount that is on loan (including ones that were sent to EOAs). */ function currentTVL() public override returns (uint256 tvl_) { tvl_ += totalUnderlyingSupply(); tvl_ += s().totalBorrowed; tvl_ -= s().totalRepaid; } /** * @notice It validates whether supply to debt (StD) ratio is valid including the loan amount. * @param newLoanAmount the new loan amount to consider the StD ratio. * @return ratio_ Whether debt ratio for lending pool is valid. */ function debtRatioFor(uint256 newLoanAmount) external override returns (uint16 ratio_) { uint256 onLoan = s().totalBorrowed - s().totalRepaid; uint256 supplied = totalUnderlyingSupply() + onLoan; if (supplied > 0) { ratio_ = NumbersLib.ratioOf(onLoan + newLoanAmount, supplied); } } /** * @notice Called by the Teller Diamond contract when a loan has been taken out and requires funds. * @param recipient The account to send the funds to. * @param amount Funds requested to fulfil the loan. */ function fundLoan(address recipient, uint256 amount) external override authorized(CONTROLLER, _msgSender()) { // If TToken is not holding enough funds to cover the loan, call the strategy to try to withdraw uint256 balance = s().underlying.balanceOf(address(this)); if (balance < amount) { _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, amount - balance ) ); } // Increase total borrowed amount s().totalBorrowed += amount; // Transfer tokens to recipient SafeERC20.safeTransfer(s().underlying, recipient, amount); } /** * @notice Called by the Teller Diamond contract when a loan has been repaid. * @param amount Funds deposited back into the pool to repay the principal amount of a loan. * @param interestAmount Interest value paid into the pool from a loan. */ function repayLoan(uint256 amount, uint256 interestAmount) external override authorized(CONTROLLER, _msgSender()) { s().totalRepaid += amount; s().totalInterestRepaid += interestAmount; } /** * @notice Deposit underlying token amount into LP and mint tokens. * @param amount The amount of underlying tokens to use to mint. * @return Amount of TTokens minted. */ function mint(uint256 amount) external override notRestricted returns (uint256) { require(amount > 0, "Teller: cannot mint 0"); require( amount <= s().underlying.balanceOf(_msgSender()), "Teller: insufficient underlying" ); // Calculate amount of tokens to mint uint256 mintAmount = _valueOfUnderlying(amount, exchangeRate()); // Transfer tokens from lender SafeERC20.safeTransferFrom( s().underlying, _msgSender(), address(this), amount ); // Mint Teller token value of underlying _mint(_msgSender(), mintAmount); emit Mint(_msgSender(), mintAmount, amount); return mintAmount; } /** * @notice Redeem supplied Teller token underlying value. * @param amount The amount of Teller tokens to redeem. */ function redeem(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Accrue interest and calculate exchange rate uint256 underlyingAmount = _valueInUnderlying(amount, exchangeRate()); require( underlyingAmount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Burn Teller Tokens and transfer underlying _redeem(amount, underlyingAmount); } /** * @notice Redeem supplied underlying value. * @param amount The amount of underlying tokens to redeem. */ function redeemUnderlying(uint256 amount) external override { require(amount > 0, "Teller: cannot withdraw 0"); require( amount <= totalUnderlyingSupply(), "Teller: redeem ttoken lp not enough supply" ); // Accrue interest and calculate exchange rate uint256 rate = exchangeRate(); uint256 tokenValue = _valueOfUnderlying(amount, rate); // Make sure sender has adequate balance require( tokenValue <= balanceOf(_msgSender()), "Teller: redeem amount exceeds balance" ); // Burn Teller Tokens and transfer underlying _redeem(tokenValue, amount); } /** * @dev Redeem an {amount} of Teller Tokens and transfers {underlyingAmount} to the caller. * @param amount Total amount of Teller Tokens to burn. * @param underlyingAmount Total amount of underlying asset tokens to transfer to caller. * * This function should only be called by {redeem} and {redeemUnderlying} after the exchange * rate and both token values have been calculated to use. */ function _redeem(uint256 amount, uint256 underlyingAmount) internal { // Burn Teller tokens _burn(_msgSender(), amount); // Make sure enough funds are available to redeem _delegateStrategy( abi.encodeWithSelector( ITTokenStrategy.withdraw.selector, underlyingAmount ) ); // Transfer funds back to lender SafeERC20.safeTransfer(s().underlying, _msgSender(), underlyingAmount); emit Redeem(_msgSender(), amount, underlyingAmount); } /** * @notice Rebalances the funds controlled by Teller Token according to the current strategy. * * See {TTokenStrategy}. */ function rebalance() public override { _delegateStrategy( abi.encodeWithSelector(ITTokenStrategy.rebalance.selector) ); } /** * @notice Sets a new strategy to use for balancing funds. * @param strategy Address to the new strategy contract. Must implement the {ITTokenStrategy} interface. * @param initData Optional data to initialize the strategy. * * Requirements: * - Sender must have ADMIN role */ function setStrategy(address strategy, bytes calldata initData) external override authorized(ADMIN, _msgSender()) { require( ERC165Checker.supportsInterface( strategy, type(ITTokenStrategy).interfaceId ), "Teller: strategy does not support ITTokenStrategy" ); s().strategy = strategy; if (initData.length > 0) { _delegateStrategy(initData); } } /** * @notice Gets the strategy used for balancing funds. * @return address of the strategy contract */ function getStrategy() external view override returns (address) { return s().strategy; } /** * @notice Sets the restricted state of the platform. * @param state boolean value that resembles the platform's state */ function restrict(bool state) public override authorized(ADMIN, _msgSender()) { s().restricted = state; } /** * @notice it initializes the Teller Token * @param admin address of the admin to the respective Teller Token * @param underlying address of the ERC20 token */ function initialize(address admin, address underlying) external override initializer { require( Address.isContract(msg.sender), "Teller: controller not contract" ); require( Address.isContract(underlying), "Teller: underlying token not contract" ); RolesLib.grantRole(CONTROLLER, msg.sender); RolesLib.grantRole(ADMIN, admin); s().underlying = ERC20(underlying); __ERC20_init( string(abi.encodePacked("Teller ", s().underlying.name())), string(abi.encodePacked("t", s().underlying.symbol())) ); s().decimals = s().underlying.decimals(); // Platform restricted by default s().restricted = true; } /** * @notice it retrieves the value of the underlying token * @param amount the amount of tokens to calculate the value of * @param rate the exchangeRate() to divide with the amount * exchange_rate_factor * @return value_ the underlying value of the token amount */ function _valueOfUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * EXCHANGE_RATE_FACTOR) / rate; } /** * @notice it retrives the value in the underlying tokens * */ function _valueInUnderlying(uint256 amount, uint256 rate) internal pure returns (uint256 value_) { value_ = (amount * (rate)) / EXCHANGE_RATE_FACTOR; } /** * @notice Delegates data to call on the strategy contract. * @param callData Data to call the strategy contract with. * * Requirements: * - Sender must have ADMIN role */ function _delegateStrategy(bytes memory callData) internal returns (bytes memory) { return Address.functionDelegateCall(s().strategy, callData); } }
Called by the Teller Diamond contract when a loan has been repaid. amount Funds deposited back into the pool to repay the principal amount of a loan. interestAmount Interest value paid into the pool from a loan./
function repayLoan(uint256 amount, uint256 interestAmount) external override authorized(CONTROLLER, _msgSender()) { s().totalRepaid += amount; s().totalInterestRepaid += interestAmount; }
6,355,625
// 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-purchase}./ Check purchase amounts
function purchase(uint16 amount, bytes32 message, bytes calldata signature, string calldata nonce) external virtual override payable { _validatePurchaseRestrictions(); require(amount <= purchaseRemaining() && (transactionLimit == 0 || amount <= transactionLimit), "Too many requested"); uint256 balance; if (!transferLocked && (presalePurchaseLimit > 0 || purchaseLimit > 0)) { balance = _mintCount[msg.sender]; 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; require(purchaseLimit == 0 || amount <= (purchaseLimit - balance), "Too many requested"); _validatePrice(amount); } _validatePurchaseRequest(message, signature, nonce); _mint(msg.sender, amount, presale); }
10,079,391
// SPDX-License-Identifier: MIT pragma solidity = 0.5.16; import "./BookingCarpooling.sol"; import "./CarpoolingFactoryAbstract.sol"; // ManagingServices has every functions that interact with services, or modify pending and booked services inside the smart contract. contract ManagingServices is BookingCarpooling { // simplification: 1 service has 1 address, no option yet. // mapping(address => mapping (address => uint256)) public pendingUserService; // {user: {service: amount}, ...} // mapping(address => mapping (address => uint256)) public userService; // {user: {service: amount}, ...} // mapping(address => address[]) public userServices; // {user: [service, ...], ...} // address[] public mandatoryServices; // [service, ...] , e.g: owner wants passenger with idCheck & insurance... event SettleServiceToSomeone(address service, address passenger, address to, uint256 amountService); event ValidateService(address user, address service, bool validation); // ---> Services - User // The passenger/creator asks to add the service paying msg.value, or he cancels the ask and he is refunded function askService(address service, bool cancel) payable public { require(msg.value >= 0, "price service must be >= 0"); if(cancel==true && pendingUserService[msg.sender][service] > 0){ bookings[msg.sender].amountRefunded += pendingUserService[msg.sender][service]; pendingUserService[msg.sender][service] = 0; }else if(cancel==false){ pendingUserService[msg.sender][service] += msg.value; userServices[msg.sender].push(service); } askServiceUsingFactory(service, carpoolingId, msg.sender, msg.value, cancel); } // user emits a notification for insurance to get insured, using factory contract to facilitate insurance listening. function askServiceUsingFactory(address service, uint64 carpoolingId, address user, uint256 amount, bool cancel) private { CarpoolingFactoryAbstract carpoolingFactoryAbs = CarpoolingFactoryAbstract(carpoolingFactoryAddress); carpoolingFactoryAbs.setPendingServiceCarpoolingUserOption(service, carpoolingId, user, amount, cancel); } // service validates the pending query from customer function validateService(address user, bool validation) public { require(pendingUserService[user][msg.sender] > 0, "there are no pending query from this user to this service"); if(validation==true){ userService[user][msg.sender] += pendingUserService[user][msg.sender]; }else{ bookings[user].amountRefunded += pendingUserService[user][msg.sender]; } delete pendingUserService[user][msg.sender]; emit ValidateService(user, msg.sender, validation); } // it settles the service, if no issue token are sent to the service, else to the passenger or the conflictOwner function settleService(address service, address passenger, address to) internal { uint256 amountService = userService[passenger][service]; userService[passenger][service] = 0; bookings[to].amountRefunded += amountService; emit SettleServiceToSomeone(service, passenger, to, amountService); } function settleServices(address passenger, address to) internal { // If "to" == passenger address, function is like refund passenger // Else If "to" == ownerConflict, function will send token to ownerConflict, which has to finalize the paiement // else "to" is empty and it meant the service will be paid address _initialTo = to; for(uint8 j; j < userServices[passenger].length; j++){ address service = userServices[passenger][j]; if (_initialTo == address(0)){ to = service; } settleService(service, passenger, to); } } // ---> Mandatory services function addMandatoryService(address service) public ownerOnly { // in VF, modify mandatoryServices to allow more services, i.g: having insurance company, and allowing many of them... // Caution, the service must be in the safe repository. VF -> update mandatoryServices.push(service); } function getMandatoryService(uint8 index) view public returns(address) { return mandatoryServices[index]; } function checkMandatoryService(address passenger) view public returns(bool){ // Check that a passenger has every mandatory service for(uint8 i; i < mandatoryServices.length; i++){ if (userService[passenger][mandatoryServices[i]] == 0){ return false; } } return true; } }
user emits a notification for insurance to get insured, using factory contract to facilitate insurance listening.
function askServiceUsingFactory(address service, uint64 carpoolingId, address user, uint256 amount, bool cancel) private { CarpoolingFactoryAbstract carpoolingFactoryAbs = CarpoolingFactoryAbstract(carpoolingFactoryAddress); carpoolingFactoryAbs.setPendingServiceCarpoolingUserOption(service, carpoolingId, user, amount, cancel); }
12,951,335
pragma solidity ^0.5.2; import "../ethereum-api/oraclizeAPI_0.5.sol"; import "../openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "../openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../solidity-stringutils/src/strings.sol"; contract EthorseDerby is usingOraclize, Pausable, Ownable { using SafeMath for uint256; using strings for *; uint256 constant PRECISION = 1000000; /// @dev events event NewRace(uint256 race_id); event RaceEnded(uint256 race_id, bool btc_won, bool ltc_won, bool eth_won); event RaceRefunded(uint256 race_id); event BetClaimed(uint256 race_id, address player, uint256 amount); event BetPlaced(uint256 race_id, uint256 amount_btc, uint256 amount_ltc, uint256 amount_eth); event OraclizeError(uint256 value); // config /// @dev time before a started roll has to reach the DONE state before it can be refunded uint256 public config_refund_delay = 2 days; /// @dev minimal allowed duration uint256 public config_min_duration = 5 minutes; /// @dev maximal allowed duration uint256 public config_max_duration = 1 days; /// @dev gas limit for price callbacks uint256 public config_gas_limit = 200000; // @dev gas price for transactions uint256 public config_gasprice = 20000000000 wei; /// @dev house edge uint256 public config_house_edge = 7500000; //7.5% /// @dev address to which send the house cut on withdrawal address payable config_cut_address = 0xA54741f7fE21689B59bD7eAcBf3A2947cd3f3BD4; /// @dev possible states of a race enum State {READY, WAITING_QUERY1, WAITING_QUERY2, DONE, REFUND} /// @dev oraclize queries for ETH,BTC and LTC with encrypted api key for cryptocompare string constant public query_string = "[URL] json(https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH,BTC,LTC&tsyms=USD&extraParams=EthorseDerby&sign=true&api_key=${[decrypt] BB+VUXuu1fOGP2zlf5DI7lO6QJkY+Q+NH3g+thd0G2hcpRAZyOussOYdZg8tbs8usk/BCmDug525UuF++FKxuIqfLA0A/JdvWnUHrZnM194wUH1UQc8VlQ8404iHc24twpY1R7R7I5RLVsNamEZftxjRXBpWqCU6j9BrJqlPGgbUbyZw4PSIiPW9ErAYJwccCg==}).[ETH,BTC,LTC].USD"; /// @dev current roll id uint256 public current_race = 0; /// @dev total amount of collected eth by the house uint256 public house; /// @dev describes a user bet struct Bet { //amount of wagered ETH in Wei uint256 amount_eth; uint256 amount_btc; uint256 amount_ltc; } /// @dev describes a roll struct Race { // oraclize query ids bytes32 query_price_start; bytes32 query_price_end; // query results uint256 result_price_start_ETH; uint256 result_price_start_BTC; uint256 result_price_start_LTC; uint256 result_price_end_ETH; uint256 result_price_end_BTC; uint256 result_price_end_LTC; uint256 race_duration; uint256 min_bet; uint256 start_time; uint256 betting_duration; uint256 btc_pool; uint256 ltc_pool; uint256 eth_pool; uint256 winners_total; State state; bool btc_won; bool ltc_won; bool eth_won; // mapping bettors to their bets on this roll mapping(address => Bet) bets; } mapping(uint256 => Race) public races; mapping(bytes32 => uint256) internal _query_to_race; /// @dev mapping to prevent processing twice the same query mapping(bytes32 => bool) internal _processed; /// @dev internal wallet mapping(address => uint256) public balanceOf; /** @dev init the contract */ constructor() public Pausable() Ownable() { //TLSNotary proof for URLs oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); } function newRace(uint256 race_duration, uint256 betting_duration, uint256 start_time, uint256 min_bet) public payable whenNotPaused() { require(duration >= config_min_duration && duration <= config_max_duration,"Invalid duration"); require(start_time > block.timestamp, "Races must start in the future"); require(min_bet > 0, "Must set a greater minimal bet"); require(betting_duration > 1 minutes, "Betting duration is too short"); //compute oraclize fees uint256 call_price = oraclize_getPrice("URL", config_gas_limit) * 2; //2 calls if(call_price >= msg.value) { //the caller didnt send enough for oraclize fees, just push an event and display the desired price emit OraclizeError(call_price); } else { //lets race! Race storage race = races[current_race]; //save the oraclize query indices for proof uint256 starts_in = start_time.add(betting_duration).sub(block.timestamp); uint256 ends_in = start_time.add(betting_duration).sub(block.timestamp).add(race_duration); race.query_price_start = oraclize_query(starts_in, "nested", query_string, config_gas_limit); race.query_price_end = oraclize_query(ends_in, "nested", query_string, config_gas_limit); race.state = State.WAITING_QUERY1; race.race_duration = race_duration; race.min_bet = min_bet; race.betting_duration = betting_duration; //save mappings to find the right race number associated with this query _query_to_race[race.query_price_start] = current_race; _query_to_race[race.query_price_end] = current_race; emit NewRace(current_race); _prepareNextRace(); } } /** @dev Allows to place a bet on a specific race @param race_id : race number @param is_up : true if the expected price change is positive, false overwise */ function placeBet(uint256 race_id, uint256 eth_bet, uint256 btc_bet, uint256 ltc_bet) external payable { uint256 total_bet = eth_bet.add(btc_bet).add(ltc_bet); uint256 betting_ends = race.start_time.add(race.betting_duration); uint256 house_edge = total_bet.mul(PRECISION).div(config_house_edge); house = house.add(house_edge); Race storage race = races[race_id]; require(race.State == WAITING_QUERY1, "Invalid race state"); require(block.timestamp >= race.start_time, "Not in betting phase"); require(block.timestamp <= betting_ends, "Not in betting phase"); require(msg.value == total_bet.add(house_edge), "Invalid payment"); require(total_bet >= race.min_bet, "Invalid bet"); Bet storage bet = race.bets[msg.sender]; bet.amount_btc = bet.amount_btc.add(btc_bet); bet.amount_ltc = bet.amount_ltc.add(ltc_bet); bet.amount_eth = bet.amount_eth.add(eth_bet); race.btc_pool = race.btc_pool.add(btc_bet); race.ltc_pool = race.ltc_pool.add(ltc_bet); race.eth_pool = race.eth_pool.add(eth_bet); emit BetPlaced(race_id, btc_bet, ltc_bet, eth_bet); } /** @dev Allows to claim the winnings from a race @param race_id Race number of the race to claim from */ function claim(uint256 race_id) external { Race storage race = races[race_id]; Bet storage bet = race.bets[msg.sender]; uint256 total_bet = bet.amount_btc.add(bet.amount_ltc).add(bet.amount_eth); //handle refunding if contract isnt in the DONE or REFUND state after the refund delay is passed //also prevent refunding not started rolls if(roll.state != State.DONE && roll.state != State.REFUND) { //allow refund after the delay has passed uint256 refund_time = race.start_time.add(race.betting_duration).add(config_refund_delay); if(block.timestamp >= refund_time) { race.state = State.REFUND; } } require(race.state == State.REFUND || race.state == State.DONE,"Cant claim from this race"); //handle payments from refunded rolls if(race.state == State.REFUND) { if(total_bet) { msg.sender.transfer(total_bet); //delete the bet from the bets mapping of this roll delete(race.bets[msg.sender]); } } else { uint256 wagered_winners_total = 0; if(race.btc_won) { wagered_winners_total = wagered_winners_total.add(bet.amount_btc); } if(race.ltc_won) { wagered_winners_total = wagered_winners_total.add(bet.amount_ltc); } if(race.eth_won) { wagered_winners_total = wagered_winners_total.add(bet.amount_eth); } uint256 to_pay = race.total_pool.mul(PRECISION).div(race.winners_total).mul(wagered_winners_total); msg.sender.transfer(to_pay); emit BetClaimed(round,msg.sender,to_pay); } } // the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public { require (msg.sender == oraclize_cbAddress(), "auth failed"); require(!_processed[_queryId], "Query has already been processed!"); _processed[_queryId] = true; //fetch the roll associated with this query uint256 roll_id = _query_to_race[_queryId]; require(roll_id > 0, "Invalid _queryId"); Race storage race = races[race_id]; //identify which query is this if(_queryId == race.query_price_start) { (race.result_price_start_BTC,race.result_price_start_LTC,race.result_price_start_ETH) = _extractPrices(_result); // increment state to show we're waiting for the next queries now race.state = State(uint(race.state) + 1); } else if(_queryId == race.query_price_end) { (race.result_price_end_BTC,race.result_price_end_LTC,race.result_price_end_ETH) = _extractPrices(_result); // increment state to show we're waiting for the next queries now race.state = State(uint(race.state) + 1); } else { //fatal error roll.state = State.REFUND; emit RaceRefunded(race_id); } //if the race state has been incremented enough (2 times), we've finished if(race.state == State.DONE) { int256 btc_delta = int256(race.result_price_end_BTC) - int256(race.result_price_start_BTC); int256 ltc_delta = int256(race.result_price_end_LTC) - int256(race.result_price_start_LTC); int256 eth_delta = int256(race.result_price_end_ETH) - int256(race.result_price_start_ETH); race.btc_won = btc_delta >= ltc_delta && btc_delta >= eth_delta; race.ltc_won = ltc_delta >= btc_delta && ltc_delta >= eth_delta; race.eth_won = eth_delta >= ltc_delta && eth_delta >= btw_delta; race.total_pool = race.btc_pool.add(race.ltc_pool).add(race.eth_pool); if(race.btc_won) { race.winners_total = race.winners_total.add(race.btc_pool); } if(race.ltc_won) { race.winners_total = race.winners_total.add(race.ltc_pool); } if(race.eth_won) { race.winners_total = race.winners_total.add(race.eth_pool); } emit RaceEnded(race_id, race.btc_won, race.ltc_won, race.eth_won); } } /** @dev Sends the required amount to the cut address @param amount Amount to withdraw from the house in Wei */ function withdrawHouse(uint256 amount) external onlyOwner() { require(house >= amount, "Cant withdraw that much"); house = house.sub(amount); config_cut_address.transfer(amount); } /** @dev Sets the house edge @param new_edge Edge expressed in /1000 */ function setHouseEdge(uint256 new_edge) external onlyOwner() { require(new_edge <= 50,"max 5%"); config_house_edge = new_edge; } /** @dev Address of destination for the house edge @param new_desination address to send eth to */ function setCutDestination(address payable new_desination) external onlyOwner() { config_cut_address = new_desination; } /** @dev Sets the gas sent to oraclize for callback on a single price check @param new_gaslimit Gas in wei */ function setGasLimit(uint256 new_gaslimit) external onlyOwner() { config_gas_limit = new_gaslimit; } /** @dev Sets the gas price to be used by oraclize @param new_gasprice Gas in wei */ function setGasPrice(uint256 new_gasprice) external onlyOwner() { config_gasprice = new_gasprice; oraclize_setCustomGasPrice(config_gasprice); } /** @dev Sets the maximum allowed race duration @param new_duration duration in seconds */ function setMaxDuration(uint256 new_duration) external onlyOwner() { config_max_duration = new_duration; } /** @dev Sets the minimum allowed race duration @param new_duration duration in seconds */ function setMinDuration(uint256 new_duration) external onlyOwner() { config_min_duration = new_duration; } /** @dev Sets the delay to wait before a race gets refunded @param new_delay duration in seconds */ function setRefundDelay(uint256 new_delay) external onlyOwner() { config_refund_delay = new_delay; } function _prepareNextRace() internal { //increment race id for the next one current_race = current_race.add(1); Race storage race = races[current_race].state = State.READY; } function _extractPrices(string memory entry) internal pure returns (uint256, uint256, uint256) { strings.slice memory sl = entry.toSlice(); strings.slice memory delim = "\"".toSlice(); string[] memory parts = new string[](4); for(uint i = 0; i < parts.length; i++) { parts[i] = sl.split(delim).toString(); } return (_stringToUintNormalize(parts[1]), _stringToUintNormalize(parts[3]), _stringToUintNormalize(parts[5])); } //ETHORSE CODE // utility function to convert string to integer with precision consideration function _stringToUintNormalize(string memory s) internal pure returns (uint result) { uint p = 2; bool precision = false; bytes memory b = bytes(s); uint i; result = 0; for (i = 0; i < b.length; i++) { if (precision) {p = p-1;} if (uint8(b[i]) == 46){precision = true;} uint c = uint8(b[i]); if (c >= 48 && c <= 57) {result = result * 10 + (c - 48);} if (precision && p == 0){return result;} } while (p!=0) { result = result*10; p = p-1; } } }
the callback function is called by Oraclize when the result is ready the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: the proof validity is fully verified on-chainfetch the roll associated with this queryidentify which query is this increment state to show we're waiting for the next queries now increment state to show we're waiting for the next queries nowfatal errorif the race state has been incremented enough (2 times), we've finished
function __callback(bytes32 _queryId, string memory _result, bytes memory _proof) public { require (msg.sender == oraclize_cbAddress(), "auth failed"); require(!_processed[_queryId], "Query has already been processed!"); _processed[_queryId] = true; uint256 roll_id = _query_to_race[_queryId]; require(roll_id > 0, "Invalid _queryId"); Race storage race = races[race_id]; if(_queryId == race.query_price_start) { (race.result_price_start_BTC,race.result_price_start_LTC,race.result_price_start_ETH) = _extractPrices(_result); race.state = State(uint(race.state) + 1); (race.result_price_end_BTC,race.result_price_end_LTC,race.result_price_end_ETH) = _extractPrices(_result); race.state = State(uint(race.state) + 1); roll.state = State.REFUND; emit RaceRefunded(race_id); } if(race.state == State.DONE) { int256 btc_delta = int256(race.result_price_end_BTC) - int256(race.result_price_start_BTC); int256 ltc_delta = int256(race.result_price_end_LTC) - int256(race.result_price_start_LTC); int256 eth_delta = int256(race.result_price_end_ETH) - int256(race.result_price_start_ETH); race.btc_won = btc_delta >= ltc_delta && btc_delta >= eth_delta; race.ltc_won = ltc_delta >= btc_delta && ltc_delta >= eth_delta; race.eth_won = eth_delta >= ltc_delta && eth_delta >= btw_delta; race.total_pool = race.btc_pool.add(race.ltc_pool).add(race.eth_pool); if(race.btc_won) { race.winners_total = race.winners_total.add(race.btc_pool); } if(race.ltc_won) { race.winners_total = race.winners_total.add(race.ltc_pool); } if(race.eth_won) { race.winners_total = race.winners_total.add(race.eth_pool); } emit RaceEnded(race_id, race.btc_won, race.ltc_won, race.eth_won); } } @param amount Amount to withdraw from the house in Wei
12,728,545
// 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; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.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); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.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; } // File: @openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.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); } // File: @openzeppelin/contracts/token/ERC1155/ERC1155.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() { } /** * @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; } } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @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); } } contract EliteAlpha is ERC1155, Ownable { string public constant name = "ELIT3ALPHA"; string public constant symbol = "EA"; using SafeMath for uint256; using Strings for uint256; string private baseURI; uint256 public totalSupply = 0; uint256 public constant MAX_NFT_PUBLIC = 9969; uint256 private constant MAX_NFT = 9999; uint256 public constant maxGiveaway=30; uint256 public constant maxPerWalletPresale=10; uint256 public giveawayCount; uint256 public privateSalePrice = 200000000000000000; // 0.2 ETH uint256 public presalePrice = 200000000000000000; // 0.2 ETH uint256 public NFTPrice = 200000000000000000; // 0.2 ETH bool public isActive; bool public isPrivateSaleActive; bool public isPresaleActive; bool public canReveal; bytes32 public root; mapping(address => uint) public nftBalances; /* * Function to validate owner */ function _ownerOf(address owner, uint256 tokenId) internal view returns (bool) { return balanceOf(owner, tokenId) != 0; } /* * Function to mint NFTs */ function mint(address to, uint32 count) internal { if (count > 1) { uint256[] memory ids = new uint256[](uint256(count)); uint256[] memory amounts = new uint256[](uint256(count)); for (uint32 i = 0; i < count; i++) { ids[i] = totalSupply + i; amounts[i] = 1; } _mintBatch(to, ids, amounts, ""); } else { _mint(to, totalSupply, 1, ""); } totalSupply += count; } /* * Function setCanReveal to activate/desactivate reveal option */ function setCanReveal( bool _isActive ) external onlyOwner { canReveal = _isActive; } /* * Function setIsActive to activate/desactivate the smart contract */ function setIsActive( bool _isActive ) external onlyOwner { isActive = _isActive; } /* * Function setPrivateSaleActive to activate/desactivate the presale */ function setPrivateSaleActive( bool _isActive ) external onlyOwner { isPrivateSaleActive = _isActive; } /* * Function setPresaleActive to activate/desactivate the presale */ function setPresaleActive( bool _isActive ) external onlyOwner { isPresaleActive = _isActive; } /* * Function to set Base URI */ function setURI( string memory _URI ) external onlyOwner { baseURI = _URI; } /* * Function to withdraw collected amount during minting by the owner */ function withdraw( ) public onlyOwner { uint balance = address(this).balance; require(balance > 0, "Balance should be more then zero"); payable(0xfbc7A660e4820DE480Cfdf65CfEaE6dE317aD0ca).transfer((balance * 450) / 1000); payable(0xEdF400bFDF2E87D196c304480B53d0EAa2c86076).transfer((balance * 450) / 1000); payable(0xB7316530C6145Aa96CA5Be0e9888d208bed9A4dB).transfer((balance * 100) / 1000); } /* * Function to set NFT Price */ function setNFTPrice(uint256 _price) external onlyOwner { NFTPrice = _price; } /* * Function to mint new NFTs during the public sale * It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens)) */ function mintNFT( uint32 _numOfTokens ) public payable { require(isActive, 'Contract is not active'); require(!isPrivateSaleActive, 'Private sale still active'); require(!isPresaleActive, 'Presale still active'); require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs"); require(msg.value >= NFTPrice.mul(_numOfTokens), "Ether value sent is not correct"); mint(msg.sender,_numOfTokens); } /* * Function to mint new NFTs during the private sale & presale * It is payable. */ function mintNFTDuringPresale( uint32 _numOfTokens, bytes32[] memory _proof ) public payable { require(isActive, 'Contract is not active'); require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted"); if (!isPresaleActive) { require(isPrivateSaleActive, 'Private sale not active'); require(msg.value >= privateSalePrice.mul(_numOfTokens), "Ether value sent is not correct"); require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase'); mint(msg.sender,_numOfTokens); nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens); return; } require(msg.value >= presalePrice.mul(_numOfTokens), "Ether value sent is not correct"); require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase'); mint(msg.sender,_numOfTokens); nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens); } /* * Function to mint all NFTs for giveaway and partnerships */ function mintByOwner( address _to ) public onlyOwner { require(giveawayCount.add(1)<=maxGiveaway,"Cannot do more giveaway"); require(totalSupply.add(1) < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); mint(_to,1); giveawayCount=giveawayCount.add(1); } /* * Function to mint all NFTs for giveaway and partnerships */ function mintMultipleByOwner( address[] memory _to ) public onlyOwner { require(totalSupply.add(_to.length) < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); require(giveawayCount.add(_to.length)<=maxGiveaway,"Cannot do that much giveaway"); for(uint256 i = 0; i < _to.length; i++){ mint(_to[i],1); } giveawayCount=giveawayCount.add(_to.length); } /* * Function to get token URI of given token ID * URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC */ function uri( uint256 _tokenId ) public view virtual override returns (string memory) { require(_tokenId<totalSupply, "ERC1155Metadata: URI query for nonexistent token"); if (!canReveal) { return string(abi.encodePacked(baseURI)); } else { return string(abi.encodePacked(baseURI, _tokenId.toString())); } } /* * Function to withdraw collected amount during minting by the owner */ function withdrawOwner( ) public onlyOwner { uint balance = address(this).balance; require(balance > 0, "Balance should be more then zero"); payable(owner()).transfer(balance); } /* * Function to set the merkle root */ function setRoot(uint256 _root) onlyOwner() public { root = bytes32(_root); } /* * Function to verify the proof */ function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = sha256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = sha256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } }
Function to mint new NFTs during the public sale It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))/
function mintNFT( uint32 _numOfTokens ) public payable { require(isActive, 'Contract is not active'); require(!isPrivateSaleActive, 'Private sale still active'); require(!isPresaleActive, 'Presale still active'); require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs"); require(msg.value >= NFTPrice.mul(_numOfTokens), "Ether value sent is not correct"); mint(msg.sender,_numOfTokens); }
9,922,060
./partial_match/1/0x43e967c68D00C5670382D2C00689400a107f7178/sources/CoffeeWars.sol
This function can only be called by the ownerThis function is external because it will only be called from outside of this contractIf the given _uri is null, revert with the error NullString()Set the baseURI
function setURI(string memory _uri) external onlyOwner { if(bytes(_uri).length == 0) revert NullString(); baseURI = _uri; }
4,274,145
./partial_match/1/0xD7FbFF0fd48dE02901E19b192cc59b1c31198526/sources/IERC721.sol
ERC721 Non-Fungible Token Standard basic interface Prashant Prabhakar Singh [[email protected]]/
interface IERC721 { 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 ); function balanceOf(address _owner) external view returns (uint256 _balance); function ownerOf(uint256 _tokenId) external view returns (address _owner); function exists(uint256 _tokenId) external view returns (bool _exists); function approve(address _to, uint256 _tokenId) external; function getApproved(uint256 _tokenId) external view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) external; function isApprovedForAll(address _owner, address _operator) external view returns (bool); function transferFrom( address _from, address _to, uint256 _tokenId ) external; function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) external; function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory); function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) external view returns (uint256); function supportsInterface(bytes4 _interfaceId) external view returns (bool); }
15,630,764
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./utils/access/Ownable.sol"; import "./utils/math/SafeMath.sol"; import "./utils/Address.sol"; import "./utils/security/Pausable.sol"; import "./ERC721/ERC721.sol"; import "./ERC20/IERC20.sol"; import "./IMarketplace.sol"; import "./FeeManager.sol"; contract Marketplace is Ownable, Pausable, FeeManager, IMarketplace { using Address for address; using SafeMath for uint256; //using SafeERC20 for IERC20; IERC20 public acceptedToken; // From ERC721 registry assetId to Order (to avoid asset collision) mapping(address => mapping(uint256 => Order)) public orderByAssetId; // From ERC721 registry assetId to Bid (to avoid asset collision) mapping(address => mapping(uint256 => Bid)) public bidByOrderId; // 721 Interfaces bytes4 public constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /** * @dev Initialize this contract. Acts as a constructor * @param _acceptedToken - currency for payments */ constructor(address _acceptedToken) Ownable() { require( _acceptedToken.isContract(), "The accepted token address must be a deployed contract" ); acceptedToken = IERC20(_acceptedToken); } /** * @dev Sets the paused failsafe. Can only be called by owner * @param _setPaused - paused state */ function setPaused(bool _setPaused) public onlyOwner { return (_setPaused) ? _pause() : _unpause(); } /** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Duration of the order (in hours) */ function createOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) public whenNotPaused { _createOrder(_nftAddress, _assetId, _priceInWei, _expiresAt); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function cancelOrder( address _nftAddress, uint256 _assetId ) public whenNotPaused { Order memory order = orderByAssetId[_nftAddress][_assetId]; require( order.seller == msg.sender || msg.sender == owner(), "Marketplace: unauthorized sender" ); // Remove pending bid if any Bid memory bid = bidByOrderId[_nftAddress][_assetId]; if (bid.id != 0) { _cancelBid( bid.id, _nftAddress, _assetId, bid.bidder, bid.price ); } // Cancel order. _cancelOrder( order.id, _nftAddress, _assetId, msg.sender ); } /** * @dev Update an already published order * can only be updated by seller * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function updateOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) public whenNotPaused { Order memory order = orderByAssetId[_nftAddress][_assetId]; // Check valid order to update require(order.id != 0, "Marketplace: asset not published"); require(order.seller == msg.sender, "Marketplace: sender not allowed"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); // check order updated params require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require( _expiresAt > block.timestamp.add(1 minutes), "Marketplace: Expire time should be more than 1 minute in the future" ); order.price = _priceInWei; order.expiresAt = _expiresAt; emit OrderUpdated(order.id, _priceInWei, _expiresAt); } /** * @dev Executes the sale for a published NFT and checks for the asset fingerprint * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Order price */ function safeExecuteOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) public whenNotPaused { // Get the current valid order for the asset or fail Order memory order = _getValidOrder( _nftAddress, _assetId ); /// Check the execution price matches the order price require(order.price == _priceInWei, "Marketplace: invalid price"); require(order.seller != msg.sender, "Marketplace: unauthorized sender"); // market fee to cut uint256 saleShareAmount = 0; // Send market fees to owner if (FeeManager.cutPerMillion > 0) { // Calculate sale share saleShareAmount = _priceInWei .mul(FeeManager.cutPerMillion) .div(1e6); // Transfer share amount for marketplace Owner acceptedToken.transferFrom( msg.sender, //buyer owner(), saleShareAmount ); } // Transfer accepted token amount minus market fee to seller acceptedToken.transferFrom( msg.sender, // buyer order.seller, // seller order.price.sub(saleShareAmount) ); // Remove pending bid if any Bid memory bid = bidByOrderId[_nftAddress][_assetId]; if (bid.id != 0) { _cancelBid( bid.id, _nftAddress, _assetId, bid.bidder, bid.price ); } _executeOrder( order.id, msg.sender, // buyer _nftAddress, _assetId, _priceInWei ); } /* buy */ function Buy( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) public whenNotPaused { // Checks order validity Order memory order = _getValidOrder(_nftAddress, _assetId); require (_priceInWei==order.price,"Marketplace : price is not right"); // Check price if theres previous a bid Bid memory bid = bidByOrderId[_nftAddress][_assetId]; // if theres no previous bid, just check price > 0 if (bid.id != 0) { _cancelBid( bid.id, _nftAddress, _assetId, bid.bidder, bid.price ); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } // Transfer sale amount from bidder to escrow acceptedToken.transferFrom( msg.sender, // bidder address(this), _priceInWei ); // calc market fees uint256 saleShareAmount = _priceInWei .mul(FeeManager.cutPerMillion) .div(1e6); // to owner acceptedToken.transfer( owner(), saleShareAmount ); //royallty uint256 royalltyShareAmount= _priceInWei.mul(FeeManager.royaltyPerMillion).div(1e6); acceptedToken.transfer( IERC721(_nftAddress).createrOf(_assetId), royalltyShareAmount ); // transfer escrowed bid amount minus market fee to seller acceptedToken.transfer( order.seller, _priceInWei.sub(saleShareAmount).sub(royalltyShareAmount) ); // Transfer NFT asset IERC721(_nftAddress).transferFrom( address(this), msg.sender, _assetId ); emit Buycreate( _nftAddress, _assetId, order.seller, msg.sender, _priceInWei ); } /** * @dev Places a bid for a published NFT and checks for the asset fingerprint * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Bid price in acceptedToken currency * @param _expiresAt - Bid expiration time */ function PlaceBid( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) public whenNotPaused { _createBid( _nftAddress, _assetId, _priceInWei, _expiresAt ); } /** * @dev Cancel an already published bid * can only be canceled by seller or the contract owner * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function cancelBid( address _nftAddress, uint256 _assetId ) public whenNotPaused { Bid memory bid = bidByOrderId[_nftAddress][_assetId]; require( bid.bidder == msg.sender || msg.sender == owner(), "Marketplace: Unauthorized sender" ); _cancelBid( bid.id, _nftAddress, _assetId, bid.bidder, bid.price ); } /** * @dev Executes the sale for a published NFT by accepting a current bid * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _priceInWei - Bid price in wei in acceptedTokens currency */ function acceptBid( address _nftAddress, uint256 _assetId, uint256 _priceInWei ) public whenNotPaused { // check order validity Order memory order = _getValidOrder(_nftAddress, _assetId); // item seller is the only allowed to accept a bid require(order.seller == msg.sender, "Marketplace: unauthorized sender"); Bid memory bid = bidByOrderId[_nftAddress][_assetId]; require(bid.price == _priceInWei, "Marketplace: invalid bid price"); require(bid.expiresAt >= block.timestamp, "Marketplace: the bid expired"); // remove bid delete bidByOrderId[_nftAddress][_assetId]; emit BidAccepted(bid.id); // calc market fees uint256 saleShareAmount = bid.price .mul(FeeManager.cutPerMillion) .div(1e6); // to owner acceptedToken.transfer( owner(), saleShareAmount ); //royallty uint256 royalltyShareAmount= bid.price.mul(FeeManager.royaltyPerMillion).div(1e6); acceptedToken.transfer( IERC721(_nftAddress).createrOf(_assetId), royalltyShareAmount ); // transfer escrowed bid amount minus market fee to seller acceptedToken.transfer( order.seller, bid.price.sub(saleShareAmount).sub(royalltyShareAmount) ); _executeOrder( order.id, bid.bidder, _nftAddress, _assetId, _priceInWei ); } /** * @dev Internal function gets Order by nftRegistry and assetId. Checks for the order validity * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT */ function _getValidOrder( address _nftAddress, uint256 _assetId ) internal view returns (Order memory order) { order = orderByAssetId[_nftAddress][_assetId]; require(order.id != 0, "Marketplace: asset not published"); require(order.expiresAt >= block.timestamp, "Marketplace: order expired"); } /** * @dev Executes the sale for a published NFT * @param _orderId - Order Id to execute * @param _buyer - address * @param _nftAddress - Address of the NFT registry * @param _assetId - NFT id * @param _priceInWei - Order price */ function _executeOrder( bytes32 _orderId, address _buyer, address _nftAddress, uint256 _assetId, uint256 _priceInWei ) internal { // remove order delete orderByAssetId[_nftAddress][_assetId]; // Transfer NFT asset IERC721(_nftAddress).transferFrom( address(this), _buyer, _assetId ); // Notify .. emit OrderSuccessful( _orderId, _buyer, _priceInWei ); } /** * @dev Creates a new order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - Expiration time for the order */ function _createOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) internal { // Check nft registry IERC721 nftRegistry = _requireERC721(_nftAddress); // Check order creator is the asset owner address assetOwner = nftRegistry.ownerOf(_assetId); require( assetOwner == msg.sender, "Marketplace: Only the asset owner can create orders" ); require(_priceInWei > 0, "Marketplace: Price should be bigger than 0"); require( _expiresAt > block.timestamp.add(1 minutes), "Marketplace: Publication should be more than 1 minute in the future" ); // get NFT asset from seller nftRegistry.transferFrom( assetOwner, address(this), _assetId ); // create the orderId bytes32 orderId = keccak256( abi.encodePacked( block.timestamp, assetOwner, _nftAddress, _assetId, _priceInWei ) ); // save order orderByAssetId[_nftAddress][_assetId] = Order({ id: orderId, seller: assetOwner, nftAddress: _nftAddress, price: _priceInWei, expiresAt: _expiresAt }); emit OrderCreated( orderId, assetOwner, _nftAddress, _assetId, _priceInWei, _expiresAt ); } /** * @dev Creates a new bid on a existing order * @param _nftAddress - Non fungible registry address * @param _assetId - ID of the published NFT * @param _priceInWei - Price in Wei for the supported coin * @param _expiresAt - expires time */ function _createBid( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) internal { // Checks order validity Order memory order = _getValidOrder(_nftAddress, _assetId); // check on expire time if (_expiresAt > order.expiresAt) { _expiresAt = order.expiresAt; } // Check price if theres previous a bid Bid memory bid = bidByOrderId[_nftAddress][_assetId]; // if theres no previous bid, just check price > 0 if (bid.id != 0) { if (bid.expiresAt >= block.timestamp) { require( _priceInWei > bid.price, "Marketplace: bid price should be higher than last bid" ); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } _cancelBid( bid.id, _nftAddress, _assetId, bid.bidder, bid.price ); } else { require(_priceInWei > 0, "Marketplace: bid should be > 0"); } // Transfer sale amount from bidder to escrow acceptedToken.transferFrom( msg.sender, // bidder address(this), _priceInWei ); // Create bid bytes32 bidId = keccak256( abi.encodePacked( block.timestamp, msg.sender, order.id, _priceInWei, _expiresAt ) ); // Save Bid for this order bidByOrderId[_nftAddress][_assetId] = Bid({ id: bidId, bidder: msg.sender, price: _priceInWei, expiresAt: _expiresAt }); emit BidCreated( bidId, _nftAddress, _assetId, msg.sender, // bidder _priceInWei, _expiresAt ); } /** * @dev Cancel an already published order * can only be canceled by seller or the contract owner * @param _orderId - Bid identifier * @param _nftAddress - Address of the NFT registry * @param _assetId - ID of the published NFT * @param _seller - Address */ function _cancelOrder( bytes32 _orderId, address _nftAddress, uint256 _assetId, address _seller ) internal { delete orderByAssetId[_nftAddress][_assetId]; /// send asset back to seller IERC721(_nftAddress).transferFrom( address(this), _seller, _assetId ); emit OrderCancelled(_orderId); } /** * @dev Cancel bid from an already published order * can only be canceled by seller or the contract owner * @param _bidId - Bid identifier * @param _nftAddress - registry address * @param _assetId - ID of the published NFT * @param _bidder - Address * @param _escrowAmount - in acceptenToken currency */ function _cancelBid( bytes32 _bidId, address _nftAddress, uint256 _assetId, address _bidder, uint256 _escrowAmount ) internal { delete bidByOrderId[_nftAddress][_assetId]; // return escrow to canceled bidder acceptedToken.transfer( _bidder, _escrowAmount ); emit BidCancelled(_bidId); } function _requireERC721(address _nftAddress) internal view returns (IERC721) { require( _nftAddress.isContract(), "The NFT Address should be a contract" ); // require( // IERC721(_nftAddress).supportsInterface(_INTERFACE_ID_ERC721), // "The NFT contract has an invalid ERC721 implementation" // ); return IERC721(_nftAddress); } function getOrderByAssetIds (address _nftAddress,uint256[] memory _assetIds) external view returns(Order[] memory orders){ orders = new Order[](_assetIds.length); for(uint256 i = 0; i < _assetIds.length; i++){ orders[i] = orderByAssetId[_nftAddress][_assetIds[i]]; } } function getBidByAssetIds (address _nftAddress,uint256[] memory _assetIds) external view returns(Bid[] memory bids){ bids = new Bid[](_assetIds.length); for(uint256 i = 0; i < _assetIds.length; i++){ bids[i] = bidByOrderId[_nftAddress][_assetIds[i]]; } } }
Creates a new order _nftAddress - Non fungible registry address _assetId - ID of the published NFT _priceInWei - Price in Wei for the supported coin _expiresAt - Duration of the order (in hours)/
function createOrder( address _nftAddress, uint256 _assetId, uint256 _priceInWei, uint256 _expiresAt ) public whenNotPaused { _createOrder(_nftAddress, _assetId, _priceInWei, _expiresAt); }
1,057,069
./full_match/3/0xC0b4856340cC565F0BE991cf2025170fe9CFfE71/sources/browser/ProofOfName.sol
function to add another user as and authorized user
function AddAuthorisedUser(address _user) onlyOwner public { AuthorisedUser[_user] = true; }
8,185,589
// SPDX-License-Identifier: MIT // Sources flattened with hardhat v2.9.3 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File erc721a/contracts/[email protected] // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; } // Compiler will pack the following // _currentIndex and _burnCounter into a single 256bit word. // The tokenId of the next token to be minted. uint128 internal _currentIndex; // The number of tokens burned. uint128 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC721Enumerable-tokenByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenByIndex(uint256 index) public view override returns (uint256) { uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (!ownership.burned) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert TokenIndexOutOfBounds(); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds(); uint256 numMintedSoFar = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when // uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } // Execution should never reach this point. revert(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = uint128(updatedIndex); } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**128. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File contracts/Project220.sol pragma solidity ^0.8.4; error EtherValueNotCorrect(); error ExceedsSupplyCap(); error ExceedsSupplyLimit(); error SaleIsNotActive(); contract Project220 is Ownable, ERC721A { // project settings bool public isActive; uint8 public supplyCap; uint8 public supplyLimit; uint64 public ethPrice; // withdraw addresses address private _t1; // 90% address private _t2; // 5% address private _t3; // 5% string private _baseURIPath; constructor(uint64 initialPrice, address t1_, address t2_, address t3_) ERC721A("Project220", "P220") { unchecked { supplyCap = 221; // 1st token (#0) will be for owner, then 220 for public sale supplyLimit = 1; // Limit will be increased manually but supply can never exceed cap ethPrice = initialPrice; _t1 = t1_; _t2 = t2_; _t3 = t3_; } } /** * @dev Mints a single token * * Requirements: * - Contract is active * - Does not exceed supply cap * - Does not exceed current supply limit (will increase up to cap) * - Ether value must equal minting price */ function mintToken() external payable { if (!isActive) revert SaleIsNotActive(); if (totalSupply() + 1 > uint256(supplyCap)) revert ExceedsSupplyCap(); if (totalSupply() + 1 > uint256(supplyLimit)) revert ExceedsSupplyLimit(); if (uint256(ethPrice) != msg.value) revert EtherValueNotCorrect(); _safeMint(_msgSender(), 1); } /** * @dev Sets the base URI used for the metadata url */ function setBaseURI(string memory baseURI) external onlyOwner { _baseURIPath = baseURI; } /** * @dev Sets the minting price which will increase as tokens are sold */ function setEthPrice(uint64 price) external onlyOwner { ethPrice = price; } /** * @dev Sets the supply limit, but always restricted by hard supply cap */ function setSupplyLimit(uint8 limit) external onlyOwner { supplyLimit = limit; } // Just in we have to change the address after deployment function setT1(address t1_) external onlyOwner { _t1 = t1_; } /** * @dev Flips contract sale state on/off */ function toggleSaleState() external onlyOwner { isActive = !isActive; } /** * @dev Withdraw balance */ function withdraw() external onlyOwner { uint256 _share = address(this).balance / 20; Address.sendValue(payable(_t1), _share * 18); Address.sendValue(payable(_t2), _share); Address.sendValue(payable(_t3), _share); } /** * @dev Override the default baseURI path */ function _baseURI() internal view override returns (string memory) { return _baseURIPath; } }
Flips contract sale state on/off/
function toggleSaleState() external onlyOwner { isActive = !isActive; }
145,767
./full_match/1/0xD8737CA46aa6285dE7B8777a8e3db232911baD41/sources/localhost/contracts/StafiUpgrade.sol
Init stafi upgrade contract
function initThisContract() external onlySuperUser { addStafiUpgradeContract(address(this)); }
3,080,318
./full_match/1/0x8fc72dcfbf39FE686c96f47C697663EE08C78380/sources/contracts/ZunamiBaseAPS.sol
in this func user sends pending withdraw to the contract and then waits for the completion of the transaction for all users lpShares - amount of ZLP for withdraw tokenAmount - stablecoin amount that user want minimum receive/
function delegateWithdrawal(uint256 lpShares, uint256 tokenAmount) external whenNotPaused { require(lpShares > 0, 'Zunami: lpAmount must be higher 0'); PendingWithdrawal memory withdrawal; address userAddr = _msgSender(); withdrawal.lpShares = lpShares; withdrawal.tokenAmount = tokenAmount; _pendingWithdrawals[userAddr] = withdrawal; emit CreatedPendingWithdrawal(userAddr, lpShares, tokenAmount); }
4,944,121
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.5.0; /// @title Stores packed 32 bit timestamp values /// @notice Contains methods for working with a mapping from tick to 32 bit timestamp values, specifically seconds /// spent outside the tick. /// @dev The mapping uses int24 for keys since ticks are represented as int24 and there are 8 (2^3) values per word. /// Note "seconds outside" is always a relative measurement, only consistent for as long as a the lower tick and upper tick /// have gross liquidity greater than 0. library SecondsOutside { /// @notice Computes the position of the least significant bit of the 32 bit seconds outside value for a given tick /// @param tick the tick for which to compute the position /// @param tickSpacing the spacing between usable ticks /// @return wordPos the key in the mapping containing the word in which the bit is stored /// @return shift the position of the least significant bit in the 32 bit seconds outside function position(int24 tick, int24 tickSpacing) private pure returns (int24 wordPos, uint8 shift) { require(tick % tickSpacing == 0); int24 compressed = tick / tickSpacing; wordPos = compressed >> 3; shift = uint8(compressed % 8) * 32; } /// @notice Called the first time a tick is used to set the seconds outside value. Assumes the tick is not /// initialized. /// @param self the packed mapping of tick to seconds outside /// @param tick the tick to be initialized /// @param tickCurrent the current tick /// @param tickSpacing the spacing between usable ticks /// @param time the current timestamp function initialize( mapping(int24 => uint256) storage self, int24 tick, int24 tickCurrent, int24 tickSpacing, uint32 time ) internal { if (tick <= tickCurrent) { (int24 wordPos, uint8 shift) = position(tick, tickSpacing); self[wordPos] |= uint256(time) << shift; } } /// @notice Called when a tick is no longer used, to clear the seconds outside value of the tick /// @param self the packed mapping of tick to seconds outside /// @param tick the tick to be cleared /// @param tickSpacing the spacing between usable ticks function clear( mapping(int24 => uint256) storage self, int24 tick, int24 tickSpacing ) internal { (int24 wordPos, uint8 shift) = position(tick, tickSpacing); self[wordPos] &= ~(uint256((0 - uint32(1))) << shift); } /// @notice Called when an initialized tick is crossed to update the seconds outside for that tick. Must be called /// every time an initialized tick is crossed /// @param self the packed mapping of tick to seconds outside /// @param tick the tick to be crossed /// @param tickSpacing the spacing between usable ticks /// @param time the current block timestamp truncated to 32 bits function cross( mapping(int24 => uint256) storage self, int24 tick, int24 tickSpacing, uint32 time ) internal { (int24 wordPos, uint8 shift) = position(tick, tickSpacing); uint256 prev = self[wordPos]; uint32 timePrev = uint32(prev >> shift); uint32 timeNext = time - timePrev; self[wordPos] = (prev ^ (uint256(timePrev) << shift)) | (uint256(timeNext) << shift); } /// @notice Get the seconds outside for an initialized tick. Should be called only on initialized ticks. /// @param self the packed mapping of tick to seconds outside /// @param tick the tick to get the seconds outside value for /// @param tickSpacing the spacing between usable ticks /// @return the seconds outside value for that tick function get( mapping(int24 => uint256) storage self, int24 tick, int24 tickSpacing ) internal view returns (uint32) { (int24 wordPos, uint8 shift) = position(tick, tickSpacing); uint256 prev = self[wordPos]; return uint32(prev >> shift); } /// @notice Get the seconds inside a tick range, assuming both tickLower and tickUpper are initialized /// @param self the packed mapping of tick to seconds outside /// @param tickLower the lower tick for which to get seconds inside /// @param tickUpper the upper tick for which to get seconds inside /// @param tickCurrent the current tick /// @param tickSpacing the spacing between usable ticks /// @return a relative seconds inside value that can be snapshotted and compared to a later snapshot to compute /// time spent between tickLower and tickUpper, i.e. time that a position's liquidity was in use. function secondsInside( mapping(int24 => uint256) storage self, int24 tickLower, int24 tickUpper, int24 tickCurrent, int24 tickSpacing, uint32 time ) internal view returns (uint32) { // calculate seconds below uint32 secondsBelow; if (tickCurrent >= tickLower) { secondsBelow = get(self, tickLower, tickSpacing); } else { secondsBelow = time - get(self, tickLower, tickSpacing); } // calculate seconds above uint32 secondsAbove; if (tickCurrent < tickUpper) { secondsAbove = get(self, tickUpper, tickSpacing); } else { secondsAbove = time - get(self, tickUpper, tickSpacing); } return time - secondsBelow - secondsAbove; } }
Called the first time a tick is used to set the seconds outside value. Assumes the tick is not initialized. self the packed mapping of tick to seconds outside tick the tick to be initialized tickCurrent the current tick tickSpacing the spacing between usable ticks time the current timestamp
function initialize( mapping(int24 => uint256) storage self, int24 tick, int24 tickCurrent, int24 tickSpacing, uint32 time ) internal { if (tick <= tickCurrent) { (int24 wordPos, uint8 shift) = position(tick, tickSpacing); self[wordPos] |= uint256(time) << shift; } }
12,556,913
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./interfaces/IShogunToken.sol"; /* _____ _ _____ _ / ____| | / ____| (_) | (___ | |__ ___ __ _ _ _ _ __ | (___ __ _ _ __ ___ _ _ _ __ __ _ _ ___ \___ \| '_ \ / _ \ / _` | | | | '_ \ \___ \ / _` | '_ ` _ \| | | | '__/ _` | / __| ____) | | | | (_) | (_| | |_| | | | |____) | (_| | | | | | | |_| | | | (_| | \__ \ |_____/|_| |_|\___/ \__, |\__,_|_| |_|_____/ \__,_|_| |_| |_|\__,_|_| \__,_|_|___/ __/ | |___/ */ contract ShogunNFT is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; using ECDSA for bytes32; IShogunToken public SHOGUN_TOKEN; address payable public treasury; address public stakingContractAddress; address private signerAddressPublic; address private signerAddressPresale; string public baseURI; string public notRevealedUri; uint256 public cost = 0.08 ether; uint256 public maxSupply = 8888; uint256 public maxMintPerTxn = 4; // maximum number of mint per transaction uint256 public nftPerAddressLimitPublic = 8; // maximum number of mint per wallet for public sale uint256 public nftPerAddressLimitPresale = 2; // maximum number of mint per wallet for presale uint256 public nameChangePrice = 300 ether; uint256 public presaleWindow = 24 hours; // 24 hours presale period uint256 public presaleStartTime = 1634342400; // 16th October 0800 SGT uint256 public publicSaleStartTime = 1634443200; // 17thth October 1200 SGT bool public paused = false; bool public revealed = false; mapping(uint256 => string) public shogunName; // manual toggle for presale and public sale // bool public presaleOpen = false; bool public publicSaleOpen = false; // private variables // mapping(uint256 => bool) private _isLocked; mapping(address => bool) public whitelistedAddresses; // all address of whitelisted OGs mapping(address => uint256) private presaleAddressMintedAmount; // number of NFT minted for each wallet during presale mapping(address => uint256) private publicAddressMintedAmount; // number of NFT minted for each wallet during public sale mapping(bytes => bool) private _nonceUsed; // nonce was used to mint already // allows transactiones from only externally owned account (cannot be from smart contract) modifier onlyEOA() { require(msg.sender == tx.origin, "SHOGUN: Only EOA"); _; } // allow transactions only from staking Contract address modifier onlyStakingContract() { require( msg.sender == stakingContractAddress, "SHOGUN: Only callable from staking contract" ); _; } constructor( string memory _name, string memory _symbol, string memory _initBaseURI, // "" string memory _notRevealedUri, // default unrevealed IPFS address _signerAddressPresale, address _signerAddressPublic, address _treasury ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); notRevealedUri = _notRevealedUri; setSignerAddressPresale(_signerAddressPresale); setSignerAddressPublic(_signerAddressPublic); treasury = payable(_treasury); } // dev team mint function devMint(uint256 _mintAmount) public onlyEOA onlyOwner { require(!paused); // contract is not paused uint256 supply = totalSupply(); // get current mintedAmount require( supply + _mintAmount <= maxSupply, "SHOGUN: total mint amount exceeded supply, try lowering amount" ); for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } // public sale function publicMint( bytes memory nonce, bytes memory signature, uint256 _mintAmount ) public payable onlyEOA { require(!paused); require( (isPublicSaleOpen() || publicSaleOpen), "SHOGUN: public sale has not started" ); require(!_nonceUsed[nonce], "SHOGUN: nonce was used"); require( isSignedBySigner(msg.sender, nonce, signature, signerAddressPublic), "invalid signature" ); uint256 supply = totalSupply(); require( publicAddressMintedAmount[msg.sender] + _mintAmount <= nftPerAddressLimitPublic, "SHOGUN: You have exceeded max amount of mints" ); require( _mintAmount <= maxMintPerTxn, "SHOGUN: exceeded max mint amount per transaction" ); require( supply + _mintAmount <= maxSupply, "SHOGUN: total mint amount exceeded supply, try lowering amount" ); (bool success, ) = treasury.call{ value: msg.value }(""); // forward amount to treasury wallet require(success, "SHOGUN: not able to forward msg value to treasury"); require( msg.value == cost * _mintAmount, "SHOGUN: not enough ether sent for mint amount" ); for (uint256 i = 1; i <= _mintAmount; i++) { publicAddressMintedAmount[msg.sender]++; _safeMint(msg.sender, supply + i); } _nonceUsed[nonce] = true; } // presale mint function presaleMint( bytes memory nonce, bytes memory signature, uint256 _mintAmount ) public payable onlyEOA { require(!paused, "SHOGUN: contract is paused"); require( (isPresaleOpen() || presaleOpen), "SHOGUN: presale has not started or it has ended" ); require( whitelistedAddresses[msg.sender], "SHOGUN: you are not in the whitelist" ); require(!_nonceUsed[nonce], "SHOGUN: nonce was used"); require( isSignedBySigner(msg.sender, nonce, signature, signerAddressPresale), "SHOGUN: invalid signature" ); uint256 supply = totalSupply(); require( presaleAddressMintedAmount[msg.sender] + _mintAmount <= nftPerAddressLimitPresale, "SHOGUN: you can only mint a maximum of two nft during presale" ); require( msg.value >= cost * _mintAmount, "SHOGUN: not enought ethere sent for mint amount" ); (bool success, ) = treasury.call{ value: msg.value }(""); // forward amount to treasury wallet require(success, "SHOGUN: not able to forward msg value to treasury"); for (uint256 i = 1; i <= _mintAmount; i++) { presaleAddressMintedAmount[msg.sender]++; _safeMint(msg.sender, supply + i); } _nonceUsed[nonce] = true; } function airdrop(address[] memory giveawayList) public onlyEOA onlyOwner { require(!paused, "SHOGUN: contract is paused"); require( balanceOf(msg.sender) >= giveawayList.length, "SHOGUN: not enough in wallet for airdrop amount" ); uint256[] memory ownerWallet = walletOfOwner(msg.sender); for (uint256 i = 0; i < giveawayList.length; i++) { _safeTransfer(msg.sender, giveawayList[i], ownerWallet[i], "0x00"); } } //*************** PUBLIC FUNCTIONS ******************// function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); if (!revealed) { return notRevealedUri; } else { return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString())) : ""; } } //*************** INTERNAL FUNCTIONS ******************// function isSignedBySigner( address sender, bytes memory nonce, bytes memory signature, address signerAddress ) private pure returns (bool) { bytes32 hash = keccak256(abi.encodePacked(sender, nonce)); return signerAddress == hash.recover(signature); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function isPresaleOpen() public view returns (bool) { return block.timestamp >= presaleStartTime && block.timestamp < (presaleStartTime + presaleWindow); } function isPublicSaleOpen() public view returns (bool) { return block.timestamp >= publicSaleStartTime; } function isWhitelisted(address _user) public view returns (bool) { return whitelistedAddresses[_user]; } //*************** OWNER FUNCTIONS ******************// // No possible way to unreveal once it is toggled function reveal() public onlyOwner { revealed = true; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setShogunToken(address _shogunToken) external onlyOwner { SHOGUN_TOKEN = IShogunToken(_shogunToken); } function pause(bool _state) public onlyOwner { paused = _state; } function whitelistUsers(address[] calldata _users) external onlyOwner { for (uint256 i = 0; i < _users.length; i++) { whitelistedAddresses[_users[i]] = true; } } function withdrawToTreasury() public payable onlyOwner { (bool success, ) = treasury.call{ value: address(this).balance }(""); // returns boolean and data require(success); } function setPresaleOpen(bool _presaleOpen) public onlyOwner { presaleOpen = _presaleOpen; } function setPublicSaleOpen(bool _publicSaleOpen) public onlyOwner { publicSaleOpen = _publicSaleOpen; } function setSignerAddressPresale(address presaleSignerAddresss) public onlyOwner { signerAddressPresale = presaleSignerAddresss; } function setSignerAddressPublic(address publicSignerAddress) public onlyOwner { signerAddressPublic = publicSignerAddress; } function setNotRevealedUri(string memory _notRevealedUri) public onlyOwner { notRevealedUri = _notRevealedUri; } //*************** Future Utility Functions ******************// function setStakingContractAddress(address _stakingContract) public onlyOwner { stakingContractAddress = _stakingContract; } // sacrifice/burn ERC721 function seppuku(uint256 _tokenId) public { require( _isApprovedOrOwner(_msgSender(), _tokenId), "ERC721: transfer caller is not owner nor approved" ); _burn(_tokenId); } function setNameChangePrice(uint256 _newNameChangePrice) public onlyOwner { nameChangePrice = _newNameChangePrice; } function changeName(uint256 tokenId, string memory newName) public virtual { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "SHOGUN: Not a valid new name"); require( sha256(bytes(newName)) != sha256(bytes(shogunName[tokenId])), "SHOGUN: New name is same as the current one" ); SHOGUN_TOKEN.burn(_msgSender(), nameChangePrice); shogunName[tokenId] = newName; } function tokenNameByIndex(uint256 index) public view returns (string memory) { return shogunName[index]; } function validateName(string memory str) public pure returns (bool) { bytes memory b = bytes(str); if (b.length < 1) return false; if (b.length > 25) return false; // Cannot be longer than 25 characters if (b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for (uint256 i; i < b.length; i++) { bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if ( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } function lockToken(uint256[] memory _tokenIds) external onlyStakingContract { for (uint256 i = 0; i < _tokenIds.length; i++) { _isLocked[_tokenIds[i]] = true; } } function unlockToken(uint256[] memory _tokenIds) external onlyStakingContract { for (uint256 i = 0; i < _tokenIds.length; i++) { _isLocked[_tokenIds[i]] = false; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Enumerable) { require(_isLocked[tokenId] == false, "SHOGUN: Token is Locked"); super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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 Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IShogunToken is IERC20 { function updateRewardOnMint(address _user, uint256 _amount) external; function updateReward(address _from, address _to) external; function getReward(address _to) external; function burn(address _from, uint256 _amount) external; function mint(address to, uint256 amount) external; function getTotalClaimable(address _user) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // 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); }
INTERNAL FUNCTIONS
function isSignedBySigner( address sender, bytes memory nonce, bytes memory signature, address signerAddress ) private pure returns (bool) { bytes32 hash = keccak256(abi.encodePacked(sender, nonce)); return signerAddress == hash.recover(signature); }
6,918,186
pragma solidity ^0.4.18; import "./CappedToken.sol"; /** * @title Artist token * @dev Mintable token with a token cap. */ contract ArtistToken is CappedToken { string public constant name = "Tiga Coin"; // solium-disable-line uppercase string public constant symbol = "TIGA"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase uint256 public cap = 10000000 * (10 ** uint256(decimals)); /** * @dev Constructor. */ function ArtistToken() CappedToken(cap) public { } }
Constructor./
function ArtistToken() CappedToken(cap) public { }
6,484,803
// File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol pragma solidity ^0.5.4; interface IntVoteInterface { //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;} modifier votable(bytes32 _proposalId) {revert(); _;} event NewProposal( bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event ExecuteProposal(bytes32 indexed _proposalId, address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VoteProposal( bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CancelProposal(bytes32 indexed _proposalId, address indexed _organization ); event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _numOfChoices number of voting choices * @param _proposalParameters defines the parameters of the voting machine used for this proposal * @param _proposer address * @param _organization address - if this address is zero the msg.sender will be used as the organization address. * @return proposal's id. */ function propose( uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function vote( bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function cancelVote(bytes32 _proposalId) external; function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256); function isVotable(bytes32 _proposalId) external view returns(bool); /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256); /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool); /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max); } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol pragma solidity ^0.5.4; interface VotingMachineCallbacksInterface { function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external returns(bool); function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256); function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256); function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256); } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return 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 OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol pragma solidity ^0.5.4; /** * @title Reputation system * @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust . * A reputation is use to assign influence measure to a DAO'S peers. * Reputation is similar to regular tokens but with one crucial difference: It is non-transferable. * The Reputation contract maintain a map of address to reputation value. * It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address. */ contract Reputation is Ownable { uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event Mint(address indexed _to, uint256 _amount); // Event indicating burning of reputation for an address. event Burn(address indexed _from, uint256 _amount); /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of reputation at a specific block number uint128 value; } // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // Tracks the history of the `totalSupply` of the reputation Checkpoint[] totalSupplyHistory; /// @notice Constructor to create a Reputation constructor( ) public { } /// @dev This function makes it easy to get the total number of reputation /// @return The total number of reputation function totalSupply() public view returns (uint256) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /** * @dev return the reputation amount of a given owner * @param _owner an address of the owner which we want to get his reputation */ function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { return 0; // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of reputation at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of reputation at `_blockNumber` function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } /// @notice Generates `_amount` reputation that are assigned to `_owner` /// @param _user The address that will be assigned the new reputation /// @param _amount The quantity of reputation generated /// @return True if the reputation are generated correctly function mint(address _user, uint256 _amount) public onlyOwner returns (bool) { uint256 curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = balanceOf(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_user], previousBalanceTo + _amount); emit Mint(_user, _amount); return true; } /// @notice Burns `_amount` reputation from `_owner` /// @param _user The address that will lose the reputation /// @param _amount The quantity of reputation to burn /// @return True if the reputation are burned correctly function burn(address _user, uint256 _amount) public onlyOwner returns (bool) { uint256 curTotalSupply = totalSupply(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = balanceOf(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned); updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned); emit Burn(_user, amountBurned); return true; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of reputation at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of reputation being queried function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { if (checkpoints.length == 0) { return 0; } // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) { return checkpoints[checkpoints.length-1].value; } if (_block < checkpoints[0].fromBlock) { return 0; } // Binary search of the value in the array uint256 min = 0; uint256 max = checkpoints.length-1; while (max > min) { uint256 mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of reputation function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal { require(uint128(_value) == _value); //check value is in the 128 bits bounderies if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.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); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @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); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: contracts/controller/DAOToken.sol pragma solidity ^0.5.4; /** * @title DAOToken, base on zeppelin contract. * @dev ERC20 compatible token. It is a mintable, burnable token. */ contract DAOToken is ERC20, ERC20Burnable, Ownable { string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; uint256 public cap; /** * @dev Constructor * @param _name - token name * @param _symbol - token symbol * @param _cap - token cap - 0 value means no cap */ constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. */ function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { if (cap > 0) require(totalSupply().add(_amount) <= cap); _mint(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses */ library Address { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/libs/SafeERC20.sol /* SafeERC20 by daostack. The code is based on a fix by SECBIT Team. USE WITH CAUTION & NO WARRANTY REFERENCE & RELATED READING - https://github.com/ethereum/solidity/issues/4116 - https://medium.com/@chris_77367/explaining-unexpected-reverts-starting-with-solidity-0-4-22-3ada6e82308c - https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca - https://gist.github.com/BrendanChou/88a2eeb80947ff00bcf58ffdafeaeb61 */ pragma solidity ^0.5.4; library SafeERC20 { using Address for address; bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)"))); function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal { // Must be a contract addr first! require(_erc20Addr.isContract()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal { // Must be a contract addr first! require(_erc20Addr.isContract()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal { // Must be a contract addr first! require(_erc20Addr.isContract()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: contracts/controller/Avatar.sol pragma solidity ^0.5.4; /** * @title An Avatar holds tokens, reputation and ether for a controller */ contract Avatar is Ownable { using SafeERC20 for address; string public orgName; DAOToken public nativeToken; Reputation public nativeReputation; event GenericCall(address indexed _contract, bytes _params, bool _success); event SendEther(uint256 _amountInWei, address indexed _to); event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value); event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value); event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value); event ReceiveEther(address indexed _sender, uint256 _value); event MetaData(string _metaData); /** * @dev the constructor takes organization name, native token and reputation system and creates an avatar for a controller */ constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } /** * @dev enables an avatar to receive ethers */ function() external payable { emit ReceiveEther(msg.sender, msg.value); } /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @return bool success or fail * bytes - the return bytes of the called contract's function. */ function genericCall(address _contract, bytes memory _data) public onlyOwner returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-low-level-calls (success, returnValue) = _contract.call(_data); emit GenericCall(_contract, _data, success); } /** * @dev send ethers from the avatar's wallet * @param _amountInWei amount to send in Wei units * @param _to send the ethers to this address * @return bool which represents success */ function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) { _to.transfer(_amountInWei); emit SendEther(_amountInWei, _to); return true; } /** * @dev external token transfer * @param _externalToken the token contract * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value) public onlyOwner returns(bool) { address(_externalToken).safeTransfer(_to, _value); emit ExternalTokenTransfer(address(_externalToken), _to, _value); return true; } /** * @dev external token transfer from a specific account * @param _externalToken the token contract * @param _from the account to spend token from * @param _to the destination address * @param _value the amount of tokens to transfer * @return bool which represents success */ function externalTokenTransferFrom( IERC20 _externalToken, address _from, address _to, uint256 _value ) public onlyOwner returns(bool) { address(_externalToken).safeTransferFrom(_from, _to, _value); emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value); return true; } /** * @dev externalTokenApproval approve the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _value the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value) public onlyOwner returns(bool) { address(_externalToken).safeApprove(_spender, _value); emit ExternalTokenApproval(address(_externalToken), _spender, _value); return true; } /** * @dev metaData emits an event with a string, should contain the hash of some meta data. * @param _metaData a string representing a hash of the meta data * @return bool which represents a success */ function metaData(string memory _metaData) public onlyOwner returns(bool) { emit MetaData(_metaData); return true; } } // File: contracts/universalSchemes/UniversalSchemeInterface.sol pragma solidity ^0.5.4; contract UniversalSchemeInterface { function updateParameters(bytes32 _hashedParameters) public; function getParametersFromController(Avatar _avatar) internal view returns(bytes32); } // File: contracts/globalConstraints/GlobalConstraintInterface.sol pragma solidity ^0.5.4; contract GlobalConstraintInterface { enum CallPhase { Pre, Post, PreAndPost } function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); /** * @dev when return if this globalConstraints is pre, post or both. * @return CallPhase enum indication Pre, Post or PreAndPost. */ function when() public returns(CallPhase); } // File: contracts/controller/ControllerInterface.sol pragma solidity ^0.5.4; /** * @title Controller contract * @dev A controller controls the organizations tokens ,reputation and avatar. * It is subject to a set of schemes and constraints that determine its behavior. * Each scheme has it own parameters and operation permissions. */ interface ControllerInterface { /** * @dev Mint `_amount` of reputation that are assigned to `_to` . * @param _amount amount of reputation to mint * @param _to beneficiary address * @return bool which represents a success */ function mintReputation(uint256 _amount, address _to, address _avatar) external returns(bool); /** * @dev Burns `_amount` of reputation from `_from` * @param _amount amount of reputation to burn * @param _from The address that will lose the reputation * @return bool which represents a success */ function burnReputation(uint256 _amount, address _from, address _avatar) external returns(bool); /** * @dev mint tokens . * @param _amount amount of token to mint * @param _beneficiary beneficiary address * @param _avatar address * @return bool which represents a success */ function mintTokens(uint256 _amount, address _beneficiary, address _avatar) external returns(bool); /** * @dev register or update a scheme * @param _scheme the address of the scheme * @param _paramsHash a hashed configuration of the usage of the scheme * @param _permissions the permissions the new scheme will have * @param _avatar address * @return bool which represents a success */ function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) external returns(bool); /** * @dev unregister a scheme * @param _avatar address * @param _scheme the address of the scheme * @return bool which represents a success */ function unregisterScheme(address _scheme, address _avatar) external returns(bool); /** * @dev unregister the caller's scheme * @param _avatar address * @return bool which represents a success */ function unregisterSelf(address _avatar) external returns(bool); /** * @dev add or update Global Constraint * @param _globalConstraint the address of the global constraint to be added. * @param _params the constraint parameters hash. * @param _avatar the avatar of the organization * @return bool which represents a success */ function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar) external returns(bool); /** * @dev remove Global Constraint * @param _globalConstraint the address of the global constraint to be remove. * @param _avatar the organization avatar. * @return bool which represents a success */ function removeGlobalConstraint (address _globalConstraint, address _avatar) external returns(bool); /** * @dev upgrade the Controller * The function will trigger an event 'UpgradeController'. * @param _newController the address of the new controller. * @param _avatar address * @return bool which represents a success */ function upgradeController(address _newController, Avatar _avatar) external returns(bool); /** * @dev perform a generic call to an arbitrary contract * @param _contract the contract's address to call * @param _data ABI-encoded contract call to call `_contract` address. * @param _avatar the controller's avatar address * @return bool -success * bytes - the return value of the called _contract's function. */ function genericCall(address _contract, bytes calldata _data, Avatar _avatar) external returns(bool, bytes memory); /** * @dev send some ether * @param _amountInWei the amount of ether (in Wei) to send * @param _to address of the beneficiary * @param _avatar address * @return bool which represents a success */ function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar) external returns(bool); /** * @dev send some amount of arbitrary ERC20 Tokens * @param _externalToken the address of the Token Contract * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar) external returns(bool); /** * @dev transfer token "from" address "to" address * One must to approve the amount of tokens which can be spend from the * "from" account.This can be done using externalTokenApprove. * @param _externalToken the address of the Token Contract * @param _from address of the account to send from * @param _to address of the beneficiary * @param _value the amount of ether (in Wei) to send * @param _avatar address * @return bool which represents a success */ function externalTokenTransferFrom( IERC20 _externalToken, address _from, address _to, uint256 _value, Avatar _avatar) external returns(bool); /** * @dev externalTokenApproval approve the spender address to spend a specified amount of tokens * on behalf of msg.sender. * @param _externalToken the address of the Token Contract * @param _spender address * @param _value the amount of ether (in Wei) which the approval is referring to. * @return bool which represents a success */ function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar) external returns(bool); /** * @dev metaData emits an event with a string, should contain the hash of some meta data. * @param _metaData a string representing a hash of the meta data * @param _avatar Avatar * @return bool which represents a success */ function metaData(string calldata _metaData, Avatar _avatar) external returns(bool); /** * @dev getNativeReputation * @param _avatar the organization avatar. * @return organization native reputation */ function getNativeReputation(address _avatar) external view returns(address); function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool); function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32); function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32); function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4); /** * @dev globalConstraintsCount return the global constraint pre and post count * @return uint256 globalConstraintsPre count. * @return uint256 globalConstraintsPost count. */ function globalConstraintsCount(address _avatar) external view returns(uint, uint); function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool); } // File: contracts/universalSchemes/UniversalScheme.sol pragma solidity ^0.5.4; contract UniversalScheme is Ownable, UniversalSchemeInterface { bytes32 public hashedParameters; // For other parameters. function updateParameters( bytes32 _hashedParameters ) public onlyOwner { hashedParameters = _hashedParameters; } /** * @dev get the parameters for the current scheme from the controller */ function getParametersFromController(Avatar _avatar) internal view returns(bytes32) { require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)), "scheme is not registered"); return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.0; /** * @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 ECDSA { /** * @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 signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.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. // 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))) } // 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 { 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: @daostack/infra/contracts/libs/RealMath.sol pragma solidity ^0.5.4; /** * RealMath: fixed-point math library, based on fractional and integer parts. * Using uint256 as real216x40, which isn't in Solidity yet. * Internally uses the wider uint256 for some math. * * Note that for addition, subtraction, and mod (%), you should just use the * built-in Solidity operators. Functions for these operations are not provided. * */ library RealMath { /** * How many total bits are there? */ uint256 constant private REAL_BITS = 256; /** * How many fractional bits are there? */ uint256 constant private REAL_FBITS = 40; /** * What's the first non-fractional bit */ uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS; /** * Raise a real number to any positive integer power */ function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) { uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = REAL_ONE; while (tempExponent != 0) { // While there are still bits set if ((tempExponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base realResult = mul(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; if (tempExponent != 0) { // Do the squaring tempRealBase = mul(tempRealBase, tempRealBase); } } // Return the final result. return realResult; } /** * Create a real from a rational fraction. */ function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) { return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE); } /** * Multiply one real by another. Truncates overflows. */ function mul(uint256 realA, uint256 realB) private pure returns (uint256) { // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. uint256 res = realA * realB; require(res/realA == realB, "RealMath mul overflow"); return (res >> REAL_FBITS); } /** * Divide one real by another real. Truncates overflows. */ function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator)); } } // File: @daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol pragma solidity ^0.5.4; interface ProposalExecuteInterface { function executeProposal(bytes32 _proposalId, int _decision) external returns(bool); } // File: openzeppelin-solidity/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol pragma solidity ^0.5.4; /** * @title GenesisProtocol implementation -an organization's voting machine scheme. */ contract GenesisProtocolLogic is IntVoteInterface { using SafeMath for uint256; using Math for uint256; using RealMath for uint216; using RealMath for uint256; using Address for address; enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod} enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed} //Organization's parameters struct Parameters { uint256 queuedVoteRequiredPercentage; // the absolute vote percentages bar. uint256 queuedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode. uint256 boostedVotePeriodLimit; //the time limit for a proposal to be in boost mode. uint256 preBoostedVotePeriodLimit; //the time limit for a proposal //to be in an preparation state (stable) before boosted. uint256 thresholdConst; //constant for threshold calculation . //threshold =thresholdConst ** (numberOfBoostedProposals) uint256 limitExponentValue;// an upper limit for numberOfBoostedProposals //in the threshold calculation to prevent overflow uint256 quietEndingPeriod; //quite ending period uint256 proposingRepReward;//proposer reputation reward. uint256 votersReputationLossRatio;//Unsuccessful pre booster //voters lose votersReputationLossRatio% of their reputation. uint256 minimumDaoBounty; uint256 daoBountyConst;//The DAO downstake for each proposal is calculate according to the formula //(daoBountyConst * averageBoostDownstakes)/100 . uint256 activationTime;//the point in time after which proposals can be created. //if this address is set so only this address is allowed to vote of behalf of someone else. address voteOnBehalf; } struct Voter { uint256 vote; // YES(1) ,NO(2) uint256 reputation; // amount of voter's reputation bool preBoosted; } struct Staker { uint256 vote; // YES(1) ,NO(2) uint256 amount; // amount of staker's stake uint256 amount4Bounty;// amount of staker's stake used for bounty reward calculation. } struct Proposal { bytes32 organizationId; // the organization unique identifier the proposal is target to. address callbacks; // should fulfill voting callbacks interface. ProposalState state; uint256 winningVote; //the winning vote. address proposer; //the proposal boosted period limit . it is updated for the case of quiteWindow mode. uint256 currentBoostedVotePeriodLimit; bytes32 paramsHash; uint256 daoBountyRemain; //use for checking sum zero bounty claims.it is set at the proposing time. uint256 daoBounty; uint256 totalStakes;// Total number of tokens staked which can be redeemable by stakers. uint256 confidenceThreshold; //The percentage from upper stakes which the caller for the expiration was given. uint256 expirationCallBountyPercentage; uint[3] times; //times[0] - submittedTime //times[1] - boostedPhaseTime //times[2] -preBoostedPhaseTime; bool daoRedeemItsWinnings; // vote reputation mapping(uint256 => uint256 ) votes; // vote reputation mapping(uint256 => uint256 ) preBoostedVotes; // address voter mapping(address => Voter ) voters; // vote stakes mapping(uint256 => uint256 ) stakes; // address staker mapping(address => Staker ) stakers; } event Stake(bytes32 indexed _proposalId, address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event Redeem(bytes32 indexed _proposalId, address indexed _organization, address indexed _beneficiary, uint256 _amount ); event RedeemDaoBounty(bytes32 indexed _proposalId, address indexed _organization, address indexed _beneficiary, uint256 _amount ); event RedeemReputation(bytes32 indexed _proposalId, address indexed _organization, address indexed _beneficiary, uint256 _amount ); event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState); event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState); event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold); mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself. mapping(bytes32=>uint) public orgBoostedProposalsCnt; //organizationId => organization mapping(bytes32 => address ) public organizations; //organizationId => averageBoostDownstakes mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted; uint256 constant public NUM_OF_CHOICES = 2; uint256 constant public NO = 2; uint256 constant public YES = 1; uint256 public proposalsCnt; // Total number of proposals IERC20 public stakingToken; address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; uint256 constant private MAX_BOOSTED_PROPOSALS = 4096; /** * @dev Constructor */ constructor(IERC20 _stakingToken) public { //The GEN token (staking token) address is hard coded in the contract by GEN_TOKEN_ADDRESS . //This will work for a network which already hosted the GEN token on this address (e.g mainnet). //If such contract address does not exist in the network (e.g ganache) //the contract will use the _stakingToken param as the //staking token address. if (address(GEN_TOKEN_ADDRESS).isContract()) { stakingToken = IERC20(GEN_TOKEN_ADDRESS); } else { stakingToken = _stakingToken; } } /** * @dev Check that the proposal is votable * a proposal is votable if it is in one of the following states: * PreBoosted,Boosted,QuietEndingPeriod or Queued */ modifier votable(bytes32 _proposalId) { require(_isVotable(_proposalId)); _; } /** * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being * generated by calculating keccak256 of a incremented counter. * @param _paramsHash parameters hash * @param _proposer address * @param _organization address */ function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization) external returns(bytes32) { // solhint-disable-next-line not-rely-on-time require(now > parameters[_paramsHash].activationTime, "not active yet"); //Check parameters existence. require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50); // Generate a unique ID: bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt)); proposalsCnt = proposalsCnt.add(1); // Open proposal: Proposal memory proposal; proposal.callbacks = msg.sender; proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization)); proposal.state = ProposalState.Queued; // solhint-disable-next-line not-rely-on-time proposal.times[0] = now;//submitted time proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit; proposal.proposer = _proposer; proposal.winningVote = NO; proposal.paramsHash = _paramsHash; if (organizations[proposal.organizationId] == address(0)) { if (_organization == address(0)) { organizations[proposal.organizationId] = msg.sender; } else { organizations[proposal.organizationId] = _organization; } } //calc dao bounty uint256 daoBounty = parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100); if (daoBounty < parameters[_paramsHash].minimumDaoBounty) { proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty; } else { proposal.daoBountyRemain = daoBounty; } proposal.totalStakes = proposal.daoBountyRemain; proposals[proposalId] = proposal; proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;//dao downstake on the proposal emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash); return proposalId; } /** * @dev executeBoosted try to execute a boosted or QuietEndingPeriod proposal if it is expired * @param _proposalId the id of the proposal * @return uint256 expirationCallBounty the bounty amount for the expiration call */ function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod, "proposal state in not Boosted nor QuietEndingPeriod"); require(_execute(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100); require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty); } /** * @dev hash the parameters, save them if necessary, and return the hash value * @param _params a parameters array * _params[0] - _queuedVoteRequiredPercentage, * _params[1] - _queuedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode. * _params[2] - _boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode. * _params[3] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an preparation * state (stable) before boosted. * _params[4] -_thresholdConst * _params[5] -_quietEndingPeriod * _params[6] -_proposingRepReward * _params[7] -_votersReputationLossRatio * _params[8] -_minimumDaoBounty * _params[9] -_daoBountyConst * _params[10] -_activationTime * @param _voteOnBehalf - authorized to vote on behalf of others. */ function setParameters( uint[11] calldata _params, //use array here due to stack too deep issue. address _voteOnBehalf ) external returns(bytes32) { require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100"); require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000"); require(_params[7] <= 100, "votersReputationLossRatio <= 100"); require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod"); require(_params[8] > 0, "minimumDaoBounty should be > 0"); require(_params[9] > 0, "daoBountyConst should be > 0"); bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf); //set a limit for power for a given alpha to prevent overflow uint256 limitExponent = 172;//for alpha less or equal 2 uint256 j = 2; for (uint256 i = 2000; i < 16000; i = i*2) { if ((_params[4] > i) && (_params[4] <= i*2)) { limitExponent = limitExponent/j; break; } j++; } parameters[paramsHash] = Parameters({ queuedVoteRequiredPercentage: _params[0], queuedVotePeriodLimit: _params[1], boostedVotePeriodLimit: _params[2], preBoostedVotePeriodLimit: _params[3], thresholdConst:uint216(_params[4]).fraction(uint216(1000)), limitExponentValue:limitExponent, quietEndingPeriod: _params[5], proposingRepReward: _params[6], votersReputationLossRatio:_params[7], minimumDaoBounty:_params[8], daoBountyConst:_params[9], activationTime:_params[10], voteOnBehalf:_voteOnBehalf }); return paramsHash; } /** * @dev redeem a reward for a successful stake, vote or proposing. * The function use a beneficiary address as a parameter (and not msg.sender) to enable * users to redeem on behalf of someone else. * @param _proposalId the ID of the proposal * @param _beneficiary - the beneficiary address * @return rewards - * [0] stakerTokenReward * [1] voterReputationReward * [2] proposerReputationReward */ // solhint-disable-next-line function-max-lines,code-complexity function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { Proposal storage proposal = proposals[_proposalId]; require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue), "Proposal should be Executed or ExpiredInQueue"); Parameters memory params = parameters[proposal.paramsHash]; uint256 lostReputation; if (proposal.winningVote == YES) { lostReputation = proposal.preBoostedVotes[NO]; } else { lostReputation = proposal.preBoostedVotes[YES]; } lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; if (staker.amount > 0) { uint256 totalStakesLeftAfterCallBounty = totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100)); if (proposal.state == ProposalState.ExpiredInQueue) { //Stakes of a proposal that expires in Queue are sent back to stakers rewards[0] = staker.amount; } else if (staker.vote == proposal.winningVote) { if (staker.vote == YES) { if (proposal.daoBounty < totalStakesLeftAfterCallBounty) { uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty); rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes; } } else { rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes; } } staker.amount = 0; } //dao redeem its winnings if (proposal.daoRedeemItsWinnings == false && _beneficiary == organizations[proposal.organizationId] && proposal.state != ProposalState.ExpiredInQueue && proposal.winningVote == NO) { rewards[0] = rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty); proposal.daoRedeemItsWinnings = true; } //as voter Voter storage voter = proposal.voters[_beneficiary]; if ((voter.reputation != 0) && (voter.preBoosted)) { if (proposal.state == ProposalState.ExpiredInQueue) { //give back reputation for the voter rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100) .add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.sub(rewards[0]); require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].add(rewards[2]) != 0) { VotingMachineCallbacksInterface(proposal.callbacks) .mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId); emit RedeemReputation( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].add(rewards[2]) ); } } /** * @dev redeemDaoBounty a reward for a successful stake. * The function use a beneficiary address as a parameter (and not msg.sender) to enable * users to redeem on behalf of someone else. * @param _proposalId the ID of the proposal * @param _beneficiary - the beneficiary address * @return redeemedAmount - redeem token amount * @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the organization ) */ function redeemDaoBounty(bytes32 _proposalId, address _beneficiary) public returns(uint256 redeemedAmount, uint256 potentialAmount) { Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Executed); uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; Staker storage staker = proposal.stakers[_beneficiary]; if ( (staker.amount4Bounty > 0)&& (staker.vote == proposal.winningVote)&& (proposal.winningVote == YES)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (VotingMachineCallbacksInterface(proposal.callbacks) .balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount); require( VotingMachineCallbacksInterface(proposal.callbacks) .stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } /** * @dev shouldBoost check if a proposal should be shifted to boosted phase. * @param _proposalId the ID of the proposal * @return bool true or false. */ function shouldBoost(bytes32 _proposalId) public view returns(bool) { Proposal memory proposal = proposals[_proposalId]; return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId)); } /** * @dev threshold return the organization's score threshold which required by * a proposal to shift to boosted state. * This threshold is dynamically set and it depend on the number of boosted proposal. * @param _organizationId the organization identifier * @param _paramsHash the organization parameters hash * @return uint256 organization's score threshold as real number. */ function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.pow(power); } /** * @dev hashParameters returns a hash of the given parameters */ function getParametersHash( uint[11] memory _params,//use array here due to stack too deep issue. address _voteOnBehalf ) public pure returns(bytes32) { //double call to keccak256 to avoid deep stack issue when call with too many params. return keccak256( abi.encodePacked( keccak256( abi.encodePacked( _params[0], _params[1], _params[2], _params[3], _params[4], _params[5], _params[6], _params[7], _params[8], _params[9], _params[10]) ), _voteOnBehalf )); } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ // solhint-disable-next-line function-max-lines,code-complexity function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId); //first divide by 100 to prevent overflow uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage; ExecutionState executionState = ExecutionState.None; uint256 averageDownstakesOfBoosted; uint256 confidenceThreshold; if (proposal.votes[proposal.winningVote] > executionBar) { // someone crossed the absolute vote execution bar. if (proposal.state == ProposalState.Queued) { executionState = ExecutionState.QueueBarCrossed; } else if (proposal.state == ProposalState.PreBoosted) { executionState = ExecutionState.PreBoostedBarCrossed; } else { executionState = ExecutionState.BoostedBarCrossed; } proposal.state = ProposalState.Executed; } else { if (proposal.state == ProposalState.Queued) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) { proposal.state = ProposalState.ExpiredInQueue; proposal.winningVote = NO; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId); if (_score(_proposalId) > confidenceThreshold) { //change proposal mode to PreBoosted mode. proposal.state = ProposalState.PreBoosted; // solhint-disable-next-line not-rely-on-time proposal.times[2] = now; proposal.confidenceThreshold = confidenceThreshold; } } } if (proposal.state == ProposalState.PreBoosted) { confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_score(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS)) { //change proposal mode to Boosted mode. proposal.state = ProposalState.Boosted; // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; orgBoostedProposalsCnt[proposal.organizationId]++; //add a value to average -> average = average + ((value - average) / nbValues) averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; // solium-disable-next-line indentation averagesDownstakesOfBoosted[proposal.organizationId] = uint256(int256(averageDownstakesOfBoosted) + ((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _score(_proposalId); if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = confidenceThreshold; emit ConfidenceLevelChange(_proposalId, confidenceThreshold); } } } } if ((proposal.state == ProposalState.Boosted) || (proposal.state == ProposalState.QuietEndingPeriod)) { // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) { proposal.state = ProposalState.Executed; executionState = ExecutionState.BoostedTimeOut; } } if (executionState != ExecutionState.None) { if ((executionState == ExecutionState.BoostedTimeOut) || (executionState == ExecutionState.BoostedBarCrossed)) { orgBoostedProposalsCnt[tmpProposal.organizationId] = orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1); //remove a value from average = ((average * nbValues) - value) / (nbValues - 1); uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId]; if (boostedProposals == 0) { averagesDownstakesOfBoosted[proposal.organizationId] = 0; } else { averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId]; averagesDownstakesOfBoosted[proposal.organizationId] = (averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals; } } emit ExecuteProposal( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPExecuteProposal(_proposalId, executionState); ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit StateChange(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @return bool true - the proposal has been executed * false - otherwise. */ function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { // 0 is not a valid vote. require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_execute(_proposalId)) { return true; } Proposal storage proposal = proposals[_proposalId]; if ((proposal.state != ProposalState.PreBoosted) && (proposal.state != ProposalState.Queued)) { return false; } // enable to increase stake only on the previous stake vote Staker storage staker = proposal.stakers[_staker]; if ((staker.amount > 0) && (staker.vote != _vote)) { return false; } uint256 amount = _amount; require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.add(amount); //update totalRedeemableStakes staker.amount = staker.amount.add(amount); //This is to prevent average downstakes calculation overflow //Note that any how GEN cap is 100000000 ether. require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high"); require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high"); if (_vote == YES) { staker.amount4Bounty = staker.amount4Bounty.add(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]); emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _execute(_proposalId); } /** * @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead * @param _proposalId id of the proposal * @param _voter used in case the vote is cast for someone else * @param _vote a value between 0 to and the proposal's number of choices. * @param _rep how many reputation the voter would like to stake for this vote. * if _rep==0 so the voter full reputation will be use. * @return true in case of proposal execution otherwise false * throws if proposal is not open or if it has been executed * NB: executes the proposal if a decision has been reached */ // solhint-disable-next-line function-max-lines,code-complexity function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2"); if (_execute(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId); require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } // If this voter has already voted, return false. if (proposal.voters[_voter].reputation != 0) { return false; } // The voting itself: proposal.votes[_vote] = rep.add(proposal.votes[_vote]); //check if the current winningVote changed or there is a tie. //for the case there is a tie the current winningVote set to NO. if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) || ((proposal.votes[NO] == proposal.votes[proposal.winningVote]) && proposal.winningVote == YES)) { if (proposal.state == ProposalState.Boosted && // solhint-disable-next-line not-rely-on-time ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { //quietEndingPeriod if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } // solhint-disable-next-line not-rely-on-time proposal.times[1] = now; } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId); } emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _execute(_proposalId); } /** * @dev _score return the proposal score (Confidence level) * For dual choice proposal S = (S+)/(S-) * @param _proposalId the ID of the proposal * @return uint256 proposal score as real number. */ function _score(bytes32 _proposalId) internal view returns(uint256) { Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO])); } /** * @dev _isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function _isVotable(bytes32 _proposalId) internal view returns(bool) { ProposalState pState = proposals[_proposalId].state; return ((pState == ProposalState.PreBoosted)|| (pState == ProposalState.Boosted)|| (pState == ProposalState.QuietEndingPeriod)|| (pState == ProposalState.Queued) ); } } // File: @daostack/infra/contracts/votingMachines/GenesisProtocol.sol pragma solidity ^0.5.4; /** * @title GenesisProtocol implementation -an organization's voting machine scheme. */ contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic { using ECDSA for bytes32; // Digest describing the data the user signs according EIP 712. // Needs to match what is passed to Metamask. bytes32 public constant DELEGATION_HASH_EIP712 = keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce /** * @dev Constructor */ constructor(IERC20 _stakingToken) public // solhint-disable-next-line no-empty-blocks GenesisProtocolLogic(_stakingToken) { } /** * @dev staking function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @return bool true - the proposal has been executed * false - otherwise. */ function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { return _stake(_proposalId, _vote, _amount, msg.sender); } /** * @dev stakeWithSignature function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the betting amount * @param _nonce nonce value ,it is part of the signature to ensure that a signature can be received only once. * @param _signatureType signature type 1 - for web3.eth.sign 2 - for eth_signTypedData according to EIP #712. * @param _signature - signed data by the staker * @return bool true - the proposal has been executed * false - otherwise. */ function stakeWithSignature( bytes32 _proposalId, uint256 _vote, uint256 _amount, uint256 _nonce, uint256 _signatureType, bytes calldata _signature ) external returns(bool) { // Recreate the digest the user signed bytes32 delegationDigest; if (_signatureType == 2) { delegationDigest = keccak256( abi.encodePacked( DELEGATION_HASH_EIP712, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).toEthSignedMessageHash(); } address staker = delegationDigest.recover(_signature); //a garbage staker address due to wrong signature will revert due to lack of approval and funds. require(staker != address(0), "staker address cannot be 0"); require(stakesNonce[staker] == _nonce); stakesNonce[staker] = stakesNonce[staker].add(1); return _stake(_proposalId, _vote, _amount, staker); } /** * @dev voting function * @param _proposalId id of the proposal * @param _vote NO(2) or YES(1). * @param _amount the reputation amount to vote with . if _amount == 0 it will use all voter reputation. * @param _voter voter address * @return bool true - the proposal has been executed * false - otherwise. */ function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) external votable(_proposalId) returns(bool) { Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; address voter; if (params.voteOnBehalf != address(0)) { require(msg.sender == params.voteOnBehalf); voter = _voter; } else { voter = msg.sender; } return internalVote(_proposalId, voter, _vote, _amount); } /** * @dev Cancel the vote of the msg.sender. * cancel vote is not allow in genesisProtocol so this function doing nothing. * This function is here in order to comply to the IntVoteInterface . */ function cancelVote(bytes32 _proposalId) external votable(_proposalId) { //this is not allowed return; } /** * @dev execute check if the proposal has been decided, and if so, execute the proposal * @param _proposalId the id of the proposal * @return bool true - the proposal has been executed * false - otherwise. */ function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) { return _execute(_proposalId); } /** * @dev getNumberOfChoices returns the number of choices possible in this proposal * @return uint256 that contains number of choices */ function getNumberOfChoices(bytes32) external view returns(uint256) { return NUM_OF_CHOICES; } /** * @dev getProposalTimes returns proposals times variables. * @param _proposalId id of the proposal * @return proposals times array */ function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) { return proposals[_proposalId].times; } /** * @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal * @param _proposalId the ID of the proposal * @param _voter the address of the voter * @return uint256 vote - the voters vote * uint256 reputation - amount of reputation committed by _voter to _proposalId */ function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) { Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } /** * @dev voteStatus returns the reputation voted for a proposal for a specific voting choice. * @param _proposalId the ID of the proposal * @param _choice the index in the * @return voted reputation for the given choice */ function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { return proposals[_proposalId].votes[_choice]; } /** * @dev isVotable check if the proposal is votable * @param _proposalId the ID of the proposal * @return bool true or false */ function isVotable(bytes32 _proposalId) external view returns(bool) { return _isVotable(_proposalId); } /** * @dev proposalStatus return the total votes and stakes for a given proposal * @param _proposalId the ID of the proposal * @return uint256 preBoostedVotes YES * @return uint256 preBoostedVotes NO * @return uint256 total stakes YES * @return uint256 total stakes NO */ function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { return ( proposals[_proposalId].preBoostedVotes[YES], proposals[_proposalId].preBoostedVotes[NO], proposals[_proposalId].stakes[YES], proposals[_proposalId].stakes[NO] ); } /** * @dev getProposalOrganization return the organizationId for a given proposal * @param _proposalId the ID of the proposal * @return bytes32 organization identifier */ function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) { return (proposals[_proposalId].organizationId); } /** * @dev getStaker return the vote and stake amount for a given proposal and staker * @param _proposalId the ID of the proposal * @param _staker staker address * @return uint256 vote * @return uint256 amount */ function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } /** * @dev voteStake return the amount stakes for a given proposal and vote * @param _proposalId the ID of the proposal * @param _vote vote number * @return uint256 stake amount */ function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { return proposals[_proposalId].stakes[_vote]; } /** * @dev voteStake return the winningVote for a given proposal * @param _proposalId the ID of the proposal * @return uint256 winningVote */ function winningVote(bytes32 _proposalId) external view returns(uint256) { return proposals[_proposalId].winningVote; } /** * @dev voteStake return the state for a given proposal * @param _proposalId the ID of the proposal * @return ProposalState proposal state */ function state(bytes32 _proposalId) external view returns(ProposalState) { return proposals[_proposalId].state; } /** * @dev isAbstainAllow returns if the voting machine allow abstain (0) * @return bool true or false */ function isAbstainAllow() external pure returns(bool) { return false; } /** * @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine. * @return min - minimum number of choices max - maximum number of choices */ function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) { return (YES, NO); } /** * @dev score return the proposal score * @param _proposalId the ID of the proposal * @return uint256 proposal score. */ function score(bytes32 _proposalId) public view returns(uint256) { return _score(_proposalId); } } // File: contracts/votingMachines/VotingMachineCallbacks.sol pragma solidity ^0.5.4; contract VotingMachineCallbacks is VotingMachineCallbacksInterface { struct ProposalInfo { uint256 blockNumber; // the proposal's block number Avatar avatar; // the proposal's avatar } modifier onlyVotingMachine(bytes32 _proposalId) { require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine"); _; } // VotingMaching -> proposalId -> ProposalInfo mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo; function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external onlyVotingMachine(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar)); } function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external onlyVotingMachine(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar)); } function stakingTokenTransfer( IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external onlyVotingMachine(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (avatar == Avatar(0)) { return false; } return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar); } function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) { return 0; } return _stakingToken.balanceOf(address(avatar)); } function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) { ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber); } function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) { ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId]; if (proposal.avatar == Avatar(0)) { return 0; } return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber); } } // File: universalSchemes/SchemeRegistrar.sol pragma solidity ^0.5.4; /** * @title A registrar for Schemes for organizations * @dev The SchemeRegistrar is used for registering and unregistering schemes at organizations */ contract SchemeRegistrar is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface { event NewSchemeProposal( address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string _descriptionHash ); event RemoveSchemeProposal(address indexed _avatar, bytes32 indexed _proposalId, address indexed _intVoteInterface, address _scheme, string _descriptionHash ); event ProposalExecuted(address indexed _avatar, bytes32 indexed _proposalId, int256 _param); event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId); // a SchemeProposal is a proposal to add or remove a scheme to/from the an organization struct SchemeProposal { address scheme; // bool addScheme; // true: add a scheme, false: remove a scheme. bytes32 parametersHash; bytes4 permissions; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>SchemeProposal)) public organizationsProposals; // A mapping from hashes to parameters (use to store a particular configuration on the controller) struct Parameters { bytes32 voteRegisterParams; bytes32 voteRemoveParams; IntVoteInterface intVote; } mapping(bytes32=>Parameters) public parameters; /** * @dev execution of proposals, can only be called by the voting machine in which the vote is held. * @param _proposalId the ID of the voting in the voting machine * @param _param a parameter of the voting result, 1 yes and 2 is no. */ function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns(bool) { Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar; SchemeProposal memory proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.scheme != address(0)); delete organizationsProposals[address(avatar)][_proposalId]; emit ProposalDeleted(address(avatar), _proposalId); if (_param == 1) { // Define controller and get the params: ControllerInterface controller = ControllerInterface(avatar.owner()); // Add a scheme: if (proposal.addScheme) { require(controller.registerScheme( proposal.scheme, proposal.parametersHash, proposal.permissions, address(avatar)) ); } // Remove a scheme: if (!proposal.addScheme) { require(controller.unregisterScheme(proposal.scheme, address(avatar))); } } emit ProposalExecuted(address(avatar), _proposalId, _param); return true; } /** * @dev hash the parameters, save them if necessary, and return the hash value */ function setParameters( bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public returns(bytes32) { bytes32 paramsHash = getParametersHash(_voteRegisterParams, _voteRemoveParams, _intVote); parameters[paramsHash].voteRegisterParams = _voteRegisterParams; parameters[paramsHash].voteRemoveParams = _voteRemoveParams; parameters[paramsHash].intVote = _intVote; return paramsHash; } function getParametersHash( bytes32 _voteRegisterParams, bytes32 _voteRemoveParams, IntVoteInterface _intVote ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteRegisterParams, _voteRemoveParams, _intVote)); } /** * @dev create a proposal to register a scheme * @param _avatar the address of the organization the scheme will be registered for * @param _scheme the address of the scheme to be registered * @param _parametersHash a hash of the configuration of the _scheme * @param _permissions the permission of the scheme to be registered * @param _descriptionHash proposal's description hash * @return a proposal Id * @dev NB: not only proposes the vote, but also votes for it */ function proposeScheme( Avatar _avatar, address _scheme, bytes32 _parametersHash, bytes4 _permissions, string memory _descriptionHash ) public returns(bytes32) { // propose require(_scheme != address(0), "scheme cannot be zero"); Parameters memory controllerParams = parameters[getParametersFromController(_avatar)]; bytes32 proposalId = controllerParams.intVote.propose( 2, controllerParams.voteRegisterParams, msg.sender, address(_avatar) ); SchemeProposal memory proposal = SchemeProposal({ scheme: _scheme, parametersHash: _parametersHash, addScheme: true, permissions: _permissions }); emit NewSchemeProposal( address(_avatar), proposalId, address(controllerParams.intVote), _scheme, _parametersHash, _permissions, _descriptionHash ); organizationsProposals[address(_avatar)][proposalId] = proposal; proposalsInfo[address(controllerParams.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } /** * @dev propose to remove a scheme for a controller * @param _avatar the address of the controller from which we want to remove a scheme * @param _scheme the address of the scheme we want to remove * @param _descriptionHash proposal description hash * NB: not only registers the proposal, but also votes for it */ function proposeToRemoveScheme(Avatar _avatar, address _scheme, string memory _descriptionHash) public returns(bytes32) { require(_scheme != address(0), "scheme cannot be zero"); bytes32 paramsHash = getParametersFromController(_avatar); Parameters memory params = parameters[paramsHash]; IntVoteInterface intVote = params.intVote; bytes32 proposalId = intVote.propose(2, params.voteRemoveParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId].scheme = _scheme; emit RemoveSchemeProposal(address(_avatar), proposalId, address(intVote), _scheme, _descriptionHash); proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar }); return proposalId; } }
Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead _proposalId id of the proposal _voter used in case the vote is cast for someone else _vote a value between 0 to and the proposal's number of choices. _rep how many reputation the voter would like to stake for this vote. if _rep==0 so the voter full reputation will be use. return true in case of proposal execution otherwise false throws if proposal is not open or if it has been executed NB: executes the proposal if a decision has been reached/ solhint-disable-next-line function-max-lines,code-complexity If this voter has already voted, return false. solhint-disable-next-line not-rely-on-timequietEndingPeriod
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2"); if (_execute(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; require(reputation > 0, "_voter must have reputation"); require(reputation >= _rep, "reputation >= _rep"); uint256 rep = _rep; if (rep == 0) { rep = reputation; } if (proposal.voters[_voter].reputation != 0) { return false; } ((proposal.votes[NO] == proposal.votes[proposal.winningVote]) && proposal.winningVote == YES)) { if (proposal.state == ProposalState.Boosted && ((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))|| proposal.state == ProposalState.QuietEndingPeriod) { if (proposal.state != ProposalState.QuietEndingPeriod) { proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod; proposal.state = ProposalState.QuietEndingPeriod; } } proposal.winningVote = _vote; } proposal.voters[_voter] = Voter({ reputation: rep, vote: _vote, preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) }); if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) { proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100; VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId); } emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _execute(_proposalId); }
1,835,351
pragma solidity ^0.4.11; // ---------------------------------------------------------------------------- // The Useless Reserve Bank Token Contract // // - If you need welfare support, claim your free URB token entitlements from // the gubberment. // // Call the default function `()` to claim 1,000 URBs by sending a 0 value // transaction to this contract address. // // NOTE that any ethers sent with this call will fill the coffers of this // gubberment&#39;s token contract. // // - If you consider yourself to be in the top 1%, make a donation for world // peace. // // Call `philanthropise({message})` and 100,000 URBs will be sent to // your account for each ether you donate. Fractions of ethers are always // accepted. // // Your message and donation amount will be etched into the blockchain // forever, to recognise your generousity. Thank you. // // As you are making this world a better place, your philanthropic donation // is eligible for a special discounted 20% tax rate. Your taxes will be // shared equally among the current gubberment treasury officials. // Thank you. // // - If you have fallen into hard times and have accumulated some URB tokens, // you can convert your URBs into ethers. // // Liquidate your URBs by calling `liquidate(amountOfTokens)`, where // 1 URB is specified as 1,000,000,000,000,000,000 (18 decimal places). // You will receive 1 ether for each 30,000 URBs you liquidate. // // NOTE that this treasury contract can only dish out ethers in exchange // for URB tokens **IF** there are sufficient ethers in this contract. // Only 25% of the ether balance of this contract can be claimed at any // one time. // // - Any gifts of ERC20 tokens send to this contract will be solemnly accepted // by the gubberment. The treasury will at it&#39;s discretion disburst these // gifts to friendly officials. Thank you. // // Token Contract: // - Symbol: URB // - Name: Useless Reserve Bank // - Decimals: 18 // - Contract address; 0x7a83db2d2737c240c77c7c5d8be8c2ad68f6ff23 // - Block: 4,000,000 // // Usage: // - Watch this contract at address: // 0x7A83dB2d2737C240C77C7C5D8be8c2aD68f6FF23 // with the application binary interface published at: // https://etherscan.io/address/0x7a83db2d2737c240c77c7c5d8be8c2ad68f6ff23#code // to execute this token contract functions in Ethereum Wallet / Mist or // MyEtherWallet. // // User Functions: // - default send function () // Users can send 0 or more ethers to this contract address and receive back // 1000 URBs // // - philanthropise(name) // Rich users can send a non-zero ether amount, calling this function with // a name or dedication message. 100,000 URBs will be minted for each // 1 ETH sent. Fractions of an ether can be sent. // Remember that your goodwill karma is related to the size of your donation. // // - liquidate(amountOfTokens) // URB token holders can liquidate part or all of their tokens and receive // back 1 ether for every 30,000 URBs liquidated, ONLY if the ethers to be // received is less than 25% of the outstanding ETH balance of this contract // // - bribe() // Send ethers directly to the gubberment treasury officials. Your ethers // will be distributed equally among the current treasury offcials. // // Info Functions: // - currentEtherBalance() // Returns the current ether balance of this contract. // // - currentTokenBalance() // Returns the total supply of URB tokens, where 1 URB is represented as // 1,000,000,000,000,000,000 (18 decimal places). // // - numberOfTreasuryOfficials() // Returns the number of officials on the payroll of the gubberment // treasury. // // Gubberment Functions: // - pilfer(amount) // Gubberment officials can pilfer any ethers in this contract when necessary. // // - acceptGiftTokens(tokenAddress) // The gubberment can accept any ERC20-compliant gift tokens send to this // contract. // // - replaceOfficials([accounts]) // The gubberment can sack and replace all it&#39;s treasury officials in one go. // // Standard ERC20 Functions: // - balanceOf(account) // - totalSupply // - transfer(to, amount) // - approve(spender, amount) // - transferFrom(owner, spender, amount) // // Yes, I made it into block 4,000,000 . // // Remember to make love and peace, not war! // // (c) The Gubberment 2017. The MIT Licence. // ---------------------------------------------------------------------------- contract Gubberment { address public gubberment; address public newGubberment; event GubbermentOverthrown(address indexed _from, address indexed _to); function Gubberment() { gubberment = msg.sender; } modifier onlyGubberment { if (msg.sender != gubberment) throw; _; } function coupDetat(address _newGubberment) onlyGubberment { newGubberment = _newGubberment; } function gubbermentOverthrown() { if (msg.sender == newGubberment) { GubbermentOverthrown(gubberment, newGubberment); gubberment = newGubberment; } } } // ERC Token Standard #20 - https://github.com/ethereum/EIPs/issues/20 contract ERC20Token { // ------------------------------------------------------------------------ // Balances for each account // ------------------------------------------------------------------------ mapping(address => uint) balances; // ------------------------------------------------------------------------ // Owner of account approves the transfer of an amount to another account // ------------------------------------------------------------------------ mapping(address => mapping (address => uint)) allowed; // ------------------------------------------------------------------------ // Total token supply // ------------------------------------------------------------------------ uint public totalSupply; // ------------------------------------------------------------------------ // Get the account balance of another account with address _owner // ------------------------------------------------------------------------ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } // ------------------------------------------------------------------------ // Transfer the balance from owner&#39;s account to another account // ------------------------------------------------------------------------ function transfer(address _to, uint _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Allow _spender to withdraw from your account, multiple times, up to the // _value amount. If this function is called again it overwrites the // current allowance with _value. // ------------------------------------------------------------------------ function approve( address _spender, uint _amount ) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } // ------------------------------------------------------------------------ // Spender of tokens transfer an amount of tokens from the token owner&#39;s // balance to the spender&#39;s account. The owner of the tokens must already // have approve(...)-d this transfer // ------------------------------------------------------------------------ function transferFrom( address _from, address _to, uint _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance( address _owner, address _spender ) constant returns (uint remaining) { return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract UselessReserveBank is ERC20Token, Gubberment { // ------------------------------------------------------------------------ // Token information // ------------------------------------------------------------------------ string public constant symbol = "URB"; string public constant name = "Useless Reserve Bank"; uint8 public constant decimals = 18; uint public constant WELFARE_HANDOUT = 1000; uint public constant ONEPERCENT_TOKENS_PER_ETH = 100000; uint public constant LIQUIDATION_TOKENS_PER_ETH = 30000; address[] public treasuryOfficials; uint public constant TAXRATE = 20; uint public constant LIQUIDATION_RESERVE_RATIO = 75; uint public totalTaxed; uint public totalBribery; uint public totalPilfered; uint public constant SENDING_BLOCK = 3999998; function UselessReserveBank() { treasuryOfficials.push(0xDe18789c4d65DC8ecE671A4145F32F1590c4D802); treasuryOfficials.push(0x8899822D031891371afC369767511164Ef21e55c); } // ------------------------------------------------------------------------ // Just give the welfare handouts // ------------------------------------------------------------------------ function () payable { uint tokens = WELFARE_HANDOUT * 1 ether; totalSupply += tokens; balances[msg.sender] += tokens; WelfareHandout(msg.sender, tokens, totalSupply, msg.value, this.balance); Transfer(0x0, msg.sender, tokens); } event WelfareHandout(address indexed recipient, uint tokens, uint newTotalSupply, uint ethers, uint newEtherBalance); // ------------------------------------------------------------------------ // If you consider yourself rich, donate for world peace // ------------------------------------------------------------------------ function philanthropise(string name) payable { // Sending something real? require(msg.value > 0); // Calculate the number of tokens uint tokens = msg.value * ONEPERCENT_TOKENS_PER_ETH; // Assign tokens to account and inflate total supply balances[msg.sender] += tokens; totalSupply += tokens; // Calculate and forward taxes to the treasury uint taxAmount = msg.value * TAXRATE / 100; if (taxAmount > 0) { totalTaxed += taxAmount; uint taxPerOfficial = taxAmount / treasuryOfficials.length; for (uint i = 0; i < treasuryOfficials.length; i++) { treasuryOfficials[i].transfer(taxPerOfficial); } } Philanthropy(msg.sender, name, tokens, totalSupply, msg.value, this.balance, totalTaxed); Transfer(0x0, msg.sender, tokens); } event Philanthropy(address indexed buyer, string name, uint tokens, uint newTotalSupply, uint ethers, uint newEtherBalance, uint totalTaxed); // ------------------------------------------------------------------------ // Liquidate your tokens for ETH, if this contract has sufficient ETH // ------------------------------------------------------------------------ function liquidate(uint amountOfTokens) { // Account must have sufficient tokens require(amountOfTokens <= balances[msg.sender]); // Burn tokens balances[msg.sender] -= amountOfTokens; totalSupply -= amountOfTokens; // Calculate ETH to exchange uint ethersToSend = amountOfTokens / LIQUIDATION_TOKENS_PER_ETH; // Is there sufficient ETH to support this liquidation? require(ethersToSend > 0 && ethersToSend <= (this.balance * (100 - LIQUIDATION_RESERVE_RATIO) / 100)); // Log message Liquidate(msg.sender, amountOfTokens, totalSupply, ethersToSend, this.balance - ethersToSend); Transfer(msg.sender, 0x0, amountOfTokens); // Send ETH msg.sender.transfer(ethersToSend); } event Liquidate(address indexed seller, uint tokens, uint newTotalSupply, uint ethers, uint newEtherBalance); // ------------------------------------------------------------------------ // Gubberment officials will accept 100% of bribes // ------------------------------------------------------------------------ function bribe() payable { // Briber must be offering something real require(msg.value > 0); // Do we really need to keep track of the total bribes? totalBribery += msg.value; Bribed(msg.value, totalBribery); uint bribePerOfficial = msg.value / treasuryOfficials.length; for (uint i = 0; i < treasuryOfficials.length; i++) { treasuryOfficials[i].transfer(bribePerOfficial); } } event Bribed(uint amount, uint newTotalBribery); // ------------------------------------------------------------------------ // Gubberment officials can pilfer out of necessity // ------------------------------------------------------------------------ function pilfer(uint amount) onlyGubberment { // Cannot pilfer more than the contract balance require(amount > this.balance); // Do we really need to keep track of the total pilfered amounts? totalPilfered += amount; Pilfered(amount, totalPilfered, this.balance - amount); uint amountPerOfficial = amount / treasuryOfficials.length; for (uint i = 0; i < treasuryOfficials.length; i++) { treasuryOfficials[i].transfer(amountPerOfficial); } } event Pilfered(uint amount, uint totalPilfered, uint newEtherBalance); // ------------------------------------------------------------------------ // Accept any ERC20 gifts // ------------------------------------------------------------------------ function acceptGiftTokens(address tokenAddress) onlyGubberment returns (bool success) { ERC20Token token = ERC20Token(tokenAddress); uint amount = token.balanceOf(this); return token.transfer(gubberment, amount); } // ------------------------------------------------------------------------ // Change gubberment officials // ------------------------------------------------------------------------ function replaceOfficials(address[] newOfficials) onlyGubberment { treasuryOfficials = newOfficials; } // ------------------------------------------------------------------------ // Information function // ------------------------------------------------------------------------ function currentEtherBalance() constant returns (uint) { return this.balance; } function currentTokenBalance() constant returns (uint) { return totalSupply; } function numberOfTreasuryOfficials() constant returns (uint) { return treasuryOfficials.length; } }
------------------------------------------------------------------------ Transfer the balance from owner&39;s account to another account ------------------------------------------------------------------------
function transfer(address _to, uint _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; return false; } }
6,710,295
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol
to who receive tokens user who pay dTokens token original token address dTokenAmount dtoken the token record amount used for calculate user withdraw amount this function could be called from d3Proxy, so we need "user" param In the meantime, some users may hope to use this function directly, to prevent these users fill "user" param with wrong addresses, we use "msg.sender" param to check.
function userWithdraw(address to, address user, address token, uint256 dTokenAmount) external nonReentrant allowedToken(token) returns(uint256 amount) { accrueInterest(token); AssetInfo storage info = assetInfo[token]; require(dTokenAmount <= IDToken(info.dToken).balanceOf(msg.sender), Errors.DTOKEN_BALANCE_NOT_ENOUGH); amount = dTokenAmount.mul(_getExchangeRate(token)); IDToken(info.dToken).burn(msg.sender, dTokenAmount); IERC20(token).safeTransfer(to, amount); info.balance = info.balance - amount; emit UserWithdraw(msg.sender, user, token, amount, dTokenAmount); }
4,285,634
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // solhint-disable-line /** * @dev Constant values shared across mixins. */ abstract contract Constants { uint256 internal constant BASIS_POINTS = 10000; } interface ICHIARTNFT721 { function tokenCreator(uint256 tokenId) external view returns (address payable); } /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @notice A mixin that stores a reference to the Chiart treasury contract. */ abstract contract ChiartTreasuryNode is Initializable { using AddressUpgradeable for address payable; address payable private treasury; /** * @dev Called once after the initial deployment to set the Chiart treasury address. */ function _initializeChiartTreasuryNode(address payable _treasury) internal initializer { require(_treasury.isContract(), "ChiartTreasuryNode: Address is not a contract"); treasury = _treasury; } /** * @notice Returns the address of the Chiart treasury. */ function getChiartTreasury() public view returns (address payable) { return treasury; } // `______gap` is added to each mixin to allow adding new data slots or additional mixins in an upgrade-safe way. uint256[2000] private __gap; } /** * @notice Allows a contract to leverage an admin role defined by the Chiart contract. */ abstract contract ChiartAdminRole is ChiartTreasuryNode { // This file uses 0 data slots (other than what's included via ChiartTreasuryNode) modifier onlyChiartAdmin() { require( IAdminRole(getChiartTreasury()).isAdmin(msg.sender), "ChiartAdminRole: caller does not have the Admin role" ); _; } } /** * @notice A place for common modifiers and functions used by various NFTMarket mixins, if any. * @dev This also leaves a gap which can be used to add a new mixin to the top of the inheritance tree. */ abstract contract NFTMarketCore { /** * @dev If the auction did not have an escrowed seller to return, this falls back to return the current owner. * This allows functions to calculate the correct fees before the NFT has been listed in auction. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual returns (address) { return IERC721Upgradeable(nftContract).ownerOf(tokenId); } // 50 slots were consumed by adding ReentrancyGuardUpgradeable uint256[950] private ______gap; } /** * @notice Attempt to send ETH and if the transfer fails or runs out of gas, store the balance * for future withdrawal instead. */ abstract contract SendValueWithFallbackWithdraw is ReentrancyGuardUpgradeable { using AddressUpgradeable for address payable; using SafeMathUpgradeable for uint256; mapping(address => uint256) private pendingWithdrawals; event WithdrawPending(address indexed user, uint256 amount); event Withdrawal(address indexed user, uint256 amount); /** * @notice Returns how much funds are available for manual withdraw due to failed transfers. */ function getPendingWithdrawal(address user) public view returns (uint256) { return pendingWithdrawals[user]; } /** * @notice Allows a user to manually withdraw funds which originally failed to transfer. */ function withdraw() public nonReentrant { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "No funds are pending withdrawal"); pendingWithdrawals[msg.sender] = 0; msg.sender.sendValue(amount); emit Withdrawal(msg.sender, amount); } function _sendValueWithFallbackWithdraw(address payable user, uint256 amount) internal { if (amount == 0) { return; } // Cap the gas to prevent consuming all available gas to block a tx from completing successfully // solhint-disable-next-line avoid-low-level-calls (bool success, ) = user.call{ value: amount, gas: 20000 }(""); if (!success) { // Record failed sends for a withdrawal later // Transfers could fail if sent to a multisig with non-trivial receiver logic // solhint-disable-next-line reentrancy pendingWithdrawals[user] = pendingWithdrawals[user].add(amount); emit WithdrawPending(user, amount); } } uint256[499] private ______gap; } /** * @notice A mixin for associating creators to NFTs. * @dev In the future this may store creators directly in order to support NFTs created on a different platform. */ abstract contract NFTMarketCreators is ReentrancyGuardUpgradeable // Adding this unused mixin to help with linearization { /** * @dev If the creator is not available then 0x0 is returned. Downstream this indicates that the creator * fee should be sent to the current seller instead. * This may apply when selling NFTs that were not minted on Chiart. */ function getCreator(address nftContract, uint256 tokenId) internal view returns (address payable) { try ICHIARTNFT721(nftContract).tokenCreator(tokenId) returns (address payable creator) { return creator; } catch { return address(0); } } // 500 slots were added via the new SendValueWithFallbackWithdraw mixin uint256[500] private ______gap; } /** * @notice A mixin to distribute funds when an NFT is sold. */ abstract contract NFTMarketFees is Constants, Initializable, ChiartTreasuryNode, NFTMarketCore, NFTMarketCreators, SendValueWithFallbackWithdraw { using SafeMathUpgradeable for uint256; event MarketFeesUpdated( uint256 primaryChiartFeeBasisPoints, uint256 secondaryChiartFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ); uint256 private _primaryChiartFeeBasisPoints; uint256 private _secondaryChiartFeeBasisPoints; uint256 private _secondaryCreatorFeeBasisPoints; mapping(address => mapping(uint256 => bool)) private nftContractToTokenIdToFirstSaleCompleted; /** * @notice Returns true if the given NFT has not been sold in this market previously and is being sold by the creator. */ function getIsPrimary(address nftContract, uint256 tokenId) public view returns (bool) { return _getIsPrimary(nftContract, tokenId, _getSellerFor(nftContract, tokenId)); } /** * @dev A helper that determines if this is a primary sale given the current seller. * This is a minor optimization to use the seller if already known instead of making a redundant lookup call. */ function _getIsPrimary( address nftContract, uint256 tokenId, address seller ) private view returns (bool) { // By checking if the first sale has been completed first we can short circuit getCreator which is an external call. return !nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] && getCreator(nftContract, tokenId) == seller; } /** * @notice Returns the current fee configuration in basis points. */ function getFeeConfig() public view returns ( uint256 primaryChiartFeeBasisPoints, uint256 secondaryChiartFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) { return (_primaryChiartFeeBasisPoints, _secondaryChiartFeeBasisPoints, _secondaryCreatorFeeBasisPoints); } /** * @notice Returns how funds will be distributed for a sale at the given price point. * @dev This could be used to present exact fee distributing on listing or before a bid is placed. */ function getFees( address nftContract, uint256 tokenId, uint256 price ) public view returns ( uint256 chiartFee, uint256 creatorSecondaryFee, uint256 ownerRev ) { return _getFees(nftContract, tokenId, _getSellerFor(nftContract, tokenId), price); } /** * @dev Calculates how funds should be distributed for the given sale details. * If this is a primary sale, the creator revenue will appear as `ownerRev`. */ function _getFees( address nftContract, uint256 tokenId, address seller, uint256 price ) public view returns ( uint256 chiartFee, uint256 creatorSecondaryFee, uint256 ownerRev ) { uint256 chiartFeeBasisPoints; if (_getIsPrimary(nftContract, tokenId, seller)) { chiartFeeBasisPoints = _primaryChiartFeeBasisPoints; // On a primary sale, the creator is paid the remainder via `ownerRev`. } else { chiartFeeBasisPoints = _secondaryChiartFeeBasisPoints; // SafeMath is not required when dividing by a constant value > 0. creatorSecondaryFee = price.mul(_secondaryCreatorFeeBasisPoints) / BASIS_POINTS; } // SafeMath is not required when dividing by a constant value > 0. chiartFee = price.mul(chiartFeeBasisPoints) / BASIS_POINTS; ownerRev = price.sub(chiartFee).sub(creatorSecondaryFee); } /** * @dev Distributes funds to chiart, creator, and NFT owner after a sale. */ function _distributeFunds( address nftContract, uint256 tokenId, address payable seller, uint256 price ) internal returns ( uint256 chiartFee, uint256 creatorFee, uint256 ownerRev ) { (chiartFee, creatorFee, ownerRev) = _getFees(nftContract, tokenId, seller, price); // Anytime fees are distributed that indicates the first sale is complete, // which will not change state during a secondary sale. // This must come after the `_getFees` call above as this state is considered in the function. nftContractToTokenIdToFirstSaleCompleted[nftContract][tokenId] = true; _sendValueWithFallbackWithdraw(getChiartTreasury(), chiartFee); if (creatorFee > 0) { address payable creator = getCreator(nftContract, tokenId); if (creator == address(0)) { // If the creator is unknown, send all revenue to the current seller instead. ownerRev = ownerRev.add(creatorFee); creatorFee = 0; } else { _sendValueWithFallbackWithdraw(creator, creatorFee); } } _sendValueWithFallbackWithdraw(seller, ownerRev); } /** * @notice Allows Chiart to change the market fees. */ function _updateMarketFees( uint256 primaryChiartFeeBasisPoints, uint256 secondaryChiartFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) internal { require(primaryChiartFeeBasisPoints < BASIS_POINTS, "NFTMarketFees: Fees >= 100%"); require( secondaryChiartFeeBasisPoints.add(secondaryCreatorFeeBasisPoints) < BASIS_POINTS, "NFTMarketFees: Fees >= 100%" ); _primaryChiartFeeBasisPoints = primaryChiartFeeBasisPoints; _secondaryChiartFeeBasisPoints = secondaryChiartFeeBasisPoints; _secondaryCreatorFeeBasisPoints = secondaryCreatorFeeBasisPoints; emit MarketFeesUpdated( primaryChiartFeeBasisPoints, secondaryChiartFeeBasisPoints, secondaryCreatorFeeBasisPoints ); } uint256[1000] private ______gap; } /** * @notice An abstraction layer for auctions. * @dev This contract can be expanded with reusable calls and data as more auction types are added. */ abstract contract NFTMarketAuction { /** * @dev A global id for auctions of any type. */ uint256 private nextAuctionId; function _initializeNFTMarketAuction() internal { nextAuctionId = 1; } function _getNextAndIncrementAuctionId() internal returns (uint256) { return nextAuctionId++; } uint256[1000] private ______gap; } /** * @notice Manages a reserve price auction for NFTs. */ abstract contract NFTMarketReserveAuction is Constants, NFTMarketCore, ReentrancyGuardUpgradeable, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction { using SafeMathUpgradeable for uint256; struct ReserveAuction { address nftContract; uint256 tokenId; address payable seller; uint256 duration; uint256 extensionDuration; uint256 endTime; address payable bidder; uint256 amount; } mapping(address => mapping(uint256 => uint256)) private nftContractToTokenIdToAuctionId; mapping(uint256 => ReserveAuction) private auctionIdToAuction; uint256 private _minPercentIncrementInBasisPoints; // This variable was used in an older version of the contract, left here as a gap to ensure upgrade compatibility uint256 private ______gap_was_maxBidIncrementRequirement; uint256 private _duration; // These variables were used in an older version of the contract, left here as gaps to ensure upgrade compatibility uint256 private ______gap_was_extensionDuration; uint256 private ______gap_was_goLiveDate; // Cap the max duration so that overflows will not occur uint256 private constant MAX_MAX_DURATION = 1000 days; uint256 private constant EXTENSION_DURATION = 15 minutes; event ReserveAuctionConfigUpdated( uint256 minPercentIncrementInBasisPoints, uint256 maxBidIncrementRequirement, uint256 duration, uint256 extensionDuration, uint256 goLiveDate ); event ReserveAuctionCreated( address indexed seller, address indexed nftContract, uint256 indexed tokenId, uint256 duration, uint256 extensionDuration, uint256 reservePrice, uint256 auctionId ); event ReserveAuctionUpdated(uint256 indexed auctionId, uint256 reservePrice); event ReserveAuctionCanceled(uint256 indexed auctionId); event ReserveAuctionBidPlaced(uint256 indexed auctionId, address indexed bidder, uint256 amount, uint256 endTime); event ReserveAuctionFinalized( uint256 indexed auctionId, address indexed seller, address indexed bidder, uint256 f8nFee, uint256 creatorFee, uint256 ownerRev ); modifier onlyValidAuctionConfig(uint256 reservePrice) { require(reservePrice > 0, "NFTMarketReserveAuction: Reserve price must be at least 1 wei"); _; } /** * @notice Returns auction details for a given auctionId. */ function getReserveAuction(uint256 auctionId) public view returns (ReserveAuction memory) { return auctionIdToAuction[auctionId]; } /** * @notice Returns the auctionId for a given NFT, or 0 if no auction is found. * @dev If an auction is canceled, it will not be returned. However the auction may be over and pending finalization. */ function getReserveAuctionIdFor(address nftContract, uint256 tokenId) public view returns (uint256) { return nftContractToTokenIdToAuctionId[nftContract][tokenId]; } /** * @dev Returns the seller that put a given NFT into escrow, * or bubbles the call up to check the current owner if the NFT is not currently in escrow. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override returns (address) { address seller = auctionIdToAuction[nftContractToTokenIdToAuctionId[nftContract][tokenId]].seller; if (seller == address(0)) { return super._getSellerFor(nftContract, tokenId); } return seller; } /** * @notice Returns the current configuration for reserve auctions. */ function getReserveAuctionConfig() public view returns (uint256 minPercentIncrementInBasisPoints, uint256 duration) { minPercentIncrementInBasisPoints = _minPercentIncrementInBasisPoints; duration = _duration; } function _initializeNFTMarketReserveAuction() internal { _duration = 24 hours; // A sensible default value } function _updateReserveAuctionConfig(uint256 minPercentIncrementInBasisPoints, uint256 duration) internal { require(minPercentIncrementInBasisPoints <= BASIS_POINTS, "NFTMarketReserveAuction: Min increment must be <= 100%"); // Cap the max duration so that overflows will not occur require(duration <= MAX_MAX_DURATION, "NFTMarketReserveAuction: Duration must be <= 1000 days"); require(duration >= EXTENSION_DURATION, "NFTMarketReserveAuction: Duration must be >= EXTENSION_DURATION"); _minPercentIncrementInBasisPoints = minPercentIncrementInBasisPoints; _duration = duration; // We continue to emit unused configuration variables to simplify the subgraph integration. emit ReserveAuctionConfigUpdated(minPercentIncrementInBasisPoints, 0, duration, EXTENSION_DURATION, 0); } /** * @notice Creates an auction for the given NFT. * The NFT is held in escrow until the auction is finalized or canceled. */ function createReserveAuction( address nftContract, uint256 tokenId, uint256 reservePrice ) public onlyValidAuctionConfig(reservePrice) nonReentrant { // If an auction is already in progress then the NFT would be in escrow and the modifier would have failed uint256 auctionId = _getNextAndIncrementAuctionId(); nftContractToTokenIdToAuctionId[nftContract][tokenId] = auctionId; auctionIdToAuction[auctionId] = ReserveAuction( nftContract, tokenId, msg.sender, _duration, EXTENSION_DURATION, 0, // endTime is only known once the reserve price is met address(0), // bidder is only known once a bid has been placed reservePrice ); IERC721Upgradeable(nftContract).transferFrom(msg.sender, address(this), tokenId); emit ReserveAuctionCreated( msg.sender, nftContract, tokenId, _duration, EXTENSION_DURATION, reservePrice, auctionId ); } /** * @notice If an auction has been created but has not yet received bids, the configuration * such as the reservePrice may be changed by the seller. */ function updateReserveAuction(uint256 auctionId, uint256 reservePrice) public onlyValidAuctionConfig(reservePrice) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); auction.amount = reservePrice; emit ReserveAuctionUpdated(auctionId, reservePrice); } /** * @notice If an auction has been created but has not yet received bids, it may be canceled by the seller. * The NFT is returned to the seller from escrow. */ function cancelReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction"); require(auction.endTime == 0, "NFTMarketReserveAuction: Auction in progress"); delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId]; delete auctionIdToAuction[auctionId]; IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.seller, auction.tokenId); emit ReserveAuctionCanceled(auctionId); } /** * @notice A bidder may place a bid which is at least the value defined by `getMinBidAmount`. * If this is the first bid on the auction, the countdown will begin. * If there is already an outstanding bid, the previous bidder will be refunded at this time * and if the bid is placed in the final moments of the auction, the countdown may be extended. */ function placeBid(uint256 auctionId) public payable nonReentrant { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require(auction.amount != 0, "NFTMarketReserveAuction: Auction not found"); if (auction.endTime == 0) { // If this is the first bid, ensure it's >= the reserve price require(auction.amount <= msg.value, "NFTMarketReserveAuction: Bid must be at least the reserve price"); } else { // If this bid outbids another, confirm that the bid is at least x% greater than the last require(auction.endTime >= block.timestamp, "NFTMarketReserveAuction: Auction is over"); require(auction.bidder != msg.sender, "NFTMarketReserveAuction: You already have an outstanding bid"); uint256 minAmount = _getMinBidAmountForReserveAuction(auction.amount); require(msg.value >= minAmount, "NFTMarketReserveAuction: Bid amount too low"); } if (auction.endTime == 0) { auction.amount = msg.value; auction.bidder = msg.sender; // On the first bid, the endTime is now + duration auction.endTime = block.timestamp + auction.duration; } else { // Cache and update bidder state before a possible reentrancy (via the value transfer) uint256 originalAmount = auction.amount; address payable originalBidder = auction.bidder; auction.amount = msg.value; auction.bidder = msg.sender; // When a bid outbids another, check to see if a time extension should apply. if (auction.endTime - block.timestamp < auction.extensionDuration) { auction.endTime = block.timestamp + auction.extensionDuration; } // Refund the previous bidder _sendValueWithFallbackWithdraw(originalBidder, originalAmount); } emit ReserveAuctionBidPlaced(auctionId, msg.sender, msg.value, auction.endTime); } /** * @notice Once the countdown has expired for an auction, anyone can settle the auction. * This will send the NFT to the highest bidder and distribute funds. */ function finalizeReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require(auction.endTime > 0, "NFTMarketReserveAuction: Auction has not started"); require(auction.endTime < block.timestamp, "NFTMarketReserveAuction: Auction still in progress"); delete nftContractToTokenIdToAuctionId[auction.nftContract][auction.tokenId]; delete auctionIdToAuction[auctionId]; IERC721Upgradeable(auction.nftContract).transferFrom(address(this), auction.bidder, auction.tokenId); (uint256 f8nFee, uint256 creatorFee, uint256 ownerRev) = _distributeFunds(auction.nftContract, auction.tokenId, auction.seller, auction.amount); emit ReserveAuctionFinalized(auctionId, auction.seller, auction.bidder, f8nFee, creatorFee, ownerRev); } /** * @notice Returns the minimum amount a bidder must spend to participate in an auction. */ function getMinBidAmount(uint256 auctionId) public view returns (uint256) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; if (auction.endTime == 0) { return auction.amount; } return _getMinBidAmountForReserveAuction(auction.amount); } /** * @dev Determines the minimum bid amount when outbidding another user. */ function _getMinBidAmountForReserveAuction(uint256 currentBidAmount) private view returns (uint256) { uint256 minIncrement = currentBidAmount.mul(_minPercentIncrementInBasisPoints) / BASIS_POINTS; if (minIncrement == 0) { // The next bid must be at least 1 wei greater than the current. return currentBidAmount.add(1); } return minIncrement.add(currentBidAmount); } uint256[1000] private ______gap; } /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @notice Interface for AdminRole which wraps the default admin role from * OpenZeppelin's AccessControl for easy integration. */ interface IAdminRole { function isAdmin(address account) external view returns (bool); } /** * @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); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title A market for NFTs on Chiart. * @dev This top level file holds no data directly to ease future upgrades. */ contract CHIARTNFTMarket is ChiartTreasuryNode, ChiartAdminRole, NFTMarketCore, ReentrancyGuardUpgradeable, NFTMarketCreators, SendValueWithFallbackWithdraw, NFTMarketFees, NFTMarketAuction, NFTMarketReserveAuction { /** * @notice Called once to configure the contract after the initial deployment. * @dev This farms the initialize call out to inherited contracts as needed. */ function initialize(address payable treasury) public initializer { ChiartTreasuryNode._initializeChiartTreasuryNode(treasury); NFTMarketAuction._initializeNFTMarketAuction(); NFTMarketReserveAuction._initializeNFTMarketReserveAuction(); } /** * @notice Allows Chiart to update the market configuration. */ function adminUpdateConfig( uint256 minPercentIncrementInBasisPoints, uint256 duration, uint256 primaryF8nFeeBasisPoints, uint256 secondaryF8nFeeBasisPoints, uint256 secondaryCreatorFeeBasisPoints ) public onlyChiartAdmin { _updateReserveAuctionConfig(minPercentIncrementInBasisPoints, duration); _updateMarketFees(primaryF8nFeeBasisPoints, secondaryF8nFeeBasisPoints, secondaryCreatorFeeBasisPoints); } /** * @dev Checks who the seller for an NFT is, this will check escrow or return the current owner if not in escrow. * This is a no-op function required to avoid compile errors. */ function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override(NFTMarketCore, NFTMarketReserveAuction) returns (address) { return super._getSellerFor(nftContract, tokenId); } }
Allows a user to manually withdraw funds which originally failed to transfer./
function withdraw() public nonReentrant { uint256 amount = pendingWithdrawals[msg.sender]; require(amount > 0, "No funds are pending withdrawal"); pendingWithdrawals[msg.sender] = 0; msg.sender.sendValue(amount); emit Withdrawal(msg.sender, amount); }
41,778
./full_match/8453/0xaDC80234af7D4a92323Bf6AfbE45B001232A65d2/sources/src/policies/Bond.sol
start the next round of the auctions the time that the auction is actually called to start and the official starting time used for the decay do not have to be the same
function start() external { if (block.timestamp < auctionEnd) revert AuctionOngoing(); auctionStart = auctionEnd; unchecked { ++auctionId; } auctionEnd = originalStartTime + (DAY * auctionId); availableForAuction = maru.balanceOf(address(this)); emit Start(msg.sender, availableForAuction, auctionStart, auctionEnd); }
11,545,972
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol"; import "openzeppelin-solidity/contracts/AddressUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CertChain ERC721 token standard implementation * @author rjkz808 */ contract CertToken is ERC721 { using AddressUtils for address; using SafeMath for uint256; string internal constant name_ = "CertChain"; string internal constant symbol_ = "CRT"; uint8 internal constant decimals_ = 0; bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; uint256[] internal allTokens; mapping (uint256 => address) internal tokenOwner; mapping (uint256 => address) internal tokenApproval; mapping (address => mapping (address => bool)) internal operatorApproval; mapping (address => uint256[]) internal ownedTokens; mapping (uint256 => uint256) internal ownedTokensIndex; mapping (uint256 => uint256) internal allTokensIndex; mapping (uint256 => string) internal tokenURIs; mapping (bytes4 => bool) internal supportedInterfaces; event Burn(address indexed owner, uint256 tokenId); /** * @dev Reverts, if the `msg.sender` doesn't own the specified token * @param _tokenId uint256 ID of the token */ modifier onlyOwnerOf(uint256 _tokenId) { require(msg.sender == ownerOf(_tokenId)); _; } /** * @dev Constructor to register the implemented interfaces IDs */ constructor() public { _registerInterface(InterfaceId_ERC165); _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token short code * @return string the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Gets the token decimals * @notice This function is needed to keep the balance * @notice displayed in the MetaMask * @return uint8 the token decimals (0) */ function decimals() external pure returns (uint8) { return decimals_; } /** * @dev Gets the total issued tokens amount * @return uint256 the total tokens supply */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the balance of an account * @param _owner address the tokens holder * @return uint256 the account owned tokens amount */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } /** * @dev Gets the specified token owner * @param _tokenId uint256 ID of the token * @return address the token owner */ function ownerOf(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenOwner[_tokenId]; } /** * @dev Gets the token existence state * @param _tokenId uint256 ID of the token * @return bool the token existence state */ function exists(uint256 _tokenId) public view returns (bool) { return tokenOwner[_tokenId] != address(0); } /** * @dev Gets the token approval * @param _tokenId uint256 ID of the token * @return address the token spender */ function getApproved(uint256 _tokenId) public view returns (address) { require(exists(_tokenId)); return tokenApproval[_tokenId]; } /** * @dev Gets the operator approval state * @param _owner address the tokens holder * @param _operator address the tokens spender * @return bool the operator approval state */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { require(_owner != address(0)); require(_operator != address(0)); return operatorApproval[_owner][_operator]; } /** * @dev Gets the specified address token ownership/spending state * @param _spender address the token spender * @param _tokenId uint256 the spending token ID * @return bool the ownership/spending state */ function isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) { require(_spender != address(0)); require(exists(_tokenId)); return( _spender == ownerOf(_tokenId) || _spender == getApproved(_tokenId) || isApprovedForAll(ownerOf(_tokenId), _spender) ); } /** * @dev Gets the token ID by the ownedTokens list index * @param _owner address the token owner * @param _index uint256 the token index * @return uint256 the token ID */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_owner != address(0)); require(_index < ownedTokens[_owner].length); return ownedTokens[_owner][_index]; } /** * @dev Gets the token ID by the allTokens list index * @param _index uint256 the token index * @return uint256 the token ID */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < allTokens.length); return allTokens[_index]; } /** * @dev Gets the token URI * @param _tokenId uint256 ID of the token * @return string the token URI */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the interface support state * @param _interfaceId bytes4 ID of the interface * @return bool the specified interface support state */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { require(_interfaceId != 0xffffffff); return supportedInterfaces[_interfaceId]; } /** * @dev Function to approve token to spend it * @param _to address the token spender * @param _tokenId ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(msg.sender == ownerOf(_tokenId)); require(_to != address(0)); tokenApproval[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Function to set the operator approval for the all owned tokens * @param _operator address the tokens spender * @param _approved bool the tokens approval state */ function setApprovalForAll(address _operator, bool _approved) public { require(_operator != address(0)); operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Function to clear an approval of the owned token * @param _tokenId uint256 ID of the token */ function clearApproval(uint256 _tokenId) public onlyOwnerOf(_tokenId) { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) { tokenApproval[_tokenId] = address(0); emit Approval(msg.sender, address(0), _tokenId); } } /** * @dev Function to send the owned/approved token * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); require(_to != address(0)); _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); _addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Function to send the owned/approved token with the * @dev onERC721Received function call if the token recepient is the * @dev smart contract and with the additional transaction metadata * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); require(_onERC721Received(msg.sender, _from, _to, _tokenId, _data)); } /** * @dev Function to burn the owned token * @param _tokenId uint256 ID of the token to be burned */ function burn(uint256 _tokenId) public onlyOwnerOf(_tokenId) { _burn(msg.sender, _tokenId); } /** * @dev Function to burn the owned/approved token * @param _from address the token owner * @param _tokenId uint256 ID of the token to be burned */ function burnFrom(address _from, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); _burn(_from, _tokenId); } /** * @dev Internal function to clear an approval of the token * @param _tokenId uint256 ID of the token */ function _clearApproval(uint256 _tokenId) internal { require(exists(_tokenId)); if (tokenApproval[_tokenId] != address(0)) tokenApproval[_tokenId] = address(0); } /** * @dev Internal function to add the token to the account * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be added */ function _addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); require(_to != address(0)); tokenOwner[_tokenId] = _to; ownedTokensIndex[_tokenId] = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); } /** * @dev Internal function to remove the token from its owner address * @param _from address the token owner * @param _tokenId uint256 ID of the token */ function _removeTokenFrom(address _from, uint256 _tokenId) internal { require(_from == ownerOf(_tokenId)); uint256 lastToken = ownedTokens[_from][ownedTokens[_from].length.sub(1)]; ownedTokens[_from][ownedTokensIndex[_tokenId]] = lastToken; ownedTokens[_from][ownedTokensIndex[lastToken]] = 0; ownedTokens[_from].length = ownedTokens[_from].length.sub(1); ownedTokensIndex[lastToken] = ownedTokensIndex[_tokenId]; ownedTokensIndex[_tokenId] = 0; tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to call the `onERC721Received` function if the * @dev token recepient is the smart contract * @param _operator address the `transfer` function caller * @param _from address the token owner * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes the transaction metadata */ function _onERC721Received( address _operator, address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (_to.isContract()) { ERC721Receiver receiver = ERC721Receiver(_to); return ERC721_RECEIVED == receiver.onERC721Received( _operator, _from, _tokenId, _data ); } return true; } /** * @dev Internal function the token * @param _owner address the token owner * @param _tokenId ID of the token to be burned */ function _burn(address _owner, uint256 _tokenId) internal { if (bytes(tokenURIs[_tokenId]).length > 0) delete tokenURIs[_tokenId]; _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); uint256 lastToken = allTokens[allTokens.length.sub(1)]; allTokens[allTokensIndex[_tokenId]] = lastToken; allTokens[allTokensIndex[lastToken]] = 0; allTokens.length = allTokens.length.sub(1); allTokensIndex[lastToken] = allTokensIndex[_tokenId]; allTokensIndex[_tokenId] = 0; emit Transfer(_owner, address(0), _tokenId); emit Burn(_owner, _tokenId); } /** * @dev Internal function to issue new token * @param _to address the token recepient * @param _tokenId uint256 ID of the token to be issued * @param _uri string the new token URI */ function _mint(address _to, uint256 _tokenId, string _uri) internal { require(_to != address(0)); _addTokenTo(_to, _tokenId); _setTokenURI(_tokenId, _uri); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to set the token URI * @param _tokenId ID of the token * @param _uri string the token URI */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to register the implemented interface * @param _interfaceId bytes4 ID of the interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } }
Function to burn the owned/approved token _from address the token owner _tokenId uint256 ID of the token to be burned/
function burnFrom(address _from, uint256 _tokenId) public { require(isApprovedOrOwner(msg.sender, _tokenId)); _burn(_from, _tokenId); }
6,435,020
// Play2liveICO tokensale smart contract. // Developed by Phenom.Team <[email protected]> pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal constant returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal constant returns(uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal constant returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal constant returns(uint) { uint c = a + b; assert(c >= a); return c; } } /** * @title ERC20 * @dev Standart ERC20 token interface */ contract ERC20 { uint public totalSupply = 0; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; function balanceOf(address _owner) constant returns (uint); function transfer(address _to, uint _value) returns (bool); function transferFrom(address _from, address _to, uint _value) returns (bool); function approve(address _spender, uint _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title Play2liveICO contract - takes funds from users and issues tokens */ contract Play2liveICO { // LUC - Level Up Coin token contract using SafeMath for uint; LucToken public LUC = new LucToken(this); Presale public preSaleToken; // Token price parameters // These parametes can be changed only by manager of contract uint public tokensPerDollar = 20; uint public rateEth = 446; // Rate USD per ETH uint public tokenPrice = tokensPerDollar * rateEth; // DTRC per ETH //Crowdsale parameters uint constant publicIcoPart = 625; // 62,5% of TotalSupply for BountyFund uint constant operationsPart = 111; uint constant foundersPart = 104; uint constant partnersPart = 78; // 7,8% of TotalSupply for parnersFund uint constant advisorsPart = 72; uint constant bountyPart = 10; // 1% of TotalSupply for BountyFund uint constant hardCap = 30000000 * tokensPerDollar * 1e18; // uint public soldAmount = 0; // Output ethereum addresses address public Company; address public OperationsFund; address public FoundersFund; address public PartnersFund; address public AdvisorsFund; address public BountyFund; address public Manager; // Manager controls contract address public Controller_Address1; // First address that is used to buy tokens for other cryptos address public Controller_Address2; // Second address that is used to buy tokens for other cryptos address public Controller_Address3; // Third address that is used to buy tokens for other cryptos address public Oracle; // Oracle address // Possible ICO statuses enum StatusICO { Created, PreIcoStarted, PreIcoPaused, PreIcoFinished, IcoStarted, IcoPaused, IcoFinished } StatusICO statusICO = StatusICO.Created; // Mappings mapping(address => bool) public swaped; mapping (address => string) public keys; // Events Log event LogStartPreICO(); event LogPausePreICO(); event LogFinishPreICO(); event LogStartICO(); event LogPauseICO(); event LogFinishICO(); event LogBuyForInvestor(address investor, uint lucValue, string txHash); event LogSwapTokens(address investor, uint tokensAmount); event LogRegister(address investor, string key); // Modifiers // Allows execution by the manager only modifier managerOnly { require(msg.sender == Manager); _; } // Allows execution by the oracle only modifier oracleOnly { require(msg.sender == Oracle); _; } // Allows execution by the one of controllers only modifier controllersOnly { require( (msg.sender == Controller_Address1)|| (msg.sender == Controller_Address2)|| (msg.sender == Controller_Address3) ); _; } /** * @dev Contract constructor function */ function Play2liveICO( address _preSaleToken, address _Company, address _OperationsFund, address _FoundersFund, address _PartnersFund, address _AdvisorsFund, address _BountyFund, address _Manager, address _Controller_Address1, address _Controller_Address2, address _Controller_Address3, address _Oracle ) public { preSaleToken = Presale(_preSaleToken); Company = _Company; OperationsFund = _OperationsFund; FoundersFund = _FoundersFund; PartnersFund = _PartnersFund; AdvisorsFund = _AdvisorsFund; BountyFund = _BountyFund; Manager = _Manager; Controller_Address1 = _Controller_Address1; Controller_Address2 = _Controller_Address2; Controller_Address3 = _Controller_Address3; Oracle = _Oracle; } /** * @dev Function to set rate of ETH and update token price * @param _rateEth current ETH rate */ function setRate(uint _rateEth) external oracleOnly { rateEth = _rateEth; tokenPrice = tokensPerDollar.mul(rateEth); } /** * @dev Function to start PreICO * Sets ICO status to PreIcoStarted */ function startPreIco() external managerOnly { require(statusICO == StatusICO.Created || statusICO == StatusICO.PreIcoPaused); statusICO = StatusICO.PreIcoStarted; LogStartPreICO(); } /** * @dev Function to pause PreICO * Sets ICO status to PreIcoPaused */ function pausePreIco() external managerOnly { require(statusICO == StatusICO.PreIcoStarted); statusICO = StatusICO.PreIcoPaused; LogPausePreICO(); } /** * @dev Function to finish PreICO * Sets ICO status to PreIcoFinished */ function finishPreIco() external managerOnly { require(statusICO == StatusICO.PreIcoStarted || statusICO == StatusICO.PreIcoPaused); statusICO = StatusICO.PreIcoFinished; LogFinishPreICO(); } /** * @dev Function to start ICO * Sets ICO status to IcoStarted */ function startIco() external managerOnly { require(statusICO == StatusICO.PreIcoFinished || statusICO == StatusICO.IcoPaused); statusICO = StatusICO.IcoStarted; LogStartICO(); } /** * @dev Function to pause ICO * Sets ICO status to IcoPaused */ function pauseIco() external managerOnly { require(statusICO == StatusICO.IcoStarted); statusICO = StatusICO.IcoPaused; LogPauseICO(); } /** * @dev Function to finish ICO * Sets ICO status to IcoFinished and emits tokens for funds */ function finishIco() external managerOnly { require(statusICO == StatusICO.IcoStarted || statusICO == StatusICO.IcoPaused); uint alreadyMinted = LUC.totalSupply(); uint totalAmount = alreadyMinted.mul(1000).div(publicIcoPart); LUC.mintTokens(OperationsFund, operationsPart.mul(totalAmount).div(1000)); LUC.mintTokens(FoundersFund, foundersPart.mul(totalAmount).div(1000)); LUC.mintTokens(PartnersFund, partnersPart.mul(totalAmount).div(1000)); LUC.mintTokens(AdvisorsFund, advisorsPart.mul(totalAmount).div(1000)); LUC.mintTokens(BountyFund, bountyPart.mul(totalAmount).div(1000)); statusICO = StatusICO.IcoFinished; LogFinishICO(); } /** * @dev Unfreeze tokens(enable token transfers) */ function unfreeze() external managerOnly { require(statusICO == StatusICO.IcoFinished); LUC.defrost(); } /** * @dev Function to swap tokens from pre-sale * @param _investor pre-sale tokens holder address */ function swapTokens(address _investor) external managerOnly { require(statusICO != StatusICO.IcoFinished); require(!swaped[_investor]); swaped[_investor] = true; uint tokensToSwap = preSaleToken.balanceOf(_investor); LUC.mintTokens(_investor, tokensToSwap); soldAmount = soldAmount.add(tokensToSwap); LogSwapTokens(_investor, tokensToSwap); } /** * @dev Fallback function calls buy(address _investor, uint _DTRCValue) function to issue tokens * when investor sends ETH to address of ICO contract and then stores investment amount */ function() external payable { if (statusICO == StatusICO.PreIcoStarted) { require(msg.value >= 100 finney); } buy(msg.sender, msg.value.mul(tokenPrice)); } /** * @dev Function to issues tokens for investors who made purchases in other cryptocurrencies * @param _investor address the tokens will be issued to * @param _txHash transaction hash of investor's payment * @param _lucValue number of LUC tokens */ function buyForInvestor( address _investor, uint _lucValue, string _txHash ) external controllersOnly { buy(_investor, _lucValue); LogBuyForInvestor(_investor, _lucValue, _txHash); } /** * @dev Function to issue tokens for investors who paid in ether * @param _investor address which the tokens will be issued tokens * @param _lucValue number of LUC tokens */ function buy(address _investor, uint _lucValue) internal { require(statusICO == StatusICO.PreIcoStarted || statusICO == StatusICO.IcoStarted); uint bonus = getBonus(_lucValue); uint total = _lucValue.add(bonus); require(soldAmount + _lucValue <= hardCap); LUC.mintTokens(_investor, total); soldAmount = soldAmount.add(_lucValue); } /** * @dev Function to calculates bonuses * @param _value amount of tokens * @return bonus value */ function getBonus(uint _value) public constant returns (uint) { uint bonus = 0; if (statusICO == StatusICO.PreIcoStarted) { if (now < 1517356800) { bonus = _value.mul(30).div(100); return bonus; } else { bonus = _value.mul(25).div(100); return bonus; } } if (statusICO == StatusICO.IcoStarted) { if (now < 1518652800) { bonus = _value.mul(10).div(100); return bonus; } if (now < 1518912000) { bonus = _value.mul(9).div(100); return bonus; } if (now < 1519171200) { bonus = _value.mul(8).div(100); return bonus; } if (now < 1519344000) { bonus = _value.mul(7).div(100); return bonus; } if (now < 1519516800) { bonus = _value.mul(6).div(100); return bonus; } if (now < 1519689600) { bonus = _value.mul(5).div(100); return bonus; } if (now < 1519862400) { bonus = _value.mul(4).div(100); return bonus; } if (now < 1520035200) { bonus = _value.mul(3).div(100); return bonus; } if (now < 1520208000) { bonus = _value.mul(2).div(100); return bonus; } else { bonus = _value.mul(1).div(100); return bonus; } } return bonus; } /** * @dev Allows invetsot to register thier Level Up Chain address */ function register(string _key) public { keys[msg.sender] = _key; LogRegister(msg.sender, _key); } /** * @dev Allows Company withdraw investments */ function withdrawEther() external managerOnly { Company.transfer(this.balance); } } /** * @title LucToken * @dev Luc token contract */ contract LucToken is ERC20 { using SafeMath for uint; string public name = "Level Up Coin"; string public symbol = "LUC"; uint public decimals = 18; // Ico contract address address public ico; // Tokens transfer ability status bool public tokensAreFrozen = true; // Allows execution by the owner only modifier icoOnly { require(msg.sender == ico); _; } /** * @dev Contract constructor function sets Ico address * @param _ico ico address */ function LucToken(address _ico) public { ico = _ico; } /** * @dev Function to mint tokens * @param _holder beneficiary address the tokens will be issued to * @param _value number of tokens to issue */ function mintTokens(address _holder, uint _value) external icoOnly { require(_value > 0); balances[_holder] = balances[_holder].add(_value); totalSupply = totalSupply.add(_value); Transfer(0x0, _holder, _value); } /** * @dev Function to enable token transfers */ function defrost() external icoOnly { tokensAreFrozen = false; } /** * @dev Get balance of tokens holder * @param _holder holder's address * @return balance of investor */ function balanceOf(address _holder) constant returns (uint256) { return balances[_holder]; } /** * @dev Send coins * throws on any error rather then return a false flag to minimize * user errors * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transfer(address _to, uint256 _amount) public returns (bool) { require(!tokensAreFrozen); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(msg.sender, _to, _amount); return true; } /** * @dev An account/contract attempts to get the coins * throws on any error rather then return a false flag to minimize user errors * * @param _from source address * @param _to target address * @param _amount transfer amount * * @return true if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require(!tokensAreFrozen); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); return true; } /** * @dev Allows another account/contract to spend some tokens on its behalf * throws on any error rather then return a false flag to minimize user errors * * also, to minimize the risk of the approve/transferFrom attack vector * approve has to be called twice in 2 separate transactions - once to * change the allowance to 0 and secondly to change it to the new allowance * value * * @param _spender approved address * @param _amount allowance amount * * @return true if the approval was successful */ function approve(address _spender, uint256 _amount) public returns (bool) { require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * * @param _owner the address which owns the funds * @param _spender the address which will spend the funds * * @return the amount of tokens still avaible for the spender */ function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } } contract tokenLUCG { /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply = 0; function tokenLUCG (string _name, string _symbol, uint8 _decimals){ name = _name; symbol = _symbol; decimals = _decimals; } /* This creates an array with all balances */ mapping (address => uint256) public balanceOf; } contract Presale is tokenLUCG { using SafeMath for uint; string name = 'Level Up Coin Gold'; string symbol = 'LUCG'; uint8 decimals = 18; address manager; address public ico; function Presale (address _manager) tokenLUCG (name, symbol, decimals){ manager = _manager; } event Transfer(address _from, address _to, uint256 amount); event Burn(address _from, uint256 amount); modifier onlyManager{ require(msg.sender == manager); _; } modifier onlyIco{ require(msg.sender == ico); _; } function mintTokens(address _investor, uint256 _mintedAmount) public onlyManager { balanceOf[_investor] = balanceOf[_investor].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(this, _investor, _mintedAmount); } function burnTokens(address _owner) public onlyIco{ uint tokens = balanceOf[_owner]; require(balanceOf[_owner] != 0); balanceOf[_owner] = 0; totalSupply = totalSupply.sub(tokens); Burn(_owner, tokens); } function setIco(address _ico) onlyManager{ ico = _ico; } }
Public variables of the token /
function tokenLUCG (string _name, string _symbol, uint8 _decimals){ name = _name; symbol = _symbol; decimals = _decimals; }
12,760,388
./partial_match/1/0xd558f0C903CcAC458495F0Dc776Dbcc78F1adf79/sources/BatchPreOrder.sol
Set the starting price for any given type. Can only be set once, and value must be greater than 0/
function setTypePrice(uint cType, uint256 price) public onlyOwner { if (currentTypePrice[cType] == 0) { require(price > 0, "Price already set"); currentTypePrice[cType] = price; } }
4,436,138
// SPDX-License-Identifier: UNLICENSED /* ███ ██ ██ █ █ █ █ █ █ █ █ █ ▀ ▄ █▄▄█ █▄▄█ █ █ ▄▀ █ █ █ █ ███▄ ███ █ █ ▀ █ █ ▀ ▀*/ pragma solidity >=0.8.0; /// @notice Interface for Baal {memberAction} that adjusts member `shares` & `loot`. interface IShaman { function memberAction(address member, uint96 loot, uint96 shares) external payable returns (uint96 lootOut, uint96 sharesOut); } /// @title Baal ';_;'. /// @notice Flexible guild contract inspired by Moloch DAO framework. contract Baal { bool public lootPaused; /*tracks transferability of `loot` economic weight - amendable through 'period'[2] proposal*/ bool public sharesPaused; /*tracks transferability of erc20 `shares` - amendable through 'period'[2] proposal*/ bool singleSummoner; /*internal flag to gauge speedy proposal processing*/ uint8 constant public decimals = 18; /*unit scaling factor in erc20 `shares` accounting - '18' is default to match ETH & common erc20s*/ uint16 constant MAX_GUILD_TOKEN_COUNT = 400; /*maximum number of whitelistable tokens subject to {ragequit}*/ uint96 public totalLoot; /*counter for total `loot` economic weight held by `members`*/ uint96 public totalSupply; /*counter for total `members` voting `shares` with erc20 accounting*/ uint32 public gracePeriod; /*time delay after proposal voting period for processing*/ uint32 public minVotingPeriod; /*minimum period for voting in seconds - amendable through 'period'[2] proposal*/ uint32 public maxVotingPeriod; /*maximum period for voting in seconds - amendable through 'period'[2] proposal*/ uint public proposalCount; /*counter for total `proposals` submitted*/ uint status; /*internal reentrancy check tracking value*/ string public name; /*'name' for erc20 `shares` accounting*/ string public symbol; /*'symbol' for erc20 `shares` accounting*/ bytes32 constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint chainId,address verifyingContract)'); /*EIP-712 typehash for Baal domain*/ bytes32 constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint nonce,uint expiry)'); /*EIP-712 typehash for Baal delegation*/ bytes32 constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint value,uint nonce,uint deadline)'); /*EIP-712 typehash for EIP-2612 {permit}*/ bytes32 constant VOTE_TYPEHASH = keccak256('Vote(uint proposalId,bool support)'); /*EIP-712 typehash for Baal proposal vote*/ address[] guildTokens; /*array list of erc20 tokens approved on summoning or by 'whitelist'[3] `proposals` for {ragequit} claims*/ mapping(address => mapping(address => uint)) public allowance; /*maps approved pulls of `shares` with erc20 accounting*/ mapping(address => uint) public balanceOf; /*maps `members` accounts to `shares` with erc20 accounting*/ mapping(address => mapping(uint => Checkpoint)) public checkpoints; /*maps record of vote `checkpoints` for each account by index*/ mapping(address => uint) public numCheckpoints; /*maps number of `checkpoints` for each account*/ mapping(address => address) public delegates; /*maps record of each account's `shares` delegate*/ mapping(address => uint) public nonces; /*maps record of states for signing & validating signatures*/ mapping(address => Member) public members; /*maps `members` accounts to struct details*/ mapping(uint => Proposal) public proposals; /*maps `proposalCount` to struct details*/ mapping(uint => bool) public proposalsPassed; /*maps `proposalCount` to approval status - separated out as struct is deleted, and this value can be used by minion-like contracts*/ mapping(address => bool) public shamans; /*maps contracts approved in 'whitelist'[3] proposals for {memberAction} that mint or burn `shares`*/ event SummonComplete(bool lootPaused, bool sharesPaused, uint gracePeriod, uint minVotingPeriod, uint maxVotingPeriod, string name, string symbol, address[] guildTokens, address[] shamans, address[] summoners, uint96[] loot, uint96[] shares); /*emits after Baal summoning*/ event SubmitProposal(uint8 indexed flag, uint indexed proposal, uint indexed votingPeriod, address[] to, uint96[] value, bytes[] data, string details); /*emits after proposal is submitted*/ event SponsorProposal(address indexed member, uint indexed proposal, uint indexed votingStarts); /*emits after member has sponsored proposal*/ event SubmitVote(address indexed member, uint balance, uint indexed proposal, bool indexed approved); /*emits after vote is submitted on proposal*/ event ProcessProposal(uint indexed proposal); /*emits when proposal is processed & executed*/ event Ragequit(address indexed member, address to, uint96 indexed lootToBurn, uint96 indexed sharesToBurn); /*emits when users burn Baal `shares` and/or `loot` for given `to` account*/ event Approval(address indexed owner, address indexed spender, uint amount); /*emits when Baal `shares` are approved for pulls with erc20 accounting*/ event Transfer(address indexed from, address indexed to, uint amount); /*emits when Baal `shares` are minted, burned or transferred with erc20 accounting*/ event TransferLoot(address indexed from, address indexed to, uint96 amount); /*emits when Baal `loot` is minted, burned or transferred*/ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /*emits when an account changes its voting delegate*/ event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /*emits when a delegate account's voting balance changes*/ modifier nonReentrant() { /*reentrancy guard*/ require(status == 1,'reentrant'); status = 2; _; status = 1; } struct Checkpoint { /*Baal checkpoint for marking number of delegated votes*/ uint32 fromTimeStamp; /*unix time for referencing voting balance*/ uint96 votes; /*votes at given unix time*/ } struct Member { /*Baal membership details*/ uint96 loot; /*economic weight held by `members` - can be set on summoning & adjusted via {memberAction}*/ uint highestIndexYesVote; /*highest proposal index on which a member `approved`*/ } struct Proposal { /*Baal proposal details*/ uint32 votingPeriod; /*time for voting in seconds*/ uint32 votingStarts; /*starting time for proposal in seconds since unix epoch*/ uint32 votingEnds; /*termination time for proposal in seconds since unix epoch - derived from `votingPeriod` set on proposal*/ uint96 yesVotes; /*counter for `members` `approved` 'votes' to calculate approval on processing*/ uint96 noVotes; /*counter for `members` 'dis-approved' 'votes' to calculate approval on processing*/ bool[4] flags; /*flags for proposal type & status - [action, member, period, whitelist]*/ address[] to; /*account(s) that receive(s) Baal state updates*/ uint96[] value; /*value(s) associated with Baal state updates (also used to toggle)*/ bytes[] data; /*raw data associated with Baal state updates (also used to toggle)*/ string details; /*human-readable context for proposal*/ } /// @notice Summon Baal with voting configuration & initial array of `members` accounts with `shares` & `loot` weights. /// @param _sharesPaused Sets transferability of Baal voting shares on initialization - if 'paused', `loot` will also be 'paused'. /// @param _gracePeriod Time delay in seconds after voting period before proposal can be processed. /// @param _minVotingPeriod Minimum voting period in seconds for `members` to cast votes on proposals. /// @param _maxVotingPeriod Maximum voting period in seconds for `members` to cast votes on proposals. /// @param _name Name for erc20 `shares` accounting. /// @param _symbol Symbol for erc20 `shares` accounting. /// @param _guildTokens Tokens approved for internal accounting - {ragequit} of `shares` &/or `loot`. /// @param _shamans External contracts approved for {memberAction} that adjust `shares` & `loot`. /// @param _summoners Accounts to add as `members`. /// @param _loot Economic weight among `members`. /// @param _shares Voting weight among `members` (`shares` also have economic weight & are erc20 tokens). constructor( bool _sharesPaused, uint32 _gracePeriod, uint32 _minVotingPeriod, uint32 _maxVotingPeriod, string memory _name, string memory _symbol, address[] memory _guildTokens, address[] memory _shamans, address[] memory _summoners, uint96[] memory _loot, uint96[] memory _shares ) { require(_minVotingPeriod != 0,'0_min'); /*check min. period isn't null*/ require(_minVotingPeriod <= _maxVotingPeriod,'min>max'); /*check minimum period doesn't exceed max*/ require(_guildTokens.length != 0,'0_tokens'); /*check approved tokens are not null*/ require(_summoners.length != 0,'0_summoners'); /*check that there is at least 1 summoner*/ require(_summoners.length == _loot.length && _loot.length == _shares.length,'!member array parity'); /*check `members`-related array lengths match*/ unchecked { for (uint i; i < _shamans.length; i++) shamans[_shamans[i]] = true; /*update mapping of approved `shamans` in Baal*/ for (uint i; i < _guildTokens.length; i++) guildTokens.push(_guildTokens[i]); /*update array of `guildTokens` approved for {ragequit}*/ for (uint i; i < _summoners.length; i++) { _mintLoot(_summoners[i], _loot[i]); /*mint Baal `loot` to `summoners`*/ _mintShares(_summoners[i], _shares[i]); /*mint Baal `shares` to `summoners`*/ _delegate(_summoners[i], _summoners[i]); /*delegate `summoners` voting weights to themselves - this saves a step before voting*/ if (_summoners.length == 1) singleSummoner = true; /*flag if Baal summoned singly for speedy processing*/ } } gracePeriod = _gracePeriod; /*sets delay for processing proposal*/ minVotingPeriod = _minVotingPeriod; /*set minimum voting period - adjustable via 'period'[2] proposal*/ maxVotingPeriod = _maxVotingPeriod; /*set maximum voting period - adjustable via 'period'[2] proposal*/ if (_sharesPaused) lootPaused = true; /*set initial transferability for `loot` - if `sharesPaused`, transfers are blocked*/ sharesPaused = _sharesPaused; /*set initial transferability for `shares` tokens - if 'true', transfers are blocked*/ name = _name; /*initialize Baal `name` with erc20 accounting*/ symbol = _symbol; /*initialize Baal `symbol` with erc20 accounting*/ status = 1; /*initialize 'reentrancy guard' status*/ emit SummonComplete(lootPaused, _sharesPaused, _gracePeriod, _minVotingPeriod, _maxVotingPeriod, _name, _symbol, _guildTokens, _shamans, _summoners, _loot, _shares); /*emit event reflecting Baal summoning completed*/ } /// @notice Execute membership action to mint or burn `shares` and/or `loot` against whitelisted `shamans` in consideration of user & given amounts. /// @param shaman Whitelisted contract to trigger action. /// @param loot Economic weight involved in external call. /// @param shares Voting weight involved in external call. /// @param mint Confirm whether action involves 'mint' or 'burn' action - if `false`, perform burn. /// @return lootOut sharesOut Membership updates derived from action. function memberAction( address shaman, uint96 loot, uint96 shares, bool mint ) external nonReentrant payable returns (uint96 lootOut, uint96 sharesOut) { require(shamans[shaman],'!shaman'); /*check `shaman` is approved*/ (lootOut, sharesOut) = IShaman(shaman).memberAction{value: msg.value}(msg.sender, loot, shares); /*fetch 'reaction' per inputs*/ if (mint) { /*execute `mint` actions*/ if (lootOut != 0) _mintLoot(msg.sender, lootOut); /*add `loot` to user account & Baal total*/ if (sharesOut != 0) _mintShares(msg.sender, sharesOut); /*add `shares` to user account & Baal total with erc20 accounting*/ } else { /*otherwise, execute `burn` actions*/ if (lootOut != 0) _burnLoot(msg.sender, lootOut); /*subtract `loot` from user account & Baal total*/ if (sharesOut != 0) _burnShares(msg.sender, sharesOut); /*subtract `shares` from user account & Baal total with erc20 accounting*/ } } /***************** PROPOSAL FUNCTIONS *****************/ /// @notice Submit proposal to Baal `members` for approval within given voting period. /// @param flag Index to assign proposal type '[0...3]'. /// @param votingPeriod Voting period in seconds. /// @param to Account to target for proposal. /// @param value Numerical value to bind to proposal. /// @param data Data to bind to proposal. /// @param details Context for proposal. /// @return proposal Count for submitted proposal. function submitProposal( uint8 flag, uint32 votingPeriod, address[] calldata to, uint96[] calldata value, bytes[] calldata data, string calldata details ) external nonReentrant returns (uint proposal) { require(minVotingPeriod <= votingPeriod && votingPeriod <= maxVotingPeriod,'!votingPeriod'); /*check voting period is within Baal bounds*/ require(to.length <= 10,'array max'); /*limit executable actions to help avoid block gas limit errors on processing*/ require(flag <= 3,'!flag'); /*check 'flag' is in bounds*/ bool[4] memory flags; /*plant `flags` - [action, member, period, whitelist]*/ flags[flag] = true; /*flag proposal type for struct storage*/ if (flag == 2) { if (value.length == 1) { require(value[0] <= maxVotingPeriod,'over max'); } else if (value.length == 2) { require(value[1] >= minVotingPeriod,'under min'); } } else { require(to.length == value.length && value.length == data.length,'!array parity'); /*check array lengths match*/ } bool selfSponsor; /*plant sponsor flag*/ if (balanceOf[msg.sender] != 0) selfSponsor = true; /*if a member, self-sponsor*/ unchecked { proposalCount++; /*increment proposal counter*/ proposals[proposalCount] = Proposal( /*push params into proposal struct - start voting period timer if member submission*/ votingPeriod, selfSponsor ? uint32(block.timestamp) : 0, selfSponsor ? uint32(block.timestamp) + votingPeriod : 0, 0, 0, flags, to, value, data, details ); } emit SubmitProposal(flag, proposal, votingPeriod, to, value, data, details); /*emit event reflecting proposal submission*/ } /// @notice Sponsor proposal to Baal `members` for approval within voting period. /// @param proposal Number of proposal in `proposals` mapping to sponsor. function sponsorProposal(uint proposal) external nonReentrant { Proposal storage prop = proposals[proposal]; /*alias proposal storage pointers*/ require(balanceOf[msg.sender] != 0,'!member'); /*check 'membership' - required to sponsor proposal*/ require(prop.votingPeriod != 0,'!exist'); /*check proposal existence*/ require(prop.votingStarts == 0,'sponsored'); /*check proposal not already sponsored*/ prop.votingStarts = uint32(block.timestamp); unchecked { prop.votingEnds = uint32(block.timestamp) + prop.votingPeriod; } emit SponsorProposal(msg.sender, proposal, block.timestamp); } /// @notice Submit vote - proposal must exist & voting period must not have ended. /// @param proposal Number of proposal in `proposals` mapping to cast vote on. /// @param approved If 'true', member will cast `yesVotes` onto proposal - if 'false', `noVotes` will be counted. function submitVote(uint proposal, bool approved) external nonReentrant { Proposal storage prop = proposals[proposal]; /*alias proposal storage pointers*/ uint96 balance = getPriorVotes(msg.sender, prop.votingStarts); /*fetch & gas-optimize voting weight at proposal creation time*/ require(prop.votingEnds >= block.timestamp,'ended'); /*check voting period has not ended*/ unchecked { if (approved) { /*if `approved`, cast delegated balance `yesVotes` to proposal*/ prop.yesVotes += balance; members[msg.sender].highestIndexYesVote = proposal; } else { /*otherwise, cast delegated balance `noVotes` to proposal*/ prop.noVotes += balance; } } emit SubmitVote(msg.sender, balance, proposal, approved); /*emit event reflecting vote*/ } /// @notice Submit vote with EIP-712 signature - proposal must exist & voting period must not have ended. /// @param proposal Number of proposal in `proposals` mapping to cast vote on. /// @param approved If 'true', member will cast `yesVotes` onto proposal - if 'false', `noVotes` will be counted. /// @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 submitVoteWithSig( uint proposal, bool approved, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { Proposal storage prop = proposals[proposal]; /*alias proposal storage pointers*/ bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); /*calculate EIP-712 domain hash*/ bytes32 structHash = keccak256(abi.encode(VOTE_TYPEHASH, proposal, approved)); /*calculate EIP-712 struct hash*/ bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); /*calculate EIP-712 digest for signature*/ address signatory = ecrecover(digest, v, r, s); /*recover signer from hash data*/ require(signatory != address(0),'!signatory'); /*check signer is not null*/ uint96 balance = getPriorVotes(signatory, prop.votingStarts); /*fetch & gas-optimize voting weight at proposal creation time*/ require(prop.votingEnds >= block.timestamp,'ended'); /*check voting period has not ended*/ unchecked { if (approved) { /*if `approved`, cast delegated balance `yesVotes` to proposal*/ prop.yesVotes += balance; members[signatory].highestIndexYesVote = proposal; } else { /*otherwise, cast delegated balance `noVotes` to proposal*/ prop.noVotes += balance; } } emit SubmitVote(signatory, balance, proposal, approved); /*emit event reflecting vote*/ } // ******************** // PROCESSING FUNCTIONS // ******************** /// @notice Process `proposal` & execute internal functions based on `flag`[#]. /// @param proposal Number of proposal in `proposals` mapping to process for execution. function processProposal(uint proposal) external nonReentrant { Proposal storage prop = proposals[proposal]; /*alias `proposal` storage pointers*/ _processingReady(proposal, prop); /*validate `proposal` processing requirements*/ if (prop.yesVotes > prop.noVotes) /*check if `proposal` approved by simple majority of members*/ proposalsPassed[proposal] = true; /*flag that proposal passed - allows minion-like extensions*/ if (prop.flags[0]) processActionProposal(prop); /*check `flag`, execute 'action'*/ else if (prop.flags[1]) processMemberProposal(prop); /*check `flag`, execute 'member'*/ else if (prop.flags[2]) processPeriodProposal(prop); /*check `flag`, execute 'period'*/ else processWhitelistProposal(prop); /*otherwise, execute 'whitelist'*/ delete proposals[proposal]; /*delete given proposal struct details for gas refund & the commons*/ emit ProcessProposal(proposal); /*emit event reflecting that given proposal processed*/ } /// @notice Internal function to process 'action'[0] proposal. function processActionProposal(Proposal memory prop) private { unchecked { for (uint i; i < prop.to.length; i++) prop.to[i].call{value:prop.value[i]} /*pass ETH value(s), if any*/ (prop.data[i]); /*execute low-level call(s)*/ } } /// @notice Internal function to process 'member'[1] proposal. function processMemberProposal(Proposal memory prop) private { unchecked { for (uint i; i < prop.to.length; i++) { if (prop.data[i].length == 0) { _mintShares(prop.to[i], prop.value[i]); /*grant `to` `value` `shares`*/ } else { uint96 removedBalance = uint96(balanceOf[prop.to[i]]); /*gas-optimize variable*/ _burnShares(prop.to[i], removedBalance); /*burn all of `to` `shares` & convert into `loot`*/ _mintLoot(prop.to[i], removedBalance); /*mint equivalent `loot`*/ } } } } /// @notice Internal function to process 'period'[2] proposal - state updates are broken up for security. function processPeriodProposal(Proposal memory prop) private { uint length = prop.value.length; if (length == 1) { if (prop.value[0] != 0) minVotingPeriod = uint32(prop.value[0]); /*if positive, reset min. voting period to first `value`*/ } else if (length == 2) { if (prop.value[1] != 0) maxVotingPeriod = uint32(prop.value[1]); /*if positive, reset max. voting period to second `value`*/ } else if (length == 3) { if (prop.value[2] != 0) gracePeriod = uint32(prop.value[2]); /*if positive, reset grace period to third `value`*/ } else if (length == 4) { prop.value[3] == 0 ? lootPaused = false : lootPaused = true; /*if positive, pause `loot` transfers on fourth `value`*/ } else if (length == 5) { prop.value[4] == 0 ? sharesPaused = false : sharesPaused = true; /*if positive, pause `shares` transfers on fifth `value`*/ } } /// @notice Internal function to process 'whitelist'[3] proposal - toggles included for security. function processWhitelistProposal(Proposal memory prop) private { unchecked { for (uint i; i < prop.to.length; i++) { if (prop.value[i] == 0 && prop.data[i].length == 0) { /*if `value` & `data` are null, approve `shamans`*/ shamans[prop.to[i]] = true; /*add account(s) to `shamans` extensions*/ } else if (prop.value[i] == 0 && prop.data[i].length != 0) { /*if `value` is null & `data` is populated, remove `shamans`*/ shamans[prop.to[i]] = false; /*remove account(s) from `shamans` extensions*/ } else if (prop.value[i] != 0 && prop.data[i].length == 0) { /*if `value` is positive & `data` is null, add `guildTokens`*/ if (guildTokens.length != MAX_GUILD_TOKEN_COUNT) guildTokens.push(prop.to[i]); /*push account to `guildTokens` array if within 'MAX'*/ } } } } /******************* GUILD MGMT FUNCTIONS *******************/ /// @notice Approve `to` to transfer up to `amount`. /// @return success Whether or not the approval succeeded. function approve(address to, uint amount) external returns (bool success) { allowance[msg.sender][to] = amount; /*adjust `allowance`*/ emit Approval(msg.sender, to, amount); /*emit event reflecting approval*/ success = true; /*confirm approval with ERC-20 accounting*/ } /// @notice Delegate votes from user to `delegatee`. /// @param delegatee The address to delegate votes to. function delegate(address delegatee) external { _delegate(msg.sender, delegatee); } /// @notice Delegates votes from `signatory` to `delegatee` with EIP-712 signature. /// @param delegatee The address to delegate 'votes' to. /// @param nonce The contract state required to match the signature. /// @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 delegateBySig( address delegatee, uint nonce, uint deadline, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); /*calculate EIP-712 domain hash*/ bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, deadline)); /*calculate EIP-712 struct hash*/ bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); /*calculate EIP-712 digest for signature*/ address signatory = ecrecover(digest, v, r, s); /*recover signer from hash data*/ require(signatory != address(0),'!signatory'); /*check signer is not null*/ unchecked { require(nonce == nonces[signatory]++,'!nonce'); /*check given `nonce` is next in `nonces`*/ } require(block.timestamp <= deadline,'expired'); /*check signature is not expired*/ _delegate(signatory, delegatee); /*execute delegation*/ } /// @notice Triggers an approval from `owner` to `spender` with EIP-712 signature. /// @param owner The address to approve from. /// @param spender The address to be approved. /// @param amount The number of `shares` 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, uint96 amount, uint deadline, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), block.chainid, address(this))); /*calculate EIP-712 domain hash*/ unchecked { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); /*calculate EIP-712 struct hash*/ bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); /*calculate EIP-712 digest for signature*/ address signatory = ecrecover(digest, v, r, s); /*recover signer from hash data*/ require(signatory != address(0),'!signatory'); /*check signer is not null*/ require(signatory == owner,'!authorized'); /*check signer is `owner`*/ } require(block.timestamp <= deadline,'expired'); /*check signature is not expired*/ allowance[owner][spender] = amount; /*adjust `allowance`*/ emit Approval(owner, spender, amount); /*emit event reflecting approval*/ } /// @notice Transfer `amount` tokens from user to `to`. /// @param to The address of destination account. /// @param amount The number of `shares` tokens to transfer. /// @return success Whether or not the transfer succeeded. function transfer(address to, uint96 amount) external returns (bool success) { require(!sharesPaused,'!transferable'); balanceOf[msg.sender] -= amount; unchecked { balanceOf[to] += amount; } _moveDelegates(delegates[msg.sender], delegates[to], amount); emit Transfer(msg.sender, to, amount); success = true; } /// @notice Transfer `amount` tokens from `from` to `to`. /// @param from The address of the source account. /// @param to The address of the destination account. /// @param amount The number of `shares` tokens to transfer. /// @return success Whether or not the transfer succeeded. function transferFrom(address from, address to, uint96 amount) external returns (bool success) { require(!sharesPaused,'!transferable'); if (allowance[from][msg.sender] != type(uint).max) { allowance[from][msg.sender] -= amount; } balanceOf[from] -= amount; unchecked { balanceOf[to] += amount; } _moveDelegates(delegates[from], delegates[to], amount); emit Transfer(from, to, amount); success = true; } /// @notice Transfer `amount` `loot` from user to `to`. /// @param to The address of destination account. /// @param amount The sum of loot to transfer. function transferLoot(address to, uint96 amount) external { require(!lootPaused,'!transferable'); members[msg.sender].loot -= amount; unchecked { members[to].loot += amount; } emit TransferLoot(msg.sender, to, amount); } /// @notice Process member burn of `shares` and/or `loot` to claim 'fair share' of `guildTokens`. /// @param to Account that receives 'fair share'. /// @param lootToBurn Baal pure economic weight to burn. /// @param sharesToBurn Baal voting weight to burn. function ragequit(address to, uint96 lootToBurn, uint96 sharesToBurn) external nonReentrant { require(proposals[members[msg.sender].highestIndexYesVote].votingEnds == 0,'processed'); /*check highest index proposal member approved has processed*/ for (uint i; i < guildTokens.length; i++) { (,bytes memory balanceData) = guildTokens[i].staticcall(abi.encodeWithSelector(0x70a08231, address(this))); /*get Baal token balances - 'balanceOf(address)'*/ uint balance = abi.decode(balanceData, (uint)); /*decode Baal token balances for calculation*/ uint amountToRagequit = ((lootToBurn + sharesToBurn) * balance) / (totalSupply + totalLoot); /*calculate 'fair shair' claims*/ if (amountToRagequit != 0) { /*gas optimization to allow higher maximum token limit*/ _safeTransfer(guildTokens[i], to, amountToRagequit); /*execute 'safe' token transfer*/ } } if (lootToBurn != 0) { /*gas optimization*/ _burnLoot(msg.sender, lootToBurn); /*subtract `loot` from user account & Baal totals*/ } if (sharesToBurn != 0) { /*gas optimization*/ _burnShares(msg.sender, sharesToBurn); /*subtract `shares` from user account & Baal totals with erc20 accounting*/ } emit Ragequit(msg.sender, to, lootToBurn, sharesToBurn); /*event reflects claims made against Baal*/ } /*************** GETTER FUNCTIONS ***************/ /// @notice Returns the current delegated `vote` balance for `account`. /// @param account The user to check delegated `votes` for. /// @return votes Current `votes` delegated to `account`. function getCurrentVotes(address account) external view returns (uint96 votes) { uint nCheckpoints = numCheckpoints[account]; unchecked { votes = nCheckpoints != 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } } /// @notice Returns the prior number of `votes` for `account` as of `timeStamp`. /// @param account The user to check `votes` for. /// @param timeStamp The unix time to check `votes` for. /// @return votes Prior `votes` delegated to `account`. function getPriorVotes(address account, uint timeStamp) public view returns (uint96 votes) { require(timeStamp < block.timestamp,'!determined'); uint nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) return 0; unchecked { if (checkpoints[account][nCheckpoints - 1].fromTimeStamp <= timeStamp) return checkpoints[account][nCheckpoints - 1].votes; if (checkpoints[account][0].fromTimeStamp > timeStamp) return 0; uint lower = 0; uint upper = nCheckpoints - 1; while (upper > lower) { uint center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTimeStamp == timeStamp) return cp.votes; else if (cp.fromTimeStamp < timeStamp) lower = center; else upper = center - 1; } votes = checkpoints[account][lower].votes; } } /// @notice Returns array list of approved `guildTokens` in Baal for {ragequit}. /// @return tokens ERC-20s approved for {ragequit}. function getGuildTokens() external view returns (address[] memory tokens) { tokens = guildTokens; } /// @notice Returns `flags` for given Baal `proposal` describing type ('action'[0], 'member'[1], 'period'[2], 'whitelist'[3]). /// @param proposal The index to check `flags` for. /// @return flags The boolean flags describing `proposal` type. function getProposalFlags(uint proposal) external view returns (bool[4] memory flags) { flags = proposals[proposal].flags; } /*************** HELPER FUNCTIONS ***************/ /// @notice Allows batched calls to Baal. /// @param data An array of payloads for each call. function multicall(bytes[] calldata data) external returns (bytes[] memory results) { results = new bytes[](data.length); unchecked { for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } /// @notice Returns confirmation for 'safe' ERC-721 (NFT) transfers to Baal. function onERC721Received(address, address, uint, bytes calldata) external pure returns (bytes4 sig) { sig = 0x150b7a02; /*'onERC721Received(address,address,uint,bytes)'*/ } /// @notice Returns confirmation for 'safe' ERC-1155 transfers to Baal. function onERC1155Received(address, address, uint, uint, bytes calldata) external pure returns (bytes4 sig) { sig = 0xf23a6e61; /*'onERC1155Received(address,address,uint,uint,bytes)'*/ } /// @notice Returns confirmation for 'safe' batch ERC-1155 transfers to Baal. function onERC1155BatchReceived(address, address, uint[] calldata, uint[] calldata, bytes calldata) external pure returns (bytes4 sig) { sig = 0xbc197c81; /*'onERC1155BatchReceived(address,address,uint[],uint[],bytes)'*/ } /// @notice Deposits ETH sent to Baal. receive() external payable {} /// @notice Delegates Baal voting weight. function _delegate(address delegator, address delegatee) private { address currentDelegate = delegates[delegator]; delegates[delegator] = delegatee; _moveDelegates(currentDelegate, delegatee, uint96(balanceOf[delegator])); emit DelegateChanged(delegator, currentDelegate, delegatee); } /// @notice Elaborates delegate update - cf., 'Compound Governance'. function _moveDelegates(address srcRep, address dstRep, uint96 amount) private { unchecked { if (srcRep != dstRep && amount != 0) { if (srcRep != address(0)) { uint srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum != 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum != 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } } /// @notice Elaborates delegate update - cf., 'Compound Governance'. function _writeCheckpoint(address delegatee, uint nCheckpoints, uint96 oldVotes, uint96 newVotes) private { uint32 timeStamp = uint32(block.timestamp); unchecked { if (nCheckpoints != 0 && checkpoints[delegatee][nCheckpoints - 1].fromTimeStamp == timeStamp) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(timeStamp, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /// @notice Burn function for Baal `loot`. function _burnLoot(address from, uint96 loot) private { members[from].loot -= loot; /*subtract `loot` for `from` account*/ unchecked { totalLoot -= loot; /*subtract from total Baal `loot`*/ } emit TransferLoot(from, address(0), loot); /*emit event reflecting burn of `loot`*/ } /// @notice Burn function for Baal `shares`. function _burnShares(address from, uint96 shares) private { balanceOf[from] -= shares; /*subtract `shares` for `from` account*/ unchecked { totalSupply -= shares; /*subtract from total Baal `shares`*/ } _moveDelegates(delegates[from], address(0), shares); /*update delegation*/ emit Transfer(from, address(0), shares); /*emit event reflecting burn of `shares` with erc20 accounting*/ } /// @notice Minting function for Baal `loot`. function _mintLoot(address to, uint96 loot) private { unchecked { if (totalSupply + loot <= type(uint96).max / 2) { members[to].loot += loot; /*add `loot` for `to` account*/ totalLoot += loot; /*add to total Baal `loot`*/ emit TransferLoot(address(0), to, loot); /*emit event reflecting mint of `loot`*/ } } } /// @notice Minting function for Baal `shares`. function _mintShares(address to, uint96 shares) private { unchecked { if (totalSupply + shares <= type(uint96).max / 2) { balanceOf[to] += shares; /*add `shares` for `to` account*/ totalSupply += shares; /*add to total Baal `shares`*/ _moveDelegates(address(0), delegates[to], shares); /*update delegation*/ emit Transfer(address(0), to, shares); /*emit event reflecting mint of `shares` with erc20 accounting*/ } } } /// @notice Check to validate proposal processing requirements. function _processingReady(uint proposal, Proposal memory prop) private view returns (bool ready) { unchecked { require(proposal <= proposalCount,'!exist'); /*check proposal exists*/ require(proposals[proposal - 1].votingEnds == 0,'prev!processed'); /*check previous proposal has processed by deletion*/ require(proposals[proposal].votingEnds != 0,'processed'); /*check given proposal has been sponsored & not yet processed by deletion*/ if (singleSummoner) return true; /*if single member, process early*/ if (prop.yesVotes > totalSupply / 2) return true; /*process early if majority member support*/ require(prop.votingEnds + gracePeriod <= block.timestamp,'!ended'); /*check voting period has ended*/ ready = true; /*otherwise, process if voting period done*/ } } /// @notice Provides 'safe' {transfer} for tokens that do not consistently return 'true/false'. function _safeTransfer(address token, address to, uint amount) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount)); /*'transfer(address,uint)'*/ require(success && (data.length == 0 || abi.decode(data, (bool))),'transfer failed'); /*checks success & allows non-conforming transfers*/ } }
Elaborates delegate update - cf., 'Compound Governance'.
function _moveDelegates(address srcRep, address dstRep, uint96 amount) private { unchecked { if (srcRep != dstRep && amount != 0) { if (srcRep != address(0)) { uint srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum != 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum != 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } }
5,970,948
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/internal/Deposits.sol
Returns sum of all deposits. deposits_ Deposits state struct. return Sum of all deposits in tree./ In a scaled Fenwick tree, sum is at the root node and never scaled
function treeSum( DepositsState storage deposits_ ) internal view returns (uint256) { return deposits_.values[SIZE]; }
3,630,179
pragma solidity ^0.4.23; /******************************************************************************* * * Copyright (c) 2018 Taboo University MDAO. * Released under the MIT License. * * Taboo Db - An eternal database, providing a sustainable storage solution * for use throughout the upgrade lifecycle of managing contracts. * * Version 18.5.7 * * Web : https://taboou.com/ * Email : [email protected] * Github : https://github.com/taboou/tabooads.bit/ */ /******************************************************************************* * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); 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; newOwner = address(0); } } /******************************************************************************* * Taboo Db Contract */ contract TabooDb is Owned { /* Initialize all storage types. */ mapping(bytes32 => address) private addressStorage; mapping(bytes32 => bool) private boolStorage; mapping(bytes32 => bytes) private bytesStorage; mapping(bytes32 => int256) private intStorage; mapping(bytes32 => string) private stringStorage; mapping(bytes32 => uint256) private uIntStorage; /** * @dev Only allow access from the latest version of a contract * in the Taboo U Networks (TUN) after deployment. */ modifier onlyAuthByTUN() { /*********************************************************************** * The owner is only allowed to set the authorized contracts upon * deployment, to register the initial contracts, afterwards their * direct access is permanently disabled. */ if (msg.sender == owner) { /* Verify owner's write access has not already been disabled. */ require(boolStorage[keccak256('owner.auth.disabled')] != true); } else { /* Verify write access is only permitted to authorized accounts. */ require(boolStorage[keccak256(msg.sender, '.has.auth')] == true); } _; // function code is inserted here } /*************************************************************************** * Initialize all getter methods. */ /// @param _key The key for the record function getAddress(bytes32 _key) external view returns (address) { return addressStorage[_key]; } /// @param _key The key for the record function getBool(bytes32 _key) external view returns (bool) { return boolStorage[_key]; } /// @param _key The key for the record function getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_key]; } /// @param _key The key for the record function getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /// @param _key The key for the record function getString(bytes32 _key) external view returns (string) { return stringStorage[_key]; } /// @param _key The key for the record function getUint(bytes32 _key) external view returns (uint) { return uIntStorage[_key]; } /*************************************************************************** * Initialize all setter methods. */ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyAuthByTUN external { addressStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyAuthByTUN external { boolStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyAuthByTUN external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyAuthByTUN external { intStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyAuthByTUN external { stringStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyAuthByTUN external { uIntStorage[_key] = _value; } /*************************************************************************** * Initialize all delete methods. */ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyAuthByTUN external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyAuthByTUN external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyAuthByTUN external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyAuthByTUN external { delete intStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyAuthByTUN external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyAuthByTUN external { delete uIntStorage[_key]; } }
_key The key for the record
function setString(bytes32 _key, string _value) onlyAuthByTUN external { stringStorage[_key] = _value; }
619,624
pragma solidity ^0.4.19; // File: contracts/ERC721Draft.sol /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) public view returns (address owner); function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } // File: contracts/FighterCoreInterface.sol contract FighterCoreInterface is ERC721 { function getFighter(uint256 _id) public view returns ( uint256 prizeCooldownEndTime, uint256 battleCooldownEndTime, uint256 prizeCooldownIndex, uint256 battlesFought, uint256 battlesWon, uint256 generation, uint256 genes, uint256 dexterity, uint256 strength, uint256 vitality, uint256 luck, uint256 experience ); function createPrizeFighter( uint16 _generation, uint256 _genes, uint8 _dexterity, uint8 _strength, uint8 _vitality, uint8 _luck, address _owner ) public; function updateFighter( uint256 _fighterId, uint8 _dexterity, uint8 _strength, uint8 _vitality, uint8 _luck, uint32 _experience, uint64 _prizeCooldownEndTime, uint16 _prizeCooldownIndex, uint64 _battleCooldownEndTime, uint16 _battlesFought, uint16 _battlesWon ) public; function updateFighterBattleStats( uint256 _fighterId, uint64 _prizeCooldownEndTime, uint16 _prizeCooldownIndex, uint64 _battleCooldownEndTime, uint16 _battlesFought, uint16 _battlesWon ) public; function updateDexterity(uint256 _fighterId, uint8 _dexterity) public; function updateStrength(uint256 _fighterId, uint8 _strength) public; function updateVitality(uint256 _fighterId, uint8 _vitality) public; function updateLuck(uint256 _fighterId, uint8 _luck) public; function updateExperience(uint256 _fighterId, uint32 _experience) public; } // File: contracts/Battle/BattleDeciderInterface.sol contract BattleDeciderInterface { function isBattleDecider() public pure returns (bool); function determineWinner(uint256[7][] teamAttacker, uint256[7][] teamDefender) public returns ( bool attackerWon, uint256 xpForAttacker, uint256 xpForDefender ); } // File: contracts/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/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; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } // File: contracts/Battle/GeneScienceInterface.sol /// @title defined the interface that will be referenced in main Fighter contract contract GeneScienceInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isGeneScience() public pure returns (bool); /// @dev given genes of fighter 1 & 2, return a genetic combination - may have a random factor /// @param genes1 genes of fighter1 /// @param genes2 genes of fighter1 /// @return the genes that are supposed to be passed down the new fighter function mixGenes(uint256 genes1, uint256 genes2) public returns (uint256); } // File: contracts/Battle/BattleBase.sol contract BattleBase is Ownable, Pausable { event TeamCreated(uint256 indexed teamId, uint256[] fighterIds); event TeamDeleted(uint256 indexed teamId, uint256[] fighterIds); event BattleResult(address indexed winnerAddress, address indexed loserAddress, uint256[] attackerFighterIds, uint256[] defenderFighterIds, bool attackerWon, uint16 prizeFighterGeneration, uint256 prizeFighterGenes, uint32 attackerXpGained, uint32 defenderXpGained); struct Team { address owner; uint256[] fighterIds; } struct RaceBaseStats { uint8 strength; uint8 dexterity; uint8 vitality; } Team[] public teams; // index => base stats (where index represents the race) RaceBaseStats[] public raceBaseStats; uint256 internal randomCounter = 0; FighterCoreInterface public fighterCore; GeneScienceInterface public geneScience; BattleDeciderInterface public battleDecider; mapping (uint256 => uint256) public fighterIndexToTeam; mapping (uint256 => bool) public teamIndexToExist; // an array of deleted teamIds owned by each address so that we can reuse these again // mapping (address => uint256[]) public addressToDeletedTeams; // an array of deleted teams we can reuse later uint256[] public deletedTeamIds; uint256 public maxPerTeam = 5; uint8[] public genBaseStats = [ 16, // gen 0 12, // gen 1 10, // gen 2 8, // gen 3 7, // gen 4 6, // gen 5 5, // gen 6 4, // gen 7 3, // gen 8 2, // gen 9 1 // gen 10+ ]; // modifier ownsFighters(uint256[] _fighterIds) { // uint len = _fighterIds.length; // for (uint i = 0; i < len; i++) { // require(fighterCore.ownerOf(_fighterIds[i]) == msg.sender); // } // _; // } modifier onlyTeamOwner(uint256 _teamId) { require(teams[_teamId].owner == msg.sender); _; } modifier onlyExistingTeam(uint256 _teamId) { require(teamIndexToExist[_teamId] == true); _; } function teamExists(uint256 _teamId) public view returns (bool) { return teamIndexToExist[_teamId] == true; } /// @dev random number from 0 to (_modulus - 1) function randMod(uint256 _randCounter, uint _modulus) internal view returns (uint256) { return uint(keccak256(now, msg.sender, _randCounter)) % _modulus; } function getDeletedTeams() public view returns (uint256[]) { // return addressToDeletedTeams[_address]; return deletedTeamIds; } function getRaceBaseStats(uint256 _id) public view returns ( uint256 strength, uint256 dexterity, uint256 vitality ) { RaceBaseStats storage race = raceBaseStats[_id]; strength = race.strength; dexterity = race.dexterity; vitality = race.vitality; } } // File: contracts/Battle/BattleAdmin.sol contract BattleAdmin is BattleBase { event ContractUpgrade(address newContract); address public newContractAddress; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; uint32[7] public prizeCooldowns = [ uint32(1 minutes), uint32(30 minutes), uint32(2 hours), uint32(6 hours), uint32(12 hours), uint32(1 days), uint32(3 days) ]; function setFighterCoreAddress(address _address) public onlyOwner { _setFighterCoreAddress(_address); } function _setFighterCoreAddress(address _address) internal { FighterCoreInterface candidateContract = FighterCoreInterface(_address); require(candidateContract.implementsERC721()); fighterCore = candidateContract; } function setGeneScienceAddress(address _address) public onlyOwner { _setGeneScienceAddress(_address); } function _setGeneScienceAddress(address _address) internal { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); geneScience = candidateContract; } function setBattleDeciderAddress(address _address) public onlyOwner { _setBattleDeciderAddress(_address); } function _setBattleDeciderAddress(address _address) internal { BattleDeciderInterface deciderCandidateContract = BattleDeciderInterface(_address); require(deciderCandidateContract.isBattleDecider()); battleDecider = deciderCandidateContract; } function addRace(uint8 _strength, uint8 _dexterity, uint8 _vitality) public onlyOwner { raceBaseStats.push(RaceBaseStats({ strength: _strength, dexterity: _dexterity, vitality: _vitality })); } // in case we ever add a bad race type function removeLastRace() public onlyOwner { // don't allow the first 4 races to be removed require(raceBaseStats.length > 4); delete raceBaseStats[raceBaseStats.length - 1]; } /// @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. /// @param _v2Address new address function setNewAddress(address _v2Address) public onlyOwner whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } // Owner can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 _secs) external onlyOwner { require(_secs < prizeCooldowns[0]); secondsPerBlock = _secs; } } // File: contracts/Battle/BattlePrize.sol contract BattlePrize is BattleAdmin { // array index is level, value is experience to reach that level uint32[50] public stats = [ 0, 100, 300, 600, 1000, 1500, 2100, 2800, 3600, 4500, 5500, 6600, 7800, 9100, 10500, 12000, 13600, 15300, 17100, 19000, 21000, 23100, 25300, 27600, 30000, 32500, 35100, 37800, 40600, 43500, 46500, 49600, 52800, 56100, 59500, 63000, 66600, 70300, 74100, 78000, 82000, 86100, 90300, 94600, 99000, 103500, 108100, 112800, 117600, 122500 ]; uint8[11] public extraStatsForGen = [ 16, // 0 - here for ease of use even though we never create gen0s 12, // 1 10, // 2 8, // 3 7, // 4 6, // 5 5, // 6 4, // 7 3, // 8 2, // 9 1 // 10+ ]; // the number of battles before a delay to gain new exp kicks in uint8 public battlesTillBattleCooldown = 5; // the number of battles before a delay to gain new exp kicks in uint32 public experienceDelay = uint32(6 hours); // Luck is determined as follows: // Rank 0 (5 stars) - random between 4~5 // Rank 1-2 (4 stars) - random between 2~4 // Rank 3-8 (3 stars) - random between 2~3 // Rank 9-15 (2 stars) - random between 1~3 // Rank 16+ (1 star) - random between 1~2 function genToLuck(uint256 _gen, uint256 _rand) public pure returns (uint8) { if (_gen >= 1 || _gen <= 2) { return 2 + uint8(_rand) % 3; // 2 to 4 } else if (_gen >= 3 || _gen <= 8) { return 2 + uint8(_rand) % 2; // 2 to 3 } else if (_gen >= 9 || _gen <= 15) { return 1 + uint8(_rand) % 3; // 1 to 3 } else { // 16+ return 1 + uint8(_rand) % 2; // 1 to 2 } } function raceToBaseStats(uint _race) public view returns ( uint8 strength, uint8 dexterity, uint8 vitality ) { // in case we ever have an unknown race due to new races added if (_race >= raceBaseStats.length) { _race = 0; } RaceBaseStats memory raceStats = raceBaseStats[_race]; strength = raceStats.strength; dexterity = raceStats.dexterity; vitality = raceStats.vitality; } function genToExtraStats(uint256 _gen, uint256 _rand) public view returns ( uint8 extraStrength, uint8 extraDexterity, uint8 extraVitality ) { // in case we ever have an unknown race due to new races added if (_gen >= 10) { _gen = 10; } uint8 extraStats = extraStatsForGen[_gen]; uint256 rand1 = _rand & 0xff; uint256 rand2 = _rand >> 16 & 0xff; uint256 rand3 = _rand >> 16 >> 16 & 0xff; uint256 sum = rand1 + rand2 + rand3; extraStrength = uint8((extraStats * rand1) / sum); extraDexterity = uint8((extraStats * rand2) / sum); extraVitality = uint8((extraStats * rand3) / sum); uint8 remainder = extraStats - (extraStrength + extraDexterity + extraVitality); if (rand1 > rand2 && rand1 > rand3) { extraStrength += remainder; } else if (rand2 > rand3) { extraDexterity += remainder; } else { extraVitality += remainder; } } function _getStrengthDexterityVitality(uint256 _race, uint256 _generation, uint256 _rand) public view returns ( uint256 strength, uint256 dexterity, uint256 vitality ) { uint8 baseStrength; uint8 baseDexterity; uint8 baseVitality; uint8 extraStrength; uint8 extraDexterity; uint8 extraVitality; (baseStrength, baseDexterity, baseVitality) = raceToBaseStats(_race); (extraStrength, extraDexterity, extraVitality) = genToExtraStats(_generation, _rand); strength = baseStrength + extraStrength; dexterity = baseDexterity + extraDexterity; vitality = baseVitality + extraVitality; } // we return an array here, because we had an issue of too many local variables when returning a tuple // function _generateFighterStats(uint256 _attackerLeaderId, uint256 _defenderLeaderId) internal returns (uint256[6]) { function _generateFighterStats(uint256 generation1, uint256 genes1, uint256 generation2, uint256 genes2) internal returns (uint256[6]) { // uint256 generation1; // uint256 genes1; // uint256 generation2; // uint256 genes2; uint256 generation256 = ((generation1 + generation2) / 2) + 1; // making sure a gen 65536 doesn't turn out as a gen 0 :) if (generation256 > 65535) generation256 = 65535; uint16 generation = uint16(generation256); uint256 genes = geneScience.mixGenes(genes1, genes2); uint256 strength; uint256 dexterity; uint256 vitality; uint256 rand = uint(keccak256(now, msg.sender, randomCounter++)); (strength, dexterity, vitality) = _getStrengthDexterityVitality(_getRaceFromGenes(genes), generation, rand); uint256 luck = genToLuck(genes, rand); return [ generation, genes, strength, dexterity, vitality, luck ]; } // takes in genes and returns raceId // race is first loci after version. // [][]...[][race][version] // each loci = 2B, race is also 2B. father's gene is determining the fighter's race function _getRaceFromGenes(uint256 _genes) internal pure returns (uint256) { return (_genes >> (16)) & 0xff; } function experienceToLevel(uint256 _experience) public view returns (uint256) { for (uint256 i = 0; i < stats.length; i++) { if (stats[i] > _experience) { // current level is i return i; } } return 50; } // returns a number between 0 and 4 based on which stat to increase // 0 - no stat increase // 1 - dexterity // 2 - strength // 3 - vitality // 4 - luck function _calculateNewStat(uint32 _currentExperience, uint32 _newExperience) internal returns (uint256) { // find current level for (uint256 i = 0; i < stats.length; i++) { if (stats[i] > _currentExperience) { // current level is i if (stats[i] <= _newExperience) { // level up a random stat return 1 + randMod(randomCounter++, 4); } else { return 0; } } } // at max level return 0; } // function _getFighterGenAndGenes(uint256 _fighterId) internal view returns ( // uint256 generation, // uint256 genes // ) { // (,,,,, generation, genes,,,,,) = fighterCore.getFighter(_fighterId); // } function _getFighterStatsData(uint256 _fighterId) internal view returns (uint256[6]) { uint256 dexterity; uint256 strength; uint256 vitality; uint256 luck; uint256 experience; uint256 battleCooldownEndTime; ( , battleCooldownEndTime, , , , , , dexterity, strength, vitality, luck, experience ) = fighterCore.getFighter(_fighterId); return [ dexterity, strength, vitality, luck, experience, battleCooldownEndTime ]; } function _getFighterBattleData(uint256 _fighterId) internal view returns (uint256[7]) { uint256 prizeCooldownEndTime; uint256 prizeCooldownIndex; uint256 battleCooldownEndTime; uint256 battlesFought; uint256 battlesWon; uint256 generation; uint256 genes; ( prizeCooldownEndTime, battleCooldownEndTime, prizeCooldownIndex, battlesFought, battlesWon, generation, genes, , , , , ) = fighterCore.getFighter(_fighterId); return [ prizeCooldownEndTime, prizeCooldownIndex, battleCooldownEndTime, battlesFought, battlesWon, generation, genes ]; } function _increaseFighterStats( uint256 _fighterId, uint32 _experienceGained, uint[6] memory data ) internal { // dont update if on cooldown if (data[5] >= block.number) { return; } uint32 experience = uint32(data[4]); uint32 newExperience = experience + _experienceGained; uint256 _statIncrease = _calculateNewStat(experience, newExperience); fighterCore.updateExperience(_fighterId, newExperience); if (_statIncrease == 1) { fighterCore.updateDexterity(_fighterId, uint8(++data[0])); } else if (_statIncrease == 2) { fighterCore.updateStrength(_fighterId, uint8(++data[1])); } else if (_statIncrease == 3) { fighterCore.updateVitality(_fighterId, uint8(++data[2])); } else if (_statIncrease == 4) { fighterCore.updateLuck(_fighterId, uint8(++data[3])); } } function _increaseTeamFighterStats(uint256[] memory _fighterIds, uint32 _experienceGained) private { for (uint i = 0; i < _fighterIds.length; i++) { _increaseFighterStats(_fighterIds[i], _experienceGained, _getFighterStatsData(_fighterIds[i])); } } function _updateFighterBattleStats( uint256 _fighterId, bool _winner, bool _leader, uint[7] memory data, bool _skipAwardPrize ) internal { uint64 prizeCooldownEndTime = uint64(data[0]); uint16 prizeCooldownIndex = uint16(data[1]); uint64 battleCooldownEndTime = uint64(data[2]); uint16 updatedBattlesFought = uint16(data[3]) + 1; // trigger prize cooldown if (_winner && _leader && !_skipAwardPrize) { prizeCooldownEndTime = uint64((prizeCooldowns[prizeCooldownIndex] / secondsPerBlock) + block.number); if (prizeCooldownIndex < 6) { prizeCooldownIndex += 1; } } if (updatedBattlesFought % battlesTillBattleCooldown == 0) { battleCooldownEndTime = uint64((experienceDelay / secondsPerBlock) + block.number); } fighterCore.updateFighterBattleStats( _fighterId, prizeCooldownEndTime, prizeCooldownIndex, battleCooldownEndTime, updatedBattlesFought, uint16(data[4]) + (_winner ? 1 : 0) // battlesWon ); } function _updateTeamBattleStats(uint256[] memory _fighterIds, bool _attackerWin, bool _skipAwardPrize) private { for (uint i = 0; i < _fighterIds.length; i++) { _updateFighterBattleStats(_fighterIds[i], _attackerWin, i == 0, _getFighterBattleData(_fighterIds[i]), _skipAwardPrize); } } function _awardPrizeFighter( address _winner, uint256[7] _attackerLeader, uint256[7] _defenderLeader ) internal returns (uint16 prizeGen, uint256 prizeGenes) { uint256[6] memory newFighterData = _generateFighterStats(_attackerLeader[5], _attackerLeader[6], _defenderLeader[5], _defenderLeader[6]); prizeGen = uint16(newFighterData[0]); prizeGenes = newFighterData[1]; fighterCore.createPrizeFighter( prizeGen, prizeGenes, uint8(newFighterData[2]), uint8(newFighterData[3]), uint8(newFighterData[4]), uint8(newFighterData[5]), _winner ); } function _updateFightersAndAwardPrizes( uint256[] _attackerFighterIds, uint256[] _defenderFighterIds, bool _attackerWin, address _winnerAddress, uint32 _attackerExperienceGained, uint32 _defenderExperienceGained ) internal returns (uint16 prizeGen, uint256 prizeGenes) { // grab prize cooldown info before it gets updated uint256[7] memory attackerLeader = _getFighterBattleData(_attackerFighterIds[0]); uint256[7] memory defenderLeader = _getFighterBattleData(_defenderFighterIds[0]); bool skipAwardPrize = (_attackerWin && attackerLeader[0] >= block.number) || (!_attackerWin && defenderLeader[0] >= block.number); _increaseTeamFighterStats(_attackerFighterIds, _attackerExperienceGained); _increaseTeamFighterStats(_defenderFighterIds, _defenderExperienceGained); _updateTeamBattleStats(_attackerFighterIds, _attackerWin, skipAwardPrize); _updateTeamBattleStats(_defenderFighterIds, !_attackerWin, skipAwardPrize); // prizes // dont award prize if on cooldown if (skipAwardPrize) { return; } return _awardPrizeFighter(_winnerAddress, attackerLeader, defenderLeader); } } // File: contracts/Battle/BattleCore.sol contract BattleCore is BattlePrize { function BattleCore(address _coreAddress, address _geneScienceAddress, address _battleDeciderAddress) public { addRace(4, 4, 4); // half elf addRace(6, 2, 4); // orc addRace(4, 5, 3); // succubbus addRace(6, 4, 2); // mage addRace(7, 1, 4); _setFighterCoreAddress(_coreAddress); _setGeneScienceAddress(_geneScienceAddress); _setBattleDeciderAddress(_battleDeciderAddress); // no team 0 uint256[] memory fighterIds = new uint256[](1); fighterIds[0] = uint256(0); _createTeam(address(0), fighterIds); teamIndexToExist[0] = false; } /// @dev DON'T give me your money. function() external {} function totalTeams() public view returns (uint256) { // team 0 doesn't exist return teams.length - 1; } function isValidTeam(uint256[] _fighterIds) public view returns (bool) { for (uint i = 0; i < _fighterIds.length; i++) { uint256 fighterId = _fighterIds[i]; if (fighterCore.ownerOf(fighterId) != msg.sender) return false; if (fighterIndexToTeam[fighterId] > 0) return false; // check for duplicate fighters for (uint j = i + 1; j < _fighterIds.length; j++) { if (_fighterIds[i] == _fighterIds[j]) { return false; } } } return true; } function createTeam(uint256[] _fighterIds) public whenNotPaused returns(uint256) { require(_fighterIds.length > 0 && _fighterIds.length <= maxPerTeam); require(isValidTeam(_fighterIds)); return _createTeam(msg.sender, _fighterIds); } function _createTeam(address _owner, uint256[] _fighterIds) internal returns(uint256) { Team memory _team = Team({ owner: _owner, fighterIds: _fighterIds }); uint256 newTeamId; // reuse teamId if address has deleted teams if (deletedTeamIds.length > 0) { newTeamId = deletedTeamIds[deletedTeamIds.length - 1]; delete deletedTeamIds[deletedTeamIds.length - 1]; deletedTeamIds.length--; teams[newTeamId] = _team; } else { newTeamId = teams.push(_team) - 1; } require(newTeamId <= 4294967295); for (uint i = 0; i < _fighterIds.length; i++) { uint256 fighterId = _fighterIds[i]; fighterIndexToTeam[fighterId] = newTeamId; } teamIndexToExist[newTeamId] = true; TeamCreated(newTeamId, _fighterIds); return newTeamId; } function deleteTeam(uint256 _teamId) public whenNotPaused onlyTeamOwner(_teamId) onlyExistingTeam(_teamId) { _deleteTeam(_teamId); } function _deleteTeam(uint256 _teamId) private { Team memory team = teams[_teamId]; for (uint256 i = 0; i < team.fighterIds.length; i++) { fighterIndexToTeam[team.fighterIds[i]] = 0; } TeamDeleted(_teamId, team.fighterIds); delete teams[_teamId]; deletedTeamIds.push(_teamId); teamIndexToExist[_teamId] = false; } function battle(uint256[] _attackerFighterIds, uint256 _defenderTeamId) public whenNotPaused onlyExistingTeam(_defenderTeamId) returns (bool) { require(_attackerFighterIds.length > 0 && _attackerFighterIds.length <= maxPerTeam); require(isValidTeam(_attackerFighterIds)); Team memory defenderTeam = teams[_defenderTeamId]; // check that a user isn't attacking himself require(msg.sender != defenderTeam.owner); uint256[] memory defenderFighterIds = defenderTeam.fighterIds; bool attackerWon; uint256 xpForAttacker; uint256 xpForDefender; _deleteTeam(_defenderTeamId); ( attackerWon, xpForAttacker, xpForDefender ) = battleDecider.determineWinner(getFighterArray(_attackerFighterIds), getFighterArray(defenderFighterIds)); address winnerAddress; address loserAddress; if (attackerWon) { winnerAddress = msg.sender; loserAddress = defenderTeam.owner; } else { winnerAddress = defenderTeam.owner; loserAddress = msg.sender; } uint16 prizeGen; uint256 prizeGenes; (prizeGen, prizeGenes) = _updateFightersAndAwardPrizes(_attackerFighterIds, defenderFighterIds, attackerWon, winnerAddress, uint32(xpForAttacker), uint32(xpForDefender)); BattleResult(winnerAddress, loserAddress, _attackerFighterIds, defenderFighterIds, attackerWon, prizeGen, prizeGenes, uint32(xpForAttacker), uint32(xpForDefender)); return attackerWon; } /// @param _id The ID of the team of interest. function getTeam(uint256 _id) public view returns ( address owner, uint256[] fighterIds ) { Team storage _team = teams[_id]; owner = _team.owner; fighterIds = _team.fighterIds; } function getFighterArray(uint256[] _fighterIds) public view returns (uint256[7][]) { uint256[7][] memory res = new uint256[7][](_fighterIds.length); for (uint i = 0; i < _fighterIds.length; i++) { uint256 generation; uint256 genes; uint256 dexterity; uint256 strength; uint256 vitality; uint256 luck; uint256 experience; ( , , , , , generation, genes, dexterity, strength, vitality, luck, experience ) = fighterCore.getFighter(_fighterIds[i]); uint256 level = experienceToLevel(experience); res[i] = [ level, generation, strength, dexterity, vitality, luck, genes ]; } return res; } }
returns a number between 0 and 4 based on which stat to increase 0 - no stat increase 1 - dexterity 2 - strength 3 - vitality 4 - luck find current level current level is i level up a random stat
function _calculateNewStat(uint32 _currentExperience, uint32 _newExperience) internal returns (uint256) { for (uint256 i = 0; i < stats.length; i++) { if (stats[i] > _currentExperience) { if (stats[i] <= _newExperience) { return 1 + randMod(randomCounter++, 4); return 0; } } } }
5,389,691
./partial_match/1/0x0F72714B35a366285Df85886A2eE174601292A17/sources/MarsTokenV1.sol
update the pauser role/
function updatePauser(address _newPauser) public onlyOwner { require(_newPauser != address(0)); pauser = _newPauser; emit PauserChanged(pauser); }
4,165,377
/* SPDX-License-Identifier: MIT @**********@ @*********** @*********** @*********** #***@ @***( *********** @**********# @*********** @*********** @*******@ .*********** @***@@@@***@ @***@@@@@@@@ @***@@@@@@@@ @***@@@@@@@@ #***@ @***( ****@@@@@@@ @@@@****@@@@ @***@@@@**** @***@@@@**** @***@@@@@@@@ [email protected]@@@@@@%*** @*** ***@ @***@ @***@ @***@ #***@ @***( **** **** @***@ **** @***@ **** @***@ (*** @*** @******* @******* @*********** @***@ #***@ @***( *******@ **** @***@ **** @*********** @***@ (*** %***@ @***@@@@@@@@ @***@@@@ @@@@@@@@**** @***@ #***@ @***( ****@@@@ **** @***@ **** @***@@@@**** @***@ (*** [email protected]@@@@@@@ @*** ***@ @***@ **** @***@ #***@ @***( **** **** @***@ **** @***@ **** @***@ (*** .***& @*** ***@ @*********** @*********** @*********** #***********( *********** **** @*********** @***@ **** @*******@ .*********** @@@@ @@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ @@@@@@@@@@@@ #@@@@@@@@@@@( @@@@@@@@@@@ @@@@ @@@@@@@@@@@@ @@@@@ @@@@ @@@@@@@@@ [email protected]@@@@@@@@@@ */ /** * @title Rescue Toadz * @author Vladimir Haltakov (@haltakov) * @notice ERC1155 contract for a collection of Ukrainian themed Rescue Toadz * @notice All proceeds from minting and capturing tokens are donated for humanitarian help for Ukraine via Unchain (0x10E1439455BD2624878b243819E31CfEE9eb721C). * @notice The contract represents two types of tokens: single edition tokens (id <= SINGLE_EDITIONS_SUPPLY) and multiple edition POAP tokens (id > SINGLE_EDITIONS_SUPPLY) * @notice Only the single edition tokens are allowed to be minted or captured. * @notice The contract implements a special function capture, that allows anybody to transfer a single edition token to their wallet by matching or increasing the last donation. */ pragma solidity ^0.8.12; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract RescueToadz is ERC1155, Ownable, Pausable, ERC1155Supply { using Strings for uint256; // Number of single edition tokens. For each single edition token, there will be a corresponding multiple edition token. uint256 public constant SINGLE_EDITIONS_SUPPLY = 18; // Mint price uint256 public constant MINT_PRICE = 10000000 gwei; // Address of Unchain Ukraine where all funds will be donated for humanitarian help (see https://unchain.fund/ for details) address public constant CHARITY_ADDRESS = 0x10E1439455BD2624878b243819E31CfEE9eb721C; // The last price a token was minted or captured for mapping(uint256 => uint256) private _lastPrice; // The last owner of a token. This applies only for single edition tokens mapping(uint256 => address) private _ownerOf; /** * @dev Default constructor */ constructor() ERC1155("ipfs://QmXRvBcDGpGYVKa7DpshY4UJQrSHH4ArN2AotHHjDS3BHo/") {} /** * @dev Name of the token */ function name() external pure returns (string memory) { return "Rescue Toadz"; } /** * @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY * @notice Only one token for every id <= SINGLE_EDITIONS_SUPPLY is allowed to be minted (similar to an ERC721 token) * @dev Mint a token * @param tokenId id of the token to be minted */ function mint(uint256 tokenId) external payable whenNotPaused { require( tokenId <= SINGLE_EDITIONS_SUPPLY, "Cannot mint token with id greater than SINGLE_EDITIONS_SUPPLY" ); require(tokenId > 0, "Cannot mint token 0"); require(!exists(tokenId), "Token already minted"); require(msg.value >= MINT_PRICE, "Not enough funds to mint token"); _ownerOf[tokenId] = msg.sender; _lastPrice[tokenId] = msg.value; _mint(msg.sender, tokenId, 1, ""); payable(CHARITY_ADDRESS).transfer(msg.value); } /** * @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY * @notice This function allows transferring a token from another wallet by paying more than the last price paid * @notice This function will mint a POAP token (id > SINGLE_EDITIONS_SUPPLY) in the wallet from which the token is captured * @dev Capture a token from another wallet * @param tokenId id of the token to be captured */ function capture(uint256 tokenId) external payable whenNotPaused { require( tokenId <= SINGLE_EDITIONS_SUPPLY, "Cannot capture a token with id greater than SINGLE_EDITIONS_SUPPLY" ); require(exists(tokenId), "Cannot capture a token that is not minted"); require( msg.value >= _lastPrice[tokenId], "Cannot capture a token without paying at least the last price" ); address lastOwner = _ownerOf[tokenId]; _ownerOf[tokenId] = msg.sender; _lastPrice[tokenId] = msg.value; _safeTransferFrom(lastOwner, msg.sender, tokenId, 1, ""); _mint(lastOwner, SINGLE_EDITIONS_SUPPLY + tokenId, 1, ""); payable(CHARITY_ADDRESS).transfer(msg.value); } /** * @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY * @dev Get the last price a token was minted or captured * @param tokenId id of the token to check */ function lastPrice(uint256 tokenId) external view returns (uint256) { require( tokenId <= SINGLE_EDITIONS_SUPPLY, "Cannot get the last price of a token with id greater than SINGLE_EDITIONS_SUPPLY" ); if (!exists(tokenId)) { return 0; } return _lastPrice[tokenId]; } /** * @notice Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY, because they are guaranteed to have a single edition * @dev Get the owner of a token with an id <= SINGLE_EDITIONS_SUPPLY * @param tokenId id of the token to get the owner of */ function ownerOf(uint256 tokenId) external view returns (address) { require( tokenId <= SINGLE_EDITIONS_SUPPLY, "Cannot get the owner for token with id greater than SINGLE_EDITIONS_SUPPLY" ); if (!exists(tokenId)) { return address(0); } return _ownerOf[tokenId]; } /** * @notice Override the setApprovalForAll function to prevent selling the NFT on exchanges */ function setApprovalForAll(address, bool) public virtual override { revert("setApprovalForAll is not supported"); } /** * @dev Get the URI of a token * @param tokenId id of the token */ function uri(uint256 tokenId) public view virtual override returns (string memory) { require(exists(tokenId), "URI query for nonexistent token"); string memory baseURI = super.uri(tokenId); return string(abi.encodePacked(baseURI, tokenId.toString())); } /** * @dev Change the base URI * @param newuri the new URI */ function setURI(string memory newuri) external onlyOwner { _setURI(newuri); } /** * @dev Pause the contract */ function pause() external onlyOwner { _pause(); } /** * @dev Unpause the contract */ function unpause() external onlyOwner { _unpause(); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override(ERC1155, ERC1155Supply) whenNotPaused { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/ERC1155Supply.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of ERC1155 that adds tracking of total supply per id. * * Useful for scenarios where Fungible and Non-fungible tokens have to be * clearly identified. Note: While a totalSupply of 1 might mean the * corresponding is an NFT, there is no guarantees that no other token with the * same id are not going to be minted. */ abstract contract ERC1155Supply is ERC1155 { mapping(uint256 => uint256) private _totalSupply; /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates whether any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return ERC1155Supply.totalSupply(id) > 0; } /** * @dev See {ERC1155-_beforeTokenTransfer}. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/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 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: 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 (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 // 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); }
Only allowed for tokens with id <= SINGLE_EDITIONS_SUPPLY This function allows transferring a token from another wallet by paying more than the last price paid This function will mint a POAP token (id > SINGLE_EDITIONS_SUPPLY) in the wallet from which the token is captured Capture a token from another wallet tokenId id of the token to be captured/
function capture(uint256 tokenId) external payable whenNotPaused { require( tokenId <= SINGLE_EDITIONS_SUPPLY, "Cannot capture a token with id greater than SINGLE_EDITIONS_SUPPLY" ); require(exists(tokenId), "Cannot capture a token that is not minted"); require( msg.value >= _lastPrice[tokenId], "Cannot capture a token without paying at least the last price" ); address lastOwner = _ownerOf[tokenId]; _ownerOf[tokenId] = msg.sender; _lastPrice[tokenId] = msg.value; _safeTransferFrom(lastOwner, msg.sender, tokenId, 1, ""); _mint(lastOwner, SINGLE_EDITIONS_SUPPLY + tokenId, 1, ""); payable(CHARITY_ADDRESS).transfer(msg.value); }
5,708,719
pragma solidity ^0.4.24; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct Insurance { bytes32 flightKey; address passenger; uint256 payment; } struct Flight { address airline; uint256 departureTimestamp; uint8 statusCode; } struct Airline { address airlineAccount; string companyName; bool isRegistered; bool isFunded; uint256 votes; mapping(address => bool) voters; // track airlines that have already voted } Airline[50] private airlines; // List of up to 50 airlines (may or may not be registered) Insurance[] private insurance; // List of passenger insurance mapping(address => uint256) private passengerCredit; // For a given passenger has the total credit due // uint256 private constant SENTINEL = 2 ^ 256 - 1; // MAX VALUE => "not found" uint256 private airlineCount; mapping(bytes32 => Flight) private flights; // keys (see getFlightKey) of flights for airline mapping(address => bool) private authorizedAppContracts; // Event fired each time an oracle submits a response event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status); event OracleReport(address airline, string flight, uint256 timestamp, uint8 status); // Event fired when flight status request is submitted // Oracles track this and if they have a matching index // they fetch data and submit a response event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp); // Incremented to add pseudo-randomness at various points uint8 private nonce = 0; //////////////////// // State for Oracles //////////////////// struct Oracle { bool isRegistered; uint8[3] indexes; } // Track all registered oracles mapping(address => Oracle) private oracles; // Model for responses from oracles struct ResponseInfo { address requester; // Account that requested status bool isOpen; // If open, oracle responses are accepted mapping(uint8 => address[]) responses; // Mapping key is the status code reported // This lets us group responses and identify // the response that majority of the oracles } // Track all oracle responses // Key = hash(index, flight, timestamp) mapping(bytes32 => ResponseInfo) private oracleResponses; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner * First airline is registered at deployment */ constructor (address firstAirline ) public { require(firstAirline != address(0), 'Must specify the first airline to register when deploying contract'); contractOwner = msg.sender; airlines[airlineCount++] = Airline({airlineAccount : firstAirline, companyName : "British Airways", isRegistered : true, isFunded : false, votes : 0}); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires the calling contract has been authorized */ modifier requireAuthorizedCaller() { require(authorizedAppContracts[msg.sender] || msg.sender == address(this), "Caller is not an authorized contract"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns (bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /** * @dev Authorize an App Contract to delegate to this data contract */ function authorizeCaller(address _appContract) public { authorizedAppContracts[_appContract] = true; } // Return index of the Airline for the matching address // or a large SENTINEL value if no match function findAirline(address _airline) public view returns (uint256) { // Loop through airline until found or end uint256 i = 0; while (i < airlineCount) { if (airlines[i].airlineAccount == _airline) { return i; } i++; } return airlineCount + 1000; } // True if the Voter has not already raise // a registration vote for airline function hasNotAlreadyVoted(address _airline, address _voter) external view returns (bool) { uint256 idx = findAirline(_airline); if (idx < airlineCount) { return !airlines[idx].voters[_voter]; } return true; } function getCredit(address passenger) public view returns (uint256) { return passengerCredit[passenger]; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ // Useful to check how close an airline is to being registered based on number of votes // returns: isRegistered, isFunded, votes function getAirlineStatus(address _airline) public view requireAuthorizedCaller requireIsOperational returns (bool isRegistered, bool isFunded, uint256 votes) { uint256 idx = findAirline(_airline); if (idx < airlineCount) { Airline memory airline = airlines[idx]; return (airline.isRegistered, airline.isFunded, airline.votes); } return (false, false, 0); } /** * Airline details accessed by index */ function getAirlineStatus(uint256 idx) external view requireAuthorizedCaller requireIsOperational returns (bool isRegistered, bool isFunded, uint256 votes, address airlineAccount, string companyName) { airlineAccount = airlines[idx].airlineAccount; companyName = airlines[idx].companyName; (isRegistered, isFunded, votes) = getAirlineStatus(airlineAccount); return (isRegistered, isFunded, votes, airlineAccount, companyName); } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function addAirline (address airlineAccount, string companyName, bool isRegistered, bool isFunded, uint8 votes ) external requireAuthorizedCaller requireIsOperational { airlines[airlineCount++] = Airline({airlineAccount : airlineAccount, companyName : companyName, isRegistered : isRegistered, isFunded : isFunded, votes : votes}); } /** * An airline has voted for another airline to join group */ function registerVote(uint256 idx, address _voter) external requireAuthorizedCaller requireIsOperational { // Airline has had at least one registration request // Incrementing by 1 vote.. airlines[idx].votes++; // Record vote airlines[idx].voters[_voter] = true; } /** * Return count of votes for specified airline */ function airlineVotes(uint256 idx) external view returns (uint256) { return airlines[idx].votes; } /** * Update status of a listed airline to Registered */ function registerAirline(uint256 idx) external requireAuthorizedCaller requireIsOperational { airlines[idx].isRegistered = true; } /** * Count the number of airlines that are actually registered */ function registeredAirlinesCount() external view returns (uint256) { uint256 registered = 0; for (uint i = 0; i < airlineCount; i++) { if (airlines[i].isRegistered) { registered++; } } return registered; } // Add a flight schedule to an airline function registerFlight(address _airline, string _flight, uint256 _timestamp) external requireIsOperational requireAuthorizedCaller { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); flights[flightKey] = Flight({airline : _airline, departureTimestamp : _timestamp, statusCode : 0}); } /** * @dev Buy insurance for a flight * */ function buy (address passenger, address _airline, string _flight, uint256 _timestamp ) external payable requireIsOperational requireAuthorizedCaller { bytes32 flightKey = getFlightKey(_airline, _flight, _timestamp); Flight memory flight = flights[flightKey]; require(address(flight.airline) != address(0), 'Flight does not exist'); Insurance memory _insurance = Insurance({flightKey : flightKey, passenger : passenger, payment : msg.value}); insurance.push(_insurance); } /** * @dev Credits payouts to insurees at 1.5x the original payment */ function creditInsurees ( address airline, string flight, uint256 timestamp, uint256 multiplyBy, uint256 divideBy ) internal requireAuthorizedCaller requireIsOperational { bytes32 delayedFlightKey = getFlightKey(airline, flight, timestamp); uint256 i = 0; uint256 totalRecords = insurance.length; while (i < totalRecords) { Insurance memory _insurance = insurance[i]; if (_insurance.flightKey == delayedFlightKey) { address passenger = _insurance.passenger; // Compensation determined using rationals uint256 compensation = _insurance.payment.mul(multiplyBy).div(divideBy); passengerCredit[passenger] += _insurance.payment.add(compensation); // ..and remove insurance record to prevent possible double-spend delete insurance[i]; } i++; } } // Called after oracle has updated flight status function processFlightStatus ( address airline, string flight, uint256 timestamp, uint8 statusCode, uint8 multiplyBy, uint8 divideBy, uint8 payoutCode ) public requireAuthorizedCaller requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey].statusCode = statusCode; if (statusCode == payoutCode) { creditInsurees(airline, flight, timestamp, multiplyBy, divideBy); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay (address passenger ) external requireAuthorizedCaller requireIsOperational { uint256 amount = passengerCredit[passenger]; passengerCredit[passenger] = 0; passenger.transfer(amount); } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund (address airlineAddr) public payable requireAuthorizedCaller requireIsOperational { uint256 idx = findAirline(airlineAddr); if (idx < airlineCount) { airlines[idx].isFunded = true; } } // Unique hash function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns (bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable requireAuthorizedCaller { // fund(); } /** * @dev Returns true if supplied address matches an airline address */ function isAirline(address _airline) public view returns (bool) { uint256 idx = findAirline(_airline); if (idx < airlineCount) { return true; } return false; } /** * @dev Returns true if airline is funded */ function isFundedAirline(address _airline) public view returns (bool) { uint256 idx = findAirline(_airline); if (idx < airlineCount) { return airlines[idx].isFunded; } // Airline account doesn't exist return false; } // Generate a request for oracles to fetch flight information function fetchFlightStatus ( address airline, string flight, uint256 timestamp, address passenderAddr ) requireAuthorizedCaller requireIsOperational external { uint8 index = getRandomIndex(passenderAddr); // Generate a unique key for storing the request bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); oracleResponses[key] = ResponseInfo({ requester : passenderAddr, isOpen : true }); emit OracleRequest(index, airline, flight, timestamp); } /** * Total airlines currently registered or waiting to be registered */ function getAirlineCount() public view returns (uint256) { return airlineCount; } // /** // * Return an array of the airline accounts // * which need to be extracted from the airlines struct // */ // function getAirlines() // external // view // returns (address[50]) // { // address[50] memory acc; // uint256 i = 0; // while (i < airlineCount) { // acc[i] = airlines[i].airlineAccount; // i++; // } // return acc; // } // Register an oracle with the contract function registerOracle (address oracleAddr ) external payable requireIsOperational requireAuthorizedCaller { uint8[3] memory indexes = generateIndexes(oracleAddr); Oracle memory newOracle = Oracle({ isRegistered : true, indexes : indexes }); oracles[oracleAddr] = newOracle; } function getMyIndexes (address oracleAddr ) view public returns (uint8[3] memory) { require(oracles[oracleAddr].isRegistered, "Not registered as an oracle"); return oracles[oracleAddr].indexes; } // Called by oracle when a response is available to an outstanding request // For the response to be accepted, there must be a pending request that is open // and matches one of the three Indexes randomly assigned to the oracle at the // time of registration (i.e. uninvited oracles are not welcome) // // Multiple/divide numbers provide a method to get percentage amounts of credit function submitOracleResponse ( uint8 index, address airline, string flight, uint256 timestamp, uint8 statusCode, uint256 min_responses, address oracleAddr, uint8 multiplyBy, uint8 divideBy, uint8 payoutCode ) external requireIsOperational requireAuthorizedCaller { require((oracles[oracleAddr].indexes[0] == index) || (oracles[oracleAddr].indexes[1] == index) || (oracles[oracleAddr].indexes[2] == index), "Index does not match oracle request"); bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp)); require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request"); oracleResponses[key].responses[statusCode].push(oracleAddr); // Information isn't considered verified until at least MIN_RESPONSES // oracles respond with the *** same *** information emit OracleReport(airline, flight, timestamp, statusCode); if (oracleResponses[key].responses[statusCode].length >= min_responses) { emit FlightStatusInfo(airline, flight, timestamp, statusCode); // Handle flight status as appropriate this.processFlightStatus(airline, flight, timestamp, statusCode, multiplyBy, divideBy, payoutCode); } } // Returns array of three non-duplicating integers from 0-9 function getRandomIndex ( address account ) internal returns (uint8) { uint8 maxValue = 10; // Pseudo random number...the incrementing nonce adds variation uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number), nonce++, account))) % maxValue); if (nonce > 250) { nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt } return random; } // Returns array of three non-duplicating integers from 0-9 function generateIndexes ( address account ) internal returns (uint8[3] memory) { uint8[3] memory indexes; indexes[0] = getRandomIndex(account); indexes[1] = indexes[0]; while (indexes[1] == indexes[0]) { indexes[1] = getRandomIndex(account); } indexes[2] = indexes[1]; while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) { indexes[2] = getRandomIndex(account); } return indexes; } }
Called after oracle has updated flight status
function processFlightStatus ( address airline, string flight, uint256 timestamp, uint8 statusCode, uint8 multiplyBy, uint8 divideBy, uint8 payoutCode ) public requireAuthorizedCaller requireIsOperational { bytes32 flightKey = getFlightKey(airline, flight, timestamp); flights[flightKey].statusCode = statusCode; if (statusCode == payoutCode) { creditInsurees(airline, flight, timestamp, multiplyBy, divideBy); } }
2,523,542
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol
Get the smallest part of the token that’s not divisible. return The smallest non-divisible part of the token./
function granularity() external view returns(uint256) { return _granularity; }
4,032,093
/* ■■■■■ ■■■■■■■■■■ ■■■■■■■ ■■■■ ■■■■■■ ■■■ ■■■ ■■ ■■■■■ ■■ ■■■ ■■ ■■■■■ ■■■■ ■■■■■■■■ ■ ■■■■ ■■■ ■■ ■■■ ■■■ ■■ ■■■ ■■■■ ■■■■ ■■■ ■■■ ■■■ ■■■■■■■■ ■■■■■ ■■■ ■■ ■■■ ■■■ ■■ ■■■ ■■■■ ■■■ ■■ ■■■ ■■ ■■■■■■■■■■■■■■■■■ ■■■■■■■■ ■■ ■■ ■■■■■ ■■■■■■ ■■■ ■■■ ■■ ■■■■■■■■■■■■■■■■■ ■■■■■■■■ ■■ ■■ ■■■■■ ■■ ■■ ■■■ ■■■■■ ■■■ ■■ ■■■■■■■■■■■■■■■ ■■■ ■■ ■■■ ■■ ■■■■■■ ■■■■■■■■ ■■■ ■■■■ ■■■ ■■ ■■■■■■■■■■■■■■■■■ ■■■ ■■ ■■■■■■■ ■■ ■■■ ■■ ■■ ■■■■■■■■ ■■■■■■■ ■■■■■■■■■■■■■■■■■ ■■■ ■■ ■■■■■ ■■ ■■■ ■■■ ■■■ ■■■■■ ■■■■■ ■■■■■■■■■■■■■■■■■ ■■■ ■■■■■■■■■■■■■ ■■■■■■■■ ■■■■■■■■■■■■■■ ■■■■■■■■■■■■■■■■■■■ ■■■■■■■■■ ■■■■■■■■■ ■■■■■■■■ ■■■■■■■ ■■■■■■ ■■ ■■■■■■■■■■■■ ■■■■■■■■■■ ■■■ ■ ■■■■■■■■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ ■■■ ■ ■■■■■■■■■ ■■■■■■■■■■■■■■■■■■■■■■■ ■■ ■■ ■■■■■ ■■■■■■■■■■■ ■■ ■■■■ ■■■ ■■■■■■ */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "./HokagoCore.sol"; contract Hokago is HokagoCore{ using Strings for uint256; uint64 public preSalePrice; uint64 public publicSalePrice; uint64 public saleLimit; uint64 public allowListCount; bool public isPublicSale; bool public isPreSale; string public baseTokenURI; mapping(address => uint256) private _allowList; mapping(address => uint256) private _numberMinted; constructor(uint64 _preSalePriceWei, uint64 _publicSalePriceWei, uint64 _saleLimit, string memory _baseTokenURI) HokagoCore("Hokago", "HOKAGO") { preSalePrice = _preSalePriceWei; publicSalePrice = _publicSalePriceWei; saleLimit = _saleLimit; baseTokenURI = _baseTokenURI; } // Sale Config function startPreSale() public virtual onlyOwner { isPublicSale = false; isPreSale = true; } function startPublicSale() public virtual onlyOwner { isPublicSale = true; isPreSale = false; } function pausePreSale() public virtual onlyOwner { isPreSale = false; } function pausePublicSale() public virtual onlyOwner { isPublicSale = false; } function updateSaleLimit(uint64 limit) external virtual onlyOwner { saleLimit = limit; } // AllowList Config function deleteAllowList(address addr) public virtual onlyOwner { allowListCount = allowListCount - uint64(_allowList[addr]); delete(_allowList[addr]); } function changeAllowList(address addr, uint256 maxMint) public virtual onlyOwner { allowListCount = allowListCount - uint64(_allowList[addr]); _allowList[addr] = maxMint; allowListCount = allowListCount + uint64(maxMint); } function pushAllowListAddresses(address[] memory list) public virtual onlyOwner { for (uint i = 0; i < list.length; i++) { _allowList[list[i]]++; allowListCount++; } } // Mint function devMint(uint256[] memory list) external virtual onlyOwner { for (uint256 i = 0; i<list.length; i++) { _safeMint(_msgSender(), list[i]); } } function preSaleMint(uint256 requestTokenID) external virtual payable callerIsUser { uint256 price = uint256(preSalePrice); require(!_exists(requestTokenID), "Request token has already been minted"); require(requestTokenID != 0, "Can not mintable ID (=0)"); require(msg.value >= price, "Need to send more ETH"); require(isPreSale, "Presale has not begun yet"); require(_allowList[_msgSender()] > 0, "Not eligible for allowlist mint"); require(requestTokenID <= uint256(saleLimit), "Request character is not available yet"); _safeMint(_msgSender(), requestTokenID); _allowList[_msgSender()]--; _numberMinted[_msgSender()]++; } function publicSaleMint(uint256 requestTokenID) external virtual payable callerIsUser { uint256 price = uint256(publicSalePrice); require(!_exists(requestTokenID), "Request token has already been minted"); require(requestTokenID != 0, "Can not mintable ID (=0)"); require(msg.value >= price, "Need to send more ETH"); require(isPublicSale, "Publicsale has not begun yet"); require(requestTokenID <= uint256(saleLimit), "Request character is not available yet"); require(_numberMinted[_msgSender()] < 50, "Reached mint limit (=50)"); _safeMint(_msgSender(), requestTokenID); _numberMinted[_msgSender()]++; } // Generate Random-Mintable TokenID function generateRandTokenID(uint256 characterNo, uint256 jsTimestamp) public view returns (uint256) { uint256 randNumber; uint256 counter = 0; uint256 startNo = ((characterNo-1) * 400) + 1; uint256 endNo = characterNo * 400; uint256[] memory mintableIDs = new uint256[](400); require(endNo <= uint256(saleLimit), "Request character is not available yet"); for(uint256 i=startNo; i<=endNo; i++) { if(!_exists(i)) { mintableIDs[counter] = i; counter++; } } if(counter == 0){ return 0; } else{ randNumber = uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, jsTimestamp))) % counter; return mintableIDs[randNumber]; } } // URI function setBaseURI(string memory baseURI) external virtual onlyOwner { baseTokenURI = baseURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(baseTokenURI, tokenId.toString(), '.json')); } // Status Chack function allowListCountOfOwner(address owner) external view returns(uint256) { return _allowList[owner]; } function mintedTokens() external view onlyOwner returns (uint256[] memory) { uint256 array_length = totalSupply(); uint256[] memory arrayMemory = new uint256[](array_length); for(uint256 i=0; i<array_length; i++){ arrayMemory[i] = tokenByIndex(i); } return arrayMemory; } function mintableTokensByCharacter(uint256 characterNo) public view onlyOwner returns (uint256[] memory) { uint256 counter = 0; uint256 startNo = ((characterNo-1) * 400) + 1; uint256 endNo = characterNo * 400; uint256[] memory mintableIDs = new uint256[](400); for(uint256 i=startNo; i<=endNo; i++) { if(!_exists(i)) { mintableIDs[counter] = i; counter++; } } return mintableIDs; } function numberMintedOfOwner(address owner) external view returns (uint256) { require(owner != address(0), "Number minted query for the zero address"); return _numberMinted[owner]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./ContextMixin.sol"; import "./Royalty.sol"; contract HokagoCore is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable, ContextMixin, HasSecondarySaleFees, ReentrancyGuard { constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) HasSecondarySaleFees(new address payable[](0), new uint256[](0)) { address payable[] memory thisAddressInArray = new address payable[](1); thisAddressInArray[0] = payable(address(this)); uint256[] memory royaltyWithTwoDecimals = new uint256[](1); royaltyWithTwoDecimals[0] = 800; _setCommonRoyalties(thisAddressInArray, royaltyWithTwoDecimals); } //Event event levelUp(uint256 indexed tokenId, string indexed levelName, uint32 oldLevel, uint32 newLevel); event changeCharacterSheet(address indexed changer, uint256 indexed characterNo, string indexed key, string oldValue, string newValue); event addDiary(uint256 indexed tokenId, string diaryStr); //helper modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } // Withdraw function withdrawETH() external onlyOwner nonReentrant { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } // Override function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); _transactionTimestamp[tokenId] = block.timestamp; if(from == address(0)){ _setRandLevels(tokenId); } else if (tx.origin != msg.sender) { //only caller is contract _communicationLevelUp(tokenId); } } function isApprovedForAll(address _owner, address _operator) public override view returns(bool isOperator) { return ERC721.isApprovedForAll(_owner, _operator); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override(ERC721) { super.safeTransferFrom(from, to, tokenId); } function _burn(uint256 tokenId) internal onlyOwner override(ERC721, ERC721URIStorage) { super._burn(tokenId); } function _setTokenURI(uint256 tokenId, string memory itemName) internal virtual override(ERC721URIStorage) { super._setTokenURI(tokenId, itemName); } function tokenURI(uint256 tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable, HasSecondarySaleFees) returns (bool) { return ERC721.supportsInterface(interfaceId) || HasSecondarySaleFees.supportsInterface(interfaceId); } //CharacterDetail struct level{ uint32 Creativity; uint32 Intelligence; uint32 Energy; uint32 Luck; uint32 CommunicationSkills; } mapping(uint256 => level) private _characterLevels; mapping(uint256 => string[]) private _ownerDiaries; mapping(uint256 => uint256) private _transactionTimestamp; mapping(uint256 => mapping(string => string)) private _characterSheet; bool public isLevelUp = false; address public fanFictionContract; function viewCharacterLevels(uint256 tokenId) public view returns (uint32[] memory) { uint32[] memory arrayMemory = new uint32[](5); arrayMemory[0] = _characterLevels[tokenId].Creativity; arrayMemory[1] = _characterLevels[tokenId].Intelligence; arrayMemory[2] = _characterLevels[tokenId].Energy; arrayMemory[3] = _characterLevels[tokenId].Luck; arrayMemory[4] = _characterLevels[tokenId].CommunicationSkills; return arrayMemory; } function viewLevelsByCharacter(uint256 characterNo) public view returns (uint32[] memory) { uint256 length = 2000; uint32[] memory arrayMemory = new uint32[](length); uint256 delta = (characterNo-1) * 400; for(uint256 i=1; i<=400; i++){ uint256 baseNo = (i-1) * 5; arrayMemory[baseNo+0] = _characterLevels[i+delta].Creativity; arrayMemory[baseNo+1] = _characterLevels[i+delta].Intelligence; arrayMemory[baseNo+2] = _characterLevels[i+delta].Energy; arrayMemory[baseNo+3] = _characterLevels[i+delta].Luck; arrayMemory[baseNo+4] = _characterLevels[i+delta].CommunicationSkills; } return arrayMemory; } function generateRandLevels(uint256 tokenId) public view returns(uint256[] memory) { uint256[] memory arrayMemory = new uint256[](5); for(uint256 i=0; i<5; i++){ arrayMemory[i] = uint256(keccak256(abi.encodePacked(address(this), i, tokenId))) % 4; } return arrayMemory; } function _setRandLevels(uint256 tokenId) private { uint256[] memory arrayMemory = new uint256[](5); arrayMemory = generateRandLevels(tokenId); _characterLevels[tokenId].Creativity = uint32(arrayMemory[0]); _characterLevels[tokenId].Intelligence = uint32(arrayMemory[1]); _characterLevels[tokenId].Energy = uint32(arrayMemory[2]); _characterLevels[tokenId].Luck = uint32(arrayMemory[3]); _characterLevels[tokenId].CommunicationSkills = uint32(arrayMemory[4]); } function viewDiary(uint256 tokenId) external view returns (string[] memory) { return _ownerDiaries[tokenId]; } function setDiary(uint256 tokenId, string memory diaryStr) external { require(_msgSender() == ownerOf(tokenId), "you don't own this token"); _ownerDiaries[tokenId].push(diaryStr); emit addDiary(tokenId, diaryStr); } function deleteDiary(uint256 tokenId, uint256 arrayNo) external onlyOwner { _ownerDiaries[tokenId][arrayNo] = ""; } //LevelUp! function startLevelUp() external onlyOwner { isLevelUp = true; } function stopLevelUp() external onlyOwner { isLevelUp = false; } function setFanFictionContractAddress(address contractAddress) external onlyOwner { fanFictionContract = contractAddress; } function devLevelUp(uint256[] memory tokenIds, uint256 abilityNo, uint32 levelUpSize) external onlyOwner { for (uint256 i=0; i<tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; if(abilityNo == 1){ _characterLevels[tokenId].Creativity += levelUpSize; if(_characterLevels[tokenId].Creativity > 10){ _characterLevels[tokenId].Creativity = 10; } } if(abilityNo == 2){ _characterLevels[tokenId].Intelligence += levelUpSize; if(_characterLevels[tokenId].Intelligence > 10){ _characterLevels[tokenId].Intelligence = 10; } } if(abilityNo == 3){ _characterLevels[tokenId].Energy += levelUpSize; if(_characterLevels[tokenId].Energy > 10){ _characterLevels[tokenId].Energy = 10; } } if(abilityNo == 4){ uint32 oldLevel = _characterLevels[tokenId].Luck; _characterLevels[tokenId].Luck += levelUpSize; if(_characterLevels[tokenId].Luck > 10){ _characterLevels[tokenId].Luck = 10; } emit levelUp(tokenId, "Luck", oldLevel, _characterLevels[tokenId].Luck); } if(abilityNo == 5){ _characterLevels[tokenId].CommunicationSkills += levelUpSize; if(_characterLevels[tokenId].CommunicationSkills > 10){ _characterLevels[tokenId].CommunicationSkills = 10; } } } } function intelligenceLevelUp(uint256 tokenId, uint32 levelUpSize) external payable callerIsUser { //0.02ETH * LevelUpSize uint256 Price = 20000000000000000 * uint256(levelUpSize); require(isLevelUp, "levelup is not available yet"); require(msg.value >= Price, "need to send more ETH"); require(_msgSender() == ownerOf(tokenId), "you don't own this token"); require((_characterLevels[tokenId].Intelligence + levelUpSize) <= 10, "request levelup size is over max level"); uint32 oldLevel = _characterLevels[tokenId].Intelligence; _characterLevels[tokenId].Intelligence += levelUpSize; emit levelUp(tokenId, "Intelligence", oldLevel, _characterLevels[tokenId].Intelligence); } function _communicationLevelUp(uint256 tokenId) private { if(isLevelUp){ if(_characterLevels[tokenId].CommunicationSkills < 10){ uint32 oldLevel = _characterLevels[tokenId].CommunicationSkills; _characterLevels[tokenId].CommunicationSkills++; emit levelUp(tokenId, "CommunicationSkills", oldLevel, _characterLevels[tokenId].CommunicationSkills); } } } function energyLevelUp(uint256 tokenId) external { require(isLevelUp, "Levelup is not available yet"); require(_msgSender() == ownerOf(tokenId), "You don't own this token"); require(_characterLevels[tokenId].Energy < 10, "Already max level"); //30 days uint256 period = 2592000; uint256 levelUpCount = (block.timestamp - _transactionTimestamp[tokenId]) / period; if(levelUpCount > 0){ uint32 oldLevel = _characterLevels[tokenId].Energy; _characterLevels[tokenId].Energy += uint32(levelUpCount); if(_characterLevels[tokenId].Energy > 10){ _characterLevels[tokenId].Energy = 10; } emit levelUp(tokenId, "Energy", oldLevel, _characterLevels[tokenId].Energy); } } function creativityLevelUp(uint256 tokenId) external { require(_msgSender() == fanFictionContract, "Not specific contract"); if(isLevelUp){ if(_characterLevels[tokenId].Creativity < 10){ uint32 oldLevel = _characterLevels[tokenId].Creativity; _characterLevels[tokenId].Creativity++; emit levelUp(tokenId, "Creativity", oldLevel, _characterLevels[tokenId].Creativity); } } } function viewOwnershipPeriod(uint256 tokenId) external view returns (uint256) { //return ownership period by day(s) if(_transactionTimestamp[tokenId] == 0){ return 0; } else{ return (block.timestamp - _transactionTimestamp[tokenId]) / 86400; } } //CharacterSheet function setCharacterSheet(uint256 characterNo, string memory key, string memory value) external { bool isTokenOwner = false; uint256 lastTokenIndex = balanceOf(_msgSender()); uint256 startNo = ((characterNo-1) * 400) + 1; uint256 endNo = characterNo * 400; string memory oldValue; for(uint256 i=0; i<lastTokenIndex; i++){ uint256 tokenId = tokenOfOwnerByIndex(_msgSender(), i); if((startNo <= tokenId) && (tokenId <= endNo)){ isTokenOwner = true; } } require(isTokenOwner, "You don't own this character token"); oldValue = _characterSheet[characterNo][key]; _characterSheet[characterNo][key] = value; emit changeCharacterSheet(_msgSender(), characterNo, key, oldValue, value); } function viewCharacterSheet(uint256 characterNo, string memory key) public view returns(string memory) { return _characterSheet[characterNo][key]; } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; interface IHasSecondarySaleFees { function getFeeBps(uint256 id) external view returns (uint256[] memory); function getFeeRecipients(uint256 id) external view returns (address payable[] memory); } contract HasSecondarySaleFees is IERC165, IHasSecondarySaleFees { event ChangeCommonRoyalty( address payable[] royaltyAddresses, uint256[] royaltiesWithTwoDecimals ); event ChangeRoyalty( uint256 id, address payable[] royaltyAddresses, uint256[] royaltiesWithTwoDecimals ); struct RoyaltyInfo { bool isPresent; address payable[] royaltyAddresses; uint256[] royaltiesWithTwoDecimals; } mapping(bytes32 => RoyaltyInfo) royaltyInfoMap; mapping(uint256 => bytes32) tokenRoyaltyMap; address payable[] public commonRoyaltyAddresses; uint256[] public commonRoyaltiesWithTwoDecimals; constructor( address payable[] memory _commonRoyaltyAddresses, uint256[] memory _commonRoyaltiesWithTwoDecimals ) { _setCommonRoyalties(_commonRoyaltyAddresses, _commonRoyaltiesWithTwoDecimals); } function _setRoyaltiesOf( uint256 _tokenId, address payable[] memory _royaltyAddresses, uint256[] memory _royaltiesWithTwoDecimals ) internal { require(_royaltyAddresses.length == _royaltiesWithTwoDecimals.length, "input length must be same"); bytes32 key = 0x0; for (uint256 i = 0; i < _royaltyAddresses.length; i++) { require(_royaltyAddresses[i] != address(0), "Must not be zero-address"); key = keccak256(abi.encodePacked(key, _royaltyAddresses[i], _royaltiesWithTwoDecimals[i])); } tokenRoyaltyMap[_tokenId] = key; emit ChangeRoyalty(_tokenId, _royaltyAddresses, _royaltiesWithTwoDecimals); if (royaltyInfoMap[key].isPresent) { return; } royaltyInfoMap[key] = RoyaltyInfo( true, _royaltyAddresses, _royaltiesWithTwoDecimals ); } function _setCommonRoyalties( address payable[] memory _commonRoyaltyAddresses, uint256[] memory _commonRoyaltiesWithTwoDecimals ) internal { require(_commonRoyaltyAddresses.length == _commonRoyaltiesWithTwoDecimals.length, "input length must be same"); for (uint256 i = 0; i < _commonRoyaltyAddresses.length; i++) { require(_commonRoyaltyAddresses[i] != address(0), "Must not be zero-address"); } commonRoyaltyAddresses = _commonRoyaltyAddresses; commonRoyaltiesWithTwoDecimals = _commonRoyaltiesWithTwoDecimals; emit ChangeCommonRoyalty(_commonRoyaltyAddresses, _commonRoyaltiesWithTwoDecimals); } function getFeeRecipients(uint256 _tokenId) public view override returns (address payable[] memory) { RoyaltyInfo memory royaltyInfo = royaltyInfoMap[tokenRoyaltyMap[_tokenId]]; if (!royaltyInfo.isPresent) { return commonRoyaltyAddresses; } uint256 length = commonRoyaltyAddresses.length + royaltyInfo.royaltyAddresses.length; address payable[] memory recipients = new address payable[](length); for (uint256 i = 0; i < commonRoyaltyAddresses.length; i++) { recipients[i] = commonRoyaltyAddresses[i]; } for (uint256 i = 0; i < royaltyInfo.royaltyAddresses.length; i++) { recipients[i + commonRoyaltyAddresses.length] = royaltyInfo.royaltyAddresses[i]; } return recipients; } function getFeeBps(uint256 _tokenId) public view override returns (uint256[] memory) { RoyaltyInfo memory royaltyInfo = royaltyInfoMap[tokenRoyaltyMap[_tokenId]]; if (!royaltyInfo.isPresent) { return commonRoyaltiesWithTwoDecimals; } uint256 length = commonRoyaltiesWithTwoDecimals.length + royaltyInfo.royaltiesWithTwoDecimals.length; uint256[] memory fees = new uint256[](length); for (uint256 i = 0; i < commonRoyaltiesWithTwoDecimals.length; i++) { fees[i] = commonRoyaltiesWithTwoDecimals[i]; } for (uint256 i = 0; i < royaltyInfo.royaltiesWithTwoDecimals.length; i++) { fees[i + commonRoyaltyAddresses.length] = royaltyInfo.royaltiesWithTwoDecimals[i]; } return fees; } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) { return interfaceId == type(IHasSecondarySaleFees).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; abstract contract ContextMixin { function msgSender() internal view returns(address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden 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 || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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 (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 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.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.6.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; /** * @dev 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 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 the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @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); } // 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); }
0.02ETH LevelUpSize
function intelligenceLevelUp(uint256 tokenId, uint32 levelUpSize) external payable callerIsUser { uint256 Price = 20000000000000000 * uint256(levelUpSize); require(isLevelUp, "levelup is not available yet"); require(msg.value >= Price, "need to send more ETH"); require(_msgSender() == ownerOf(tokenId), "you don't own this token"); require((_characterLevels[tokenId].Intelligence + levelUpSize) <= 10, "request levelup size is over max level"); uint32 oldLevel = _characterLevels[tokenId].Intelligence; _characterLevels[tokenId].Intelligence += levelUpSize; emit levelUp(tokenId, "Intelligence", oldLevel, _characterLevels[tokenId].Intelligence); }
6,232,724
pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract KiiAToken is ERC20, ERC20Detailed, Ownable { //Token percentages uint256 private tokenSaleRatio = 50; uint256 private foundersRatio = 10; uint256 private marketingRatio = 40; uint256 private foundersplit = 20; //Constructor constructor( string memory _name, string memory _symbol, uint8 _decimals, address _founder1, address _founder2, address _founder3, address _founder4, address _founder5, address _marketing, address _publicsale, uint256 _initialSupply ) ERC20Detailed(_name, _symbol, _decimals) public { uint256 tempInitialSupply = _initialSupply * (10 ** uint256(_decimals)); uint256 publicSupply = tempInitialSupply.mul(tokenSaleRatio).div(100); uint256 marketingSupply = tempInitialSupply.mul(marketingRatio).div(100); uint256 tempfounderSupply = tempInitialSupply.mul(foundersRatio).div(100); uint256 founderSupply = tempfounderSupply.mul(foundersplit).div(100); _mint(_publicsale, publicSupply); _mint(_marketing, marketingSupply); _mint(_founder1, founderSupply); _mint(_founder2, founderSupply); _mint(_founder3, founderSupply); _mint(_founder4, founderSupply); _mint(_founder5, founderSupply); } } // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 // // 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. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- 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; } } contract KiiADefi{ string public name = "KiiA Token Farm"; address public onlyOwner; KiiAToken public kiiaToken; using SafeMath for uint256; using BokkyPooBahsDateTimeLibrary for uint; function _diffDays(uint fromTimestamp, uint toTimestamp) public pure returns (uint _days) { _days = BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, toTimestamp); } function _getTotalDays(uint _months) public view returns(uint){ uint fromday = now; uint today = fromday.addMonths(_months); uint pendindays = _diffDays(fromday,today); return (pendindays); } //Deposit structure to hold all the variables struct Deposits { uint deposit_id; address investorAddress; uint planid; uint plantype; uint month; uint interest; uint256 invested; uint256 totalBonusToReceive; uint256 principalPmt; uint256 dailyEarnings; uint nthDay; uint daysToClose; bool isUnlocked; bool withdrawn; } //PlanDetails structure struct PlanDetails { uint planid; uint month; uint interest; uint plantype; bool isActive; } //Events to capture deposit event event addDepositEvent( uint depositId, address investorAddress ); //Events to capture add plan event addPlanEvent( uint index, uint planid ); //Events to capture update/edit plan event updateorEditPlanEvent( uint planid ); event dummyEvent( address text1, bytes32 text2 ); event dummyEventint( uint text1, bool text2, uint text3 ); //Events to capture whitelist event event whiteListEvent( address owner, address investor ); //Event to capture calculate bonus event calculateBonusEvent( uint depositid, address investorAddress ); //Events to capture unlock event event addUnlockEvent( uint indexed _id, address _investorAddress, uint _planid ); //Events to capture lock event event addlockEvent( uint indexed _id, address _investorAddress, uint _planid ); //Events to capture Withdraw event event addWithdrawEvent( uint indexed _id, address _investorAddress, uint _planid ); uint public depositCounter; uint public planCounter; Deposits[] public allDeposits; PlanDetails[] public allPlanDetails; //to view deposit information mapping(address=>Deposits[]) public depositDetails; mapping(address=>mapping(uint=>Deposits[])) public viewDeposit; mapping(address => bool) public whitelistAddresses; address[] public whiteListed; address[] public stakers; mapping(address => bool) public hasStaked; //address -> plan -> staking or not mapping(address => mapping(uint => bool)) public isStaking; //plan active state mapping(uint =>bool) public isPlanActive; constructor(KiiAToken _kiiaToken, address _owneraddr) public payable { kiiaToken = _kiiaToken; onlyOwner = _owneraddr; } function addEth() public payable { //function to accept ether } //Function to whitelist address function whiteListIt(address _beneficiary) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); require(whitelistAddresses[_beneficiary]==false, "Already whitelisted"); whitelistAddresses[_beneficiary] = true; whiteListed.push(_beneficiary); emit whiteListEvent(msg.sender,_beneficiary); return 0; } //Function to whitelist address in bulk fashion function bulkwhiteListIt(address[] memory _beneficiary) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); uint tot = _beneficiary.length; if(tot<=255){ for(uint i=0;i<tot; i++){ if(!whitelistAddresses[_beneficiary[i]]){ whitelistAddresses[_beneficiary[i]] = true; whiteListed.push(_beneficiary[i]); emit whiteListEvent(msg.sender,_beneficiary[i]); } } return 0; } } //Function to bulk remove from bulkremoveFromwhiteListIt function bulkremoveFromwhiteListIt(address[] memory _beneficiary) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); uint tot = _beneficiary.length; if(tot<=255){ for(uint i=0;i<tot; i++){ if(!whitelistAddresses[_beneficiary[i]]){ whitelistAddresses[_beneficiary[i]] = false; whiteListed.push(_beneficiary[i]); emit whiteListEvent(msg.sender,_beneficiary[i]); } } return 0; } } //remove from whiteList function removefromWhiteList(address _beneficiary) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); require(whitelistAddresses[_beneficiary]==true, "Already in graylist"); whitelistAddresses[_beneficiary] = false; emit whiteListEvent(msg.sender,_beneficiary); return 0; } //Getter Function for getplan by id function getPlanById(uint _planid) public view returns(uint plan_id,uint month,uint interest,uint plantype,bool isActive){ uint tot = allPlanDetails.length; for(uint i=0;i<tot;i++){ if(allPlanDetails[i].planid==_planid){ return(allPlanDetails[i].planid,allPlanDetails[i].month,allPlanDetails[i].interest,allPlanDetails[i].plantype,allPlanDetails[i].isActive); } } } //Getter Function for getplan by id function getPlanDetails(uint _planid) internal view returns(uint month,uint interest,uint plantype){ uint tot = allPlanDetails.length; for(uint i=0;i<tot;i++){ if(allPlanDetails[i].planid==_planid){ return(allPlanDetails[i].month,allPlanDetails[i].interest,allPlanDetails[i].plantype); } } } //this function is to avoid stack too deep error function _deposits(uint _month, uint _amount, uint256 _interest) internal view returns (uint _nthdayv2,uint _pendingDaysv2,uint256 _totalBonusToReceivev2,uint256 _dailyEarningsv2,uint _principalPmtDailyv2) { uint256 _pendingDaysv1 = _getTotalDays(_month); uint256 _interesttoDivide = _interest.mul(1000000).div(100) ; uint256 _totalBonusToReceivev1 = _amount.mul(_interesttoDivide).div(1000000); uint _nthdayv1 = 0; uint _principalPmtDaily = 0; uint _dailyEarningsv1 = 0; return (_nthdayv1,_pendingDaysv1,_totalBonusToReceivev1,_dailyEarningsv1,_principalPmtDaily); } function depositTokens(uint _plan,uint256 _plandate, uint _amount) public{ // check if user is whitelisted require(whitelistAddresses[msg.sender]==true,"Only whitelisted user is allowed to deposit tokens"); require(_amount > 0, "amount cannot be 0"); require(isPlanActive[_plan]==true,"Plan is not active"); // To check if plan is active (uint _month,uint _interest,uint _plantype) = getPlanDetails(_plan); require(_interest > 0, "interest rate cannot be 0"); require(_month > 0,"_months cannot be 0"); // Trasnfer kiiA tokens to this contract for staking kiiaToken.transferFrom(msg.sender, address(this), _amount); //scope to remove the error Stack too deep (uint _nthday,uint _daystoclose,uint _totalBonusToReceive,uint _dailyEarnings,uint _principalPmtDaily) = _deposits(_month,_amount,_interest); uint _localid = allDeposits.length++; //deposit token in defi allDeposits[allDeposits.length-1] = Deposits(_plandate, msg.sender, _plan, _plantype, _month, _interest, _amount, _totalBonusToReceive, _principalPmtDaily, _dailyEarnings, _nthday, _daystoclose, false, false ); //Add Deposit details depositDetails[msg.sender].push(allDeposits[allDeposits.length-1]); //is Staking in this plan isStaking[msg.sender][_plandate] = true; // Add user to stakers array *only* if they haven't staked already if(!hasStaked[msg.sender]) { stakers.push(msg.sender); } hasStaked[msg.sender] = true; emit addDepositEvent(_localid, msg.sender); } //Setter function for plan function registerPlan(uint _planid, uint _month,uint _interest,uint _plantype) public returns(uint){ require(msg.sender == onlyOwner, "caller must be the owner"); require(_planid > 0, "Plan Id cannot be 0"); require(_month > 0, "Month cannot be 0"); require(_interest > 0, "Interest cannot be 0"); require(_plantype >= 0, "Plantype can be either 0 or 1"); require(_plantype <= 1, "Plantype can be either 0 or 1"); require(isPlanActive[_planid]==false,"Plan already exists in active status"); planCounter = planCounter + 1; uint _localid = allPlanDetails.length++; allPlanDetails[allPlanDetails.length-1] = PlanDetails(_planid, _month, _interest, _plantype, true ); isPlanActive[_planid] = true; emit addPlanEvent(_localid,_planid); return 0; } //Setter function for plan function updatePlan(uint _planid, uint _month,uint _interest,uint _plantype) public returns(uint){ require(msg.sender == onlyOwner, "caller must be the owner"); require(_planid > 0, "Plan Id cannot be 0"); require(_month > 0, "Month cannot be 0"); require(_interest > 0, "Interest cannot be 0"); uint tot = allPlanDetails.length; for(uint i=0;i<tot;i++){ if(allPlanDetails[i].planid==_planid){ allPlanDetails[i].month = _month; allPlanDetails[i].interest = _interest; allPlanDetails[i].plantype = _plantype; } } emit updateorEditPlanEvent(_planid); return 0; } //Deactivate plan function deactivatePlan(uint _planid) public returns(uint){ require(msg.sender == onlyOwner, "caller must be the owner"); require(isPlanActive[_planid]==true, "Plan already deactivated"); isPlanActive[_planid]= false; emit updateorEditPlanEvent(_planid); return 0; } //Reactivate plan function reactivatePlan(uint _planid) public returns(uint){ require(msg.sender == onlyOwner, "caller must be the owner"); require(isPlanActive[_planid]==false, "Plan already activated"); isPlanActive[_planid]= true; emit updateorEditPlanEvent(_planid); return 0; } //To calculate bonus - this function should be called once per day by owner function calcBonus() public returns(uint){ require(msg.sender == onlyOwner, "caller must be the owner"); uint totDep = allDeposits.length; for(uint i=0; i<totDep;i++){ uint _plantype = allDeposits[i].plantype; uint _nthDay = allDeposits[i].nthDay; uint _invested = allDeposits[i].invested; uint _daysToClose= allDeposits[i].daysToClose; uint _principalPmt = _invested.div(_daysToClose); //check if already withdrawn, if yes, then dont calculate bool _withdrawn = allDeposits[i].withdrawn; emit dummyEventint(_plantype,_withdrawn,0); if(_plantype==0){ if(_nthDay<_daysToClose){ allDeposits[i].nthDay = _nthDay.add(1); allDeposits[i].principalPmt = allDeposits[i].principalPmt + _principalPmt; //emit event emit calculateBonusEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress); } } if(_plantype==1){ if(_nthDay<_daysToClose){ allDeposits[i].nthDay = _nthDay.add(1); allDeposits[i].principalPmt = allDeposits[i].principalPmt + _principalPmt; //emit event emit calculateBonusEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress); } } } } //Get deposit by address uint[] depNewArray; function getDepositidByAddress(address _beneficiary) public returns(uint[] memory){ uint tot = allDeposits.length; uint[] memory tmparray; depNewArray = tmparray; for(uint i =0; i< tot; i++){ if(allDeposits[i].investorAddress==_beneficiary){ depNewArray.push(allDeposits[i].deposit_id); } } return depNewArray; } function getDepositByAddress(address _beneficiary,uint _deposit_id) public view returns(uint256,uint,uint,uint,uint,uint256,uint256,uint,uint,uint,bool){ uint tot = allDeposits.length; for(uint i=0;i<tot;i++){ if(_beneficiary==allDeposits[i].investorAddress){ if(allDeposits[i].deposit_id==_deposit_id){ return(allDeposits[i].invested, allDeposits[i].planid, allDeposits[i].plantype, allDeposits[i].month, allDeposits[i].interest, allDeposits[i].totalBonusToReceive, allDeposits[i].dailyEarnings, allDeposits[i].principalPmt, allDeposits[i].daysToClose, allDeposits[i].nthDay, allDeposits[i].isUnlocked ); } } } } // Unlock address function setLock(address _beneficiary,uint _deposit_id) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); // set lock uint totDep = allDeposits.length; for(uint i=0;i<totDep; i++){ if(allDeposits[i].investorAddress==_beneficiary){ if (allDeposits[i].deposit_id==_deposit_id){ allDeposits[i].isUnlocked = false; emit addlockEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress,allDeposits[i].planid); } } } return 0; } // Unlock address function unlock(address _beneficiary,uint _deposit_id) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); // Unlock uint totDep = allDeposits.length; for(uint i=0;i<totDep; i++){ if(allDeposits[i].investorAddress==_beneficiary){ if (allDeposits[i].deposit_id==_deposit_id){ allDeposits[i].isUnlocked = true; emit addUnlockEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress,allDeposits[i].planid); } } } return 0; } // Bulk Unlock address function bulkunlock(address[] memory _beneficiary, uint256[] memory _deposit_id) public returns(uint) { // Only owner can call this function require(msg.sender == onlyOwner, "caller must be the owner"); require(_beneficiary.length == _deposit_id.length,"Array length must be equal"); // Unlock uint totDep = allDeposits.length; for (uint j = 0; j < _beneficiary.length; j++) { for(uint i=0;i<totDep; i++){ if(allDeposits[i].investorAddress==_beneficiary[j]){ if (allDeposits[i].deposit_id==_deposit_id[j]){ allDeposits[i].isUnlocked = true; } } } } return 0; } // Bring staker list Getter function function stakerlist() public view returns(address[] memory){ return stakers; } // Bring whitelisted addresss list address[] whiteArray; function whiteListedAddress() public returns(address[] memory){ uint tot = whiteListed.length; address[] memory tmparray; whiteArray = tmparray; for(uint i=0;i<tot; i++){ whiteArray.push(whiteListed[i]); emit dummyEvent(whiteListed[i],"testing"); } return whiteArray; } // Bring bloacklisted addresss list address[] blackArray; function blackListedAddress() public returns(address[] memory){ uint tot = whiteListed.length; address[] memory tmparray; blackArray = tmparray; for(uint i=0;i<tot; i++){ if(whitelistAddresses[whiteListed[i]]==false){ blackArray.push(whiteListed[i]); } } return blackArray; } // Unstaking Tokens (Withdraw) function withDrawTokens(uint _deposit_id, uint _plantype) public returns(uint) { uint totDep = allDeposits.length; for(uint i=0;i<totDep; i++){ if(allDeposits[i].investorAddress==msg.sender){ if (allDeposits[i].deposit_id==_deposit_id){ require(allDeposits[i].invested > 0, "Staking balance cannot be 0"); require(allDeposits[i].withdrawn==false, "Plan is already withdrawn by user"); require(allDeposits[i].isUnlocked==true, "User account must be unlocked by owner to withdraw"); require(isStaking[msg.sender][_deposit_id]==true,"User is not staking any amount in this plan"); uint balance = allDeposits[i].invested; //Regular Plan withdrawal if(_plantype==0){ uint _principalPmt = allDeposits[i].principalPmt; uint _toTransfer1 = balance.sub(_principalPmt); // Transfer back KiiA tokens to this address kiiaToken.transfer(msg.sender, _toTransfer1); allDeposits[i].principalPmt = _principalPmt.add(_toTransfer1); allDeposits[i].totalBonusToReceive = 0; allDeposits[i].withdrawn = true; isStaking[msg.sender][_deposit_id]=false; emit addWithdrawEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress,allDeposits[i].planid); return 0; } //Fixed Plan withdrawal if(_plantype==1){ uint nthDay = allDeposits[i].nthDay; uint dailyEarnings = allDeposits[i].dailyEarnings; uint256 _interestAccumulated = nthDay.mul(dailyEarnings); uint256 _toTransfer2 = balance.add(_interestAccumulated); // Transfer back KiiA tokens to this address kiiaToken.transfer(msg.sender, _toTransfer2); allDeposits[i].totalBonusToReceive = 0; allDeposits[i].withdrawn = true; isStaking[msg.sender][_deposit_id]=false; emit addWithdrawEvent(allDeposits[i].deposit_id,allDeposits[i].investorAddress,allDeposits[i].planid); return 0; } } } } } }
Sets `amount` as the allowance of `spender` over the `owner`s tokens. This is internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. Emits an {Approval} event. Requirements: - `owner` cannot be the zero address. - `spender` cannot be the zero address./
function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
454,293
./full_match/1/0x8e0CFA182425Ae40774A4a9a25AF25bfe5B3d511/sources/contracts/abstracts/PALMManagerStorage.sol
get list of operators return operators array of address representing operators
function getOperators() external view override returns (address[] memory) { return _operators.values(); }
16,568,148
pragma solidity >=0.5.17 <0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/utils/math/Math.sol'; import '../BaseStrategy.sol'; import './../../enums/ProtocolEnum.sol'; import './../../external/harvest/HarvestVault.sol'; import './../../external/harvest/HarvestStakePool.sol'; import './../../external/uniswap/IUniswapV2.sol'; //import './../../external/curve/ICurveFi.sol'; import './../../external/sushi/Sushi.sol'; import './../../dex/uniswap/SwapFarm2UsdtInUniswapV2.sol'; contract HarvestUSDTStrategy is BaseStrategy, SwapFarm2UsdtInUniswapV2{ using SafeERC20 for IERC20; using SafeMath for uint256; //待投的币种 IERC20 public constant baseToken = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); //待投池地址 address public fVault = address(0x053c80eA73Dc6941F518a68E2FC52Ac45BDE7c9C); //质押池地址 address public fPool = address(0x6ac4a7AB91E6fD098E13B7d347c6d4d1494994a2); //Farm Token address public rewardToken = address(0xa0246c9032bC3A600820415aE600c6388619A14D); //uni v2 address address constant uniV2Address = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //WETH address constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //curve pool address address constant curvePool = address(0x80466c64868E1ab14a1Ddf27A676C3fcBE638Fe5); //sushi address address constant sushiAddress = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //上次doHardwork按币本位计价的资产总值 uint256 internal lastTotalAssets = 0; //当日赎回 uint256 internal dailyWithdrawAmount = 0; constructor(address _vault){ address[] memory tokens = new address[](1); tokens[0] = address(baseToken); initialize("HarvestUSDTStrategy", uint16(ProtocolEnum.Harvest), _vault, tokens); } /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external override view returns (uint256[] memory,uint256[] memory){ uint256[] memory tokenAmountArr = new uint256[](1); tokenAmountArr[0] = amountUnderlying; return (tokenAmountArr, tokenAmountArr); } function withdrawAllToVault() external onlyVault override { uint stakingAmount = HarvestStakePool(fPool).balanceOf(address(this)); if (stakingAmount > 0){ _claimRewards(); HarvestStakePool(fPool).withdraw(stakingAmount); HarvestVault(fVault).withdraw(stakingAmount); } uint256 withdrawAmount = baseToken.balanceOf(address(this)); if (withdrawAmount > 0){ baseToken.safeTransfer(address(vault),withdrawAmount); dailyWithdrawAmount += withdrawAmount; } } /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external onlyVault override { uint256 balance = baseToken.balanceOf(address(this)); if (balance >= amountUnderlying){ baseToken.safeTransfer(address(vault),amountUnderlying); } else { uint256 missAmount = amountUnderlying - balance; uint256 shares = missAmount.mul(10 ** HarvestVault(fVault).decimals()).div(HarvestVault(fVault).getPricePerFullShare()); if (shares > 0){ uint256 stakeAmount = HarvestStakePool(fPool).balanceOf(address(this)); shares = Math.min(shares,stakeAmount); HarvestStakePool(fPool).withdraw(shares); HarvestVault(fVault).withdraw(shares); uint256 withdrawAmount = baseToken.balanceOf(address(this)); baseToken.safeTransfer(address(vault),withdrawAmount); dailyWithdrawAmount += withdrawAmount; } } } /** * 第三方池的净值 **/ function getPricePerFullShare() external override view returns (uint256) { return HarvestVault(fVault).getPricePerFullShare(); } /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external override view returns (uint256) { uint stakingAmount = HarvestStakePool(fPool).balanceOf(address(this)); uint baseTokenBalance = baseToken.balanceOf(address(this)); uint prs = HarvestVault(fVault).getPricePerFullShare(); return stakingAmount .mul(prs) .div(10 ** IERC20Metadata(fVault).decimals()) .add(baseTokenBalance); } /** * 查看策略投资池子的总数量(priced in want) **/ function getInvestVaultAssets() external override view returns (uint256) { return HarvestVault(fVault).getPricePerFullShare() .mul(IERC20(fVault).totalSupply()) .div(10 ** IERC20Metadata(fVault).decimals()); } /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWorkInner() internal override { uint256 rewards = 0; if (HarvestStakePool(fPool).balanceOf(address(this)) > 0){ rewards = _claimRewards(); } _updateApy(rewards); _invest(); lastTotalAssets = HarvestStakePool(fPool).balanceOf(address(this)) .mul(HarvestVault(fVault).getPricePerFullShare()) .div(10 ** IERC20Metadata(fVault).decimals()); lastDoHardworkTimestamp = block.timestamp; dailyWithdrawAmount = 0; } function _claimRewards() internal returns (uint256) { HarvestStakePool(fPool).getReward(); uint256 amount = IERC20(rewardToken).balanceOf(address(this)); if (amount == 0){ return 0; } //兑换成investToken //TODO::当Farm数量大于50时先从uniV2换成ETH然后再从curve换 uint256 balanceBeforeSwap = IERC20(baseToken).balanceOf(address(this)); if(amount>10**15){ swapFarm2UsdtInUniswapV2(amount,0,1800); uint256 balanceAfterSwap = IERC20(baseToken).balanceOf(address(this)); return balanceAfterSwap - balanceBeforeSwap; } return 0; } function _updateApy(uint256 _rewards) internal { // 第一次投资时lastTotalAssets为0,不用计算apy if (lastTotalAssets > 0 && lastDoHardworkTimestamp > 0){ uint256 totalAssets = HarvestStakePool(fPool).balanceOf(address(this)) .mul(HarvestVault(fVault).getPricePerFullShare()) .div(10 ** IERC20Metadata(fVault).decimals()); int assetsDelta = int(totalAssets) + int(dailyWithdrawAmount) + int(_rewards) - int(lastTotalAssets); calculateProfitRate(lastTotalAssets,assetsDelta); } } function _invest() internal { uint256 balance = baseToken.balanceOf(address(this)); if (balance > 0) { baseToken.safeApprove(fVault, 0); baseToken.safeApprove(fVault, balance); HarvestVault(fVault).deposit(balance); //stake uint256 lpAmount = IERC20(fVault).balanceOf(address(this)); IERC20(fVault).safeApprove(fPool, 0); IERC20(fVault).safeApprove(fPool, lpAmount); HarvestStakePool(fPool).stake(lpAmount); lastTotalAssets = HarvestStakePool(fPool).balanceOf(address(this)).mul(HarvestVault(fVault).getPricePerFullShare()).div(10 ** IERC20Metadata(fVault).decimals()); } } /** * 策略迁移 **/ function migrate(address _newStrategy) external override { } } // 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 "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute. return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } pragma solidity >=0.5.17 <0.8.4; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import './IStrategy.sol'; import '../vault/IVault.sol'; abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public name; uint16 public protocol; IVault public vault; address[] public tokens; uint256 internal constant BASIS_PRECISION = 1e18; //基础收益率,初始化时为1000000 uint256 internal basisProfitRate; //有效时长,用于计算apy,若策略没有资金时,不算在有效时长内 uint256 internal effectiveTime; //上次doHardwork的时间 uint256 public lastDoHardworkTimestamp = 0; function getTokens() external view returns (address[] memory) { return tokens; } function setApy(uint256 nextBasisProfitRate, uint256 nextEffectiveTime) external onlyGovernance { basisProfitRate = nextBasisProfitRate; effectiveTime = nextEffectiveTime; vault.strategyUpdate(this.investedUnderlyingBalance(),apy()); } //10000表示100%,当前apy的算法是一直累计过去的变化,有待改进 function apy() public view returns (uint256) { if (basisProfitRate <= BASIS_PRECISION) { return 0; } if (effectiveTime == 0) { return 0; } return (31536000 * (basisProfitRate - BASIS_PRECISION) * 10000) / (BASIS_PRECISION * effectiveTime); } modifier onlyGovernance() { require(msg.sender == vault.governance(), '!only governance'); _; } modifier onlyVault() { require(msg.sender == address(vault), '!only vault'); _; } function initialize( string memory _name, uint16 _protocol, address _vault, address[] memory _tokens ) internal { name = _name; protocol = _protocol; vault = IVault(_vault); tokens = _tokens; effectiveTime = 0; basisProfitRate = BASIS_PRECISION; } /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external view virtual returns (uint256[] memory, uint256[] memory); function withdrawAllToVault() external virtual; /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external virtual; /** * 第三方池的净值 **/ function getPricePerFullShare() external view virtual returns (uint256); /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external view virtual returns (uint256); /** * 查看策略投资池子的总资产 **/ function getInvestVaultAssets() external view virtual returns (uint256); /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWork() external onlyGovernance{ doHardWorkInner(); vault.strategyUpdate(this.investedUnderlyingBalance(),apy()); lastDoHardworkTimestamp = block.timestamp; } function doHardWorkInner() internal virtual; function calculateProfitRate(uint256 previousInvestedAssets,int assetsDelta) internal { if (assetsDelta < 0)return; uint256 secondDelta = block.timestamp - lastDoHardworkTimestamp; if (secondDelta > 10 && assetsDelta != 0){ effectiveTime += secondDelta; uint256 dailyProfitRate = uint256(assetsDelta>0?assetsDelta:-assetsDelta) * BASIS_PRECISION / previousInvestedAssets; if (assetsDelta > 0){ basisProfitRate = (BASIS_PRECISION + dailyProfitRate) * basisProfitRate / BASIS_PRECISION; } else { basisProfitRate = (BASIS_PRECISION - dailyProfitRate) * basisProfitRate / BASIS_PRECISION; } } } /** * 策略迁移 **/ function migrate(address _newStrategy) external virtual; } pragma solidity ^0.8.0; enum ProtocolEnum { Yearn, Harvest, Dodo, Curve, Pickle, Liquity, TrueFi } pragma solidity ^0.8.0; interface HarvestVault { function deposit(uint256) external; function withdraw(uint256) external; function withdrawAll() external; function doHardWork() external; function underlyingBalanceWithInvestment() view external returns (uint256); function getPricePerFullShare() external view returns (uint256); // function pricePerShare() external view returns (uint256); function decimals() external view returns (uint256); function balance() external view returns (uint256); } pragma solidity ^0.8.0; interface HarvestStakePool { function balanceOf(address account) external view returns (uint256); function getReward() external; function stake(uint256 amount) external; function rewardPerToken() external view returns (uint256); function withdraw(uint256 amount) external; function exit() external; } pragma solidity =0.8.0; interface IUniswapV2 { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } pragma solidity =0.8.0; interface Sushi { function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } pragma solidity >=0.5.17 <=0.8.0; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './SwapInUniswapV2.sol'; interface ISwapFarm2UsdtInUniswapV2 { function swapFarm2UsdtInUniswapV2( uint256 _amount, uint256 _minReturn, uint256 _timeout ) external returns (uint256[] memory); } contract SwapFarm2UsdtInUniswapV2 is SwapInUniswapV2 { address private FARM_ADDRESS = address(0xa0246c9032bC3A600820415aE600c6388619A14D); address private WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); address private USDT_ADDRESS = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); /** * farm => usdt */ function swapFarm2UsdtInUniswapV2( uint256 _amount, uint256 _minReturn, uint256 _timeout ) internal returns (uint256[] memory) { require(_amount > 0, '_amount>0'); require(_minReturn >= 0, '_minReturn>=0'); address[] memory _path = new address[](3); _path[0] = FARM_ADDRESS; _path[1] = WETH_ADDRESS; _path[2] = USDT_ADDRESS; return this.swap(FARM_ADDRESS, _amount, _minReturn, _path, address(this), _timeout); } } // 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; import "../IERC20.sol"; /** * @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); } pragma solidity >=0.5.17 <0.8.4; interface IStrategy { // function underlying() external view returns (address); function vault() external view returns (address); function name() external pure returns (string calldata); /** * 第三方池需要的代币地址列表 **/ function getTokens() external view returns (address[] memory); function apy() external view returns (uint256); /** * 计算基础币与其它币种的数量关系 * 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量 **/ function calculate(uint256 amountUnderlying) external view returns (uint256[] memory); function withdrawAllToVault() external; /** * amountUnderlying:需要的基础代币数量 **/ function withdrawToVault(uint256 amountUnderlying) external; /** * 第三方池的净值 **/ function getPricePerFullShare() external view returns (uint256); /** * 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算 **/ function investedUnderlyingBalance() external view returns (uint256); /** * 查看策略投资池子的总数量(priced in want) **/ function getInvestVaultAssets() external view returns (uint256); /** * 针对策略的作业: * 1.提矿 & 换币(矿币换成策略所需的稳定币?) * 2.计算apy * 3.投资 **/ function doHardWork() external; /** * 策略迁移 **/ function migrate(address _newStrategy) external virtual; } pragma solidity >=0.5.17 <0.8.4; interface IVault { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function governance() external view returns (address); /** * USDT地址 **/ function underlying() external view returns (address); /** * Vault净值 **/ function getPricePerFullShare() external view returns (uint256); /** * 总锁仓量 **/ function tlv() external view returns (uint256); function deposit(uint256 amountWei) external; function withdraw(uint256 numberOfShares) external; function addStrategy(address _strategy) external; function removeStrategy(address _strategy) external; function strategyUpdate(uint256 newTotalAssets, uint256 apy) external; /** * 策略列表 **/ function strategies() external view returns (address[] memory); /** * 分两种情况: * 不足一周时,维持Vault中USDT数量占总资金的5%,多余的投入到apy高的策略中,不足时从低apy策略中赎回份额来补够 * 到达一周时,统计各策略apy,按照资金配比规则进行调仓(统计各策略需要的稳定币数量,在Vault中汇总后再分配) **/ function doHardWork() external; struct StrategyState { uint256 totalAssets; //当前总资产 uint256 totalDebt; //投入未返还成本 } function strategyState(address strategyAddress) external view returns (StrategyState memory); /** * 获取总成本 */ function totalCapital() external view returns (uint256); /** * 获取总估值 */ function totalAssets() external view returns (uint256); /** * 获取策略投资总额 */ function strategyTotalAssetsValue() external view returns (uint256); } pragma solidity >=0.5.17 <=0.8.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './../../external/uniswap/IUniswapV2.sol'; contract SwapInUniswapV2 { using SafeERC20 for IERC20; address private uniswapV2Address = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); function swap( address fromToken, uint256 _amount, uint256 _minReturn, address[] memory _path, address recipient, uint256 _timeout ) public returns (uint256[] memory) { require(_amount > 0, '_amount>0'); require(_minReturn >= 0, '_minReturn>=0'); IERC20(fromToken).safeApprove(uniswapV2Address, 0); IERC20(fromToken).safeApprove(uniswapV2Address, _amount); try IUniswapV2(uniswapV2Address).swapExactTokensForTokens( _amount, _minReturn, _path, recipient, block.timestamp + _timeout ) returns (uint256[] memory amounts){ return amounts; }catch{ } uint256[] memory amounts = new uint256[](2); amounts[0] = 0; amounts[1] = 0; return amounts; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The 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 {} } // 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; } }
计算基础币与其它币种的数量关系 如该池是CrvEURS池,underlying是USDT数量,返回的则是 EURS、SEUR的数量/ amountUnderlying:需要的基础代币数量/ 第三方池的净值/ 已经投资的underlying数量,策略实际投入的是不同的稳定币,这里涉及待投稳定币与underlying之间的换算/ 查看策略投资池子的总资产/ 针对策略的作业: 1.提矿 & 换币(矿币换成策略所需的稳定币?) 2.计算apy 3.投资/
function calculate(uint256 amountUnderlying) external view virtual returns (uint256[] memory, uint256[] memory); function withdrawAllToVault() external virtual; function withdrawToVault(uint256 amountUnderlying) external virtual; function getPricePerFullShare() external view virtual returns (uint256); function investedUnderlyingBalance() external view virtual returns (uint256); function getInvestVaultAssets() external view virtual returns (uint256); function doHardWork() external onlyGovernance{ doHardWorkInner(); vault.strategyUpdate(this.investedUnderlyingBalance(),apy()); lastDoHardworkTimestamp = block.timestamp; }
6,894,696
./full_match/3/0xd5E75b109Cd1A91406Bdc79f6aa2B367a10e4847/sources/contracts/ComposableTopDown.sol
convert up to 32 bytes of _data to uint256, owner nft tokenId passed as uint in bytes a check for looped ownership chain
function onERC721Received( address _from, uint256 _childTokenId, bytes calldata _data ) external returns (bytes4) { require( _data.length > 0, "CTD: onERC721Received(3) _data must contain the uint256 tokenId to transfer the child token to" ); uint256 tokenId = _parseTokenId(_data); receiveChild(_from, tokenId, msg.sender, _childTokenId); require( IERC721(msg.sender).ownerOf(_childTokenId) != address(0), "CTD: onERC721Received(3) child token not owned" ); rootOwnerOf(tokenId); return ERC721_RECEIVED_OLD; }
8,124,902
pragma solidity ^0.4.24; contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); event Voted(uint256 _pID,uint256 _rID, bool _voted,uint256 _keys); } contract FoMo3Dlong is F3Devents { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address private com = 0x0787c7510b21305eea4c267fafd46ab85bdec67e; // community distribution address address private admin = msg.sender; bool RoundVoting = false; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xE77976045DD7D4BF446f048892526924CE94B16E); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "XMG Long Official"; string constant public symbol = "XMG"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => uint256) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // VOTING DATA //**************** mapping(uint256 => mapping(uint256 => bool)) VotePidRid_; // plyId => Rid => voted mapping(uint256 => F3Ddatasets.votingData) roundVotingData; //**************** // TEAM FEE DATA //**************** F3Ddatasets.TeamFee public fees_; // (team => fees) fee distribution by team F3Ddatasets.PotSplit public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_ = F3Ddatasets.TeamFee(60,0); //15% to pot, 10% to aff, 15% to com // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_ = F3Ddatasets.PotSplit(50,0); //48% to winner, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } modifier checkVoting(uint256 _pID,uint256 _rID){ require(VotePidRid_[_pID][_rID] != true,"You have already voted"); _; } modifier canVoting(){ require(RoundVoting == true,"The voting has not started yet"); _; } modifier isPlayer(uint256 _pID, uint256 _rID){ require(plyrRnds_[_pID][_rID].keys > 0, "Please buy the key and vote again."); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // buy core buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // buy core buyCore(_pID, _affID, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // reload core reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // reload core reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_.gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID], //9 rndTmEth_[_rID], //10 rndTmEth_[_rID], //11 rndTmEth_[_rID], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _eventData_); if(round_[_rID].pot > 10000000000000000000000 && RoundVoting == false){ RoundVoting = true; roundVotingData[_rID].VotingEndTime = _now.add(rndMax_); } if(_now > roundVotingData[_rID].VotingEndTime && RoundVoting == true){ uint256 _agree = roundVotingData[_rID].agress; uint256 _oppose = roundVotingData[_rID].oppose; if((_agree.mul(100)).div((_agree+_oppose)) > 67){ round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _eventData_); if(round_[_rID].pot > 10000000000000000000000 && RoundVoting == false){ RoundVoting = true; roundVotingData[_rID].VotingEndTime = _now.add(rndMax_); } if(_now > roundVotingData[_rID].VotingEndTime && RoundVoting == true){ uint256 _agree = roundVotingData[_rID].agress; uint256 _oppose = roundVotingData[_rID].oppose; if((_agree.mul(100)).div((_agree+_oppose)) > 67){ round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = 2500000000000000000; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot round_[_rID].pot = (round_[_rID].pot).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = 2500000000000000000; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot round_[_rID].pot = (round_[_rID].pot).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = 2500000000000000000; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot round_[_rID].pot = (round_[_rID].pot).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID] = _eth.add(rndTmEth_[_rID]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_.gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards com.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; RoundVoting == false; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 15% out to community rewards uint256 _com = (_eth / 10).add(_eth / 20); // distribute share to affiliate 10% uint256 _aff = (_eth / 10); // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com.add(_aff); } com.transfer(_com); return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_.gen)) / 100; // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) _eth = _eth.sub(((_eth.mul(29)) / 100).add((_eth.mul(fees_.p3d)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * 投票 */ function voting(uint256 _pID, uint256 _rID,bool _vote,uint256 _keys) canVoting checkVoting(_pID,_rID) internal { if(_vote){ roundVotingData[_rID].agress.add(_keys); }else{ roundVotingData[_rID].oppose.add(_keys); } emit Voted( _pID, _rID, _vote, _keys); } function votingByXid(uint256 _pID,bool _Vote) isPlayer( _pID, _rID) external { uint256 _rID = rID_; uint256 _keys = plyrRnds_[_pID][_rID].keys; voting( _pID, _rID, _Vote, _keys); } // function votingBymy(bool _vote)public{ // RoundVoting = _vote; // } } library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } struct votingData{ uint256 VotingEndTime; // Voting end time uint256 agress; uint256 oppose; } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); }
distributes eth based on fees to gen and pot/ calculate gen share update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) calculate pot distribute gen share (thats what updateMasks() does) and adjust balances for dust. add eth to pot set up event data
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_.gen)) / 100; _eth = _eth.sub(((_eth.mul(29)) / 100).add((_eth.mul(fees_.p3d)) / 100)); uint256 _pot = _eth.sub(_gen); uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); }
1,604,636
pragma solidity 0.4.24; 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); } 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); } 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; } } 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 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]; } } 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); } } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract 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; } } contract ZolToken is StandardToken, Ownable, BurnableToken{ uint256 public totalSupply; string public name; string public symbol; uint32 public decimals; /** * @dev assign totalSupply to account creating this contract */ constructor() public { symbol = "ZOL"; name = "ZloopToken"; decimals = 6; totalSupply = 5000000000000; owner = msg.sender; balances[msg.sender] = totalSupply; emit Transfer(0x0, msg.sender, totalSupply); }}
Burns a specific amount of tokens. _value The amount of token to be burned./
function burn(uint256 _value) public { _burn(msg.sender, _value); }
7,375,207
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/ITiny721.sol"; /* It saves bytecode to revert on custom errors instead of using require statements. We are just declaring these errors for reverting with upon various conditions later in this contract. */ error CannotConfigureEmptyCriteria(); error CannotConfigureWithoutOutputItem(); error CannotConfigureWithoutPaymentToken(); error CannotRedeemForZeroItems(); error CannotRedeemCriteriaLengthMismatch(); error CannotRedeemItemAlreadyRedeemed(); error CannotRedeemUnownedItem(); error SweepingTransferFailed(); /** @title A contract for minting ERC-721 items given an ERC-20 token burn and ownership of some prerequisite ERC-721 items. @author 0xthrpw @author Tim Clancy This contract allows for the configuration of multiple redemption rounds. Each redemption round is configured with a set of ERC-721 item collection addresses in the `redemptionCriteria` mapping that any prospective redeemers must hold. Each redemption round is also configured with a redemption configuration per the `redemptionConfigs` mapping. This configuration allows a caller holding the required ERC-721 items to mint some amount `amountOut` of a new ERC-721 `tokenOut` item in exchange for burning `price` amount of a `payingToken` ERC-20 token. Any ERC-721 collection being minted by this redeemer must grant minting permissions to this contract in some fashion. Users must also approve this contract to spend any requisite `payingToken` ERC-20 tokens on their behalf. April 27th, 2022. */ contract ImpostorsRedeemer721 is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; /** A configurable address to transfer burned ERC-20 tokens to. The intent of specifying an address like this is to support burning otherwise unburnable ERC-20 tokens by transferring them to provably unrecoverable destinations, such as blackhole smart contracts. */ address public immutable burnDestination; /** A mapping from a redemption round ID to an array of ERC-721 item collection addresses required to be held in fulfilling a redemption claim. In order to participate in a redemption round, a caller must hold a specific item from each of these required ERC-721 item collections. */ mapping ( uint256 => address[] ) public redemptionCriteria; /** This struct is used when configuring a redemption round to specify a caller's required payment and the ERC-721 items they may be minted in return. @param price The amount of `payingToken` that a caller must pay for each set of items redeemed in this round. @param tokenOut The address of the ERC-721 item collection from which a caller will receive newly-minted items. @param payingToken The ERC-20 token of which `price` must be paid for each redemption. @param amountOut The number of new `tokenOut` ERC-721 items a caller will receive in return for fulfilling a claim. */ struct RedemptionConfig { uint96 price; address tokenOut; address payingToken; uint96 amountOut; } /// A mapping from a redemption round ID to its configuration details. mapping ( uint256 => RedemptionConfig ) public redemptionConfigs; /** A triple mapping from a redemption round ID to an ERC-721 item collection address to the token ID of a specific item in the ERC-721 item collection. This mapping ensures that a specific item can only be used once in any given redemption round. */ mapping ( uint256 => mapping ( address => mapping ( uint256 => bool ) ) ) public redeemed; /** An event tracking a claim in a redemption round for some ERC-721 items. @param round The redemption round ID involved in the claim. @param caller The caller who triggered the claim. @param tokenIds The array of token IDs for specific items keyed against the matching `criteria` paramter. */ event TokenRedemption ( uint256 indexed round, address indexed caller, uint256[] tokenIds ); /** An event tracking a configuration update for the details of a particular redemption round. @param round The redemption round ID with updated configuration. @param criteria The array of ERC-721 item collection addresses required for fulfilling a redemption claim in this round. @param configuration The updated `RedemptionConfig` configuration details for this round. */ event ConfigUpdate ( uint256 indexed round, address[] indexed criteria, RedemptionConfig indexed configuration ); /** Construct a new item redeemer by specifying a destination for burnt tokens. @param _burnDestination An address where tokens received for fulfilling redemptions are sent. */ constructor ( address _burnDestination ) { burnDestination = _burnDestination; } /** Easily check the redemption status of multiple tokens of a single collection in a single round. @param _round The round to check for token redemption against. @param _collection The address of the specific item collection to check. @param _tokenIds An array of token IDs belonging to the collection `_collection` to check for redemption status. @return An array of boolean redemption status for each of the items being checked in `_tokenIds`. */ function isRedeemed ( uint256 _round, address _collection, uint256[] memory _tokenIds ) external view returns (bool[] memory) { bool[] memory redemptionStatus = new bool[](_tokenIds.length); for (uint256 i = 0; i < _tokenIds.length; i += 1) { redemptionStatus[i] = redeemed[_round][_collection][_tokenIds[i]]; } return redemptionStatus; } /** Set the configuration details for a particular redemption round. A specific redemption round may be effectively disabled by setting the `amountOut` field of the given `RedemptionConfig` `_config` value to 0. @param _round The redemption round ID to configure. @param _criteria An array of ERC-721 item collection addresses to require holdings from when a caller attempts to redeem from the round of ID `_round`. @param _config The `RedemptionConfig` configuration data to use for setting new configuration details for the round of ID `_round`. */ function setConfig ( uint256 _round, address[] calldata _criteria, RedemptionConfig calldata _config ) external onlyOwner { /* Prevent a redemption round from being configured with no requisite ERC-721 item collection holding criteria. */ if (_criteria.length == 0) { revert CannotConfigureEmptyCriteria(); } /* Perform input validation on the provided configuration details. A redemption round may not be configured with no ERC-721 item collection to mint as output. */ if (_config.tokenOut == address(0)) { revert CannotConfigureWithoutOutputItem(); } /* A redemption round may not be configured with no ERC-20 token address to attempt to enforce payment from. */ if (_config.payingToken == address(0)) { revert CannotConfigureWithoutPaymentToken(); } // Update the redemption criteria of this round. redemptionCriteria[_round] = _criteria; // Update the contents of the round configuration mapping. redemptionConfigs[_round] = RedemptionConfig({ amountOut: _config.amountOut, price: _config.price, tokenOut: _config.tokenOut, payingToken: _config.payingToken }); // Emit the configuration update event. emit ConfigUpdate(_round, _criteria, _config); } /** Allow a caller to redeem potentially multiple sets of criteria ERC-721 items in `_tokenIds` against the redemption round of ID `_round`. @param _round The ID of the redemption round to redeem against. @param _tokenIds An array of token IDs for the specific ERC-721 items keyed to the item collection criteria addresses for this round in the `redemptionCriteria` mapping. */ function redeem ( uint256 _round, uint256[][] memory _tokenIds ) external nonReentrant { address[] memory criteria = redemptionCriteria[_round]; RedemptionConfig memory config = redemptionConfigs[_round]; // Prevent a caller from redeeming from a round with zero output items. if (config.amountOut < 1) { revert CannotRedeemForZeroItems(); } /* The caller may be attempting to redeem for multiple independent sets of items in this redemption round. Process each set of token IDs against the criteria addresses. */ for (uint256 set = 0; set < _tokenIds.length; set += 1) { /* If the item set is not the same length as the criteria array, we have a mismatch and the set cannot possibly be fulfilled. */ if (_tokenIds[set].length != criteria.length) { revert CannotRedeemCriteriaLengthMismatch(); } /* Check each item in the set against each of the expected, required criteria collections. */ for (uint256 i; i < criteria.length; i += 1) { // Verify that no item may be redeemed twice against a single round. if (redeemed[_round][criteria[i]][_tokenIds[set][i]]) { revert CannotRedeemItemAlreadyRedeemed(); } /* Verify that the caller owns each of the items involved in the redemption claim. */ if (ITiny721(criteria[i]).ownerOf(_tokenIds[set][i]) != _msgSender()) { revert CannotRedeemUnownedItem(); } // Flag each item as redeemed against this round. redeemed[_round][criteria[i]][_tokenIds[set][i]] = true; } // Emit an event indicating which tokens were redeemed. emit TokenRedemption(_round, _msgSender(), _tokenIds[set]); } // If there is a non-zero redemption price, perform the required token burn. if (config.price > 0) { IERC20(config.payingToken).safeTransferFrom( _msgSender(), burnDestination, config.price * _tokenIds.length ); } // Mint the caller their redeemed items. ITiny721(config.tokenOut).mint_Qgo( _msgSender(), config.amountOut * _tokenIds.length ); } /** Allow the owner to sweep either Ether or a particular ERC-20 token from the contract and send it to another address. This allows the owner of the shop to withdraw their funds after the sale is completed. @param _token The token to sweep the balance from; if a zero address is sent then the contract's balance of Ether will be swept. @param _destination The address to send the swept tokens to. @param _amount The amount of token to sweep. */ function sweep ( address _token, address _destination, uint256 _amount ) external onlyOwner nonReentrant { // A zero address means we should attempt to sweep Ether. if (_token == address(0)) { (bool success, ) = payable(_destination).call{ value: _amount }(""); if (!success) { revert SweepingTransferFailed(); } // Otherwise, we should try to sweep an ERC-20 token. } else { IERC20(_token).safeTransfer(_destination, _amount); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.11; /** @title A minimalistic, gas-efficient ERC-721 implementation forked from the `Super721` ERC-721 implementation used by SuperFarm. @author Tim Clancy @author 0xthrpw @author Qazawat Zirak @author Rostislav Khlebnikov Compared to the original `Super721` implementation that this contract forked from, this is a very pared-down contract that includes simple delegated minting and transfer locks. This contract includes the gas efficiency techniques graciously shared with the world in the specific ERC-721 implementation by Chiru Labs that is being called "ERC-721A" (https://github.com/chiru-labs/ERC721A). We have validated this contract against their test cases. February 8th, 2022. */ interface ITiny721 { /** Return whether or not the transfer of a particular token ID `_id` is locked. @param _id The ID of the token to check the lock status of. @return Whether or not the particular token ID `_id` has transfers locked. */ function transferLocks ( uint256 _id ) external returns (bool); /** Provided with an address parameter, this function returns the number of all tokens in this collection that are owned by the specified address. @param _owner The address of the account for which we are checking balances */ function balanceOf ( address _owner ) external returns ( uint256 ); /** Return the address that holds a particular token ID. @param _id The token ID to check for the holding address of. @return The address that holds the token with ID of `_id`. */ function ownerOf ( uint256 _id ) external returns (address); /** This function allows permissioned minters of this contract to mint one or more tokens dictated by the `_amount` parameter. Any minted tokens are sent to the `_recipient` address. Note that tokens are always minted sequentially starting at one. That is, the list of token IDs is always increasing and looks like [ 1, 2, 3... ]. Also note that per our use cases the intended recipient of these minted items will always be externally-owned accounts and not other contracts. As a result there is no safety check on whether or not the mint destination can actually correctly handle an ERC-721 token. @param _recipient The recipient of the tokens being minted. @param _amount The amount of tokens to mint. */ function mint_Qgo ( address _recipient, uint256 _amount ) external; /** This function allows an administrative caller to lock the transfer of particular token IDs. This is designed for a non-escrow staking contract that comes later to lock a user's NFT while still letting them keep it in their wallet. @param _id The ID of the token to lock. @param _locked The status of the lock; true to lock, false to unlock. */ function lockTransfer ( uint256 _id, bool _locked ) external; } // 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 (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); } } } }
//// Update the contents of the round configuration mapping.
function setConfig ( uint256 _round, address[] calldata _criteria, RedemptionConfig calldata _config ) external onlyOwner { Prevent a redemption round from being configured with no requisite ERC-721 item collection holding criteria. if (_criteria.length == 0) { revert CannotConfigureEmptyCriteria(); } redemption round may not be configured with no ERC-721 item collection to mint as output. if (_config.tokenOut == address(0)) { revert CannotConfigureWithoutOutputItem(); } attempt to enforce payment from. if (_config.payingToken == address(0)) { revert CannotConfigureWithoutPaymentToken(); } redemptionConfigs[_round] = RedemptionConfig({ amountOut: _config.amountOut, price: _config.price, tokenOut: _config.tokenOut, payingToken: _config.payingToken }); } in `_tokenIds` against the redemption round of ID `_round`. @param _round The ID of the redemption round to redeem against. @param _tokenIds An array of token IDs for the specific ERC-721 items keyed to the item collection criteria addresses for this round in the `redemptionCriteria` mapping.
1,247,424
// SPDX-License-Identifier: CC0-1.0 pragma solidity ^0.8.0; // constants import "./LSP7Constants.sol"; import "../LSP1UniversalReceiver/LSP1Constants.sol"; import "../LSP4DigitalAssetMetadata/LSP4Constants.sol"; // interfaces import "../LSP1UniversalReceiver/ILSP1UniversalReceiver.sol"; import "./ILSP7DigitalAsset.sol"; // modules import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@erc725/smart-contracts/contracts/ERC725Y.sol"; // library import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; /** * @title LSP7DigitalAsset contract * @author Matthew Stevens * @dev Core Implementation of a LSP7 compliant contract. */ abstract contract LSP7DigitalAssetCore is Context, ILSP7DigitalAsset { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; using Address for address; // --- Storage bool internal _isNFT; uint256 internal _existingTokens; // Mapping from `tokenOwner` to an `amount` of tokens mapping(address => uint256) internal _tokenOwnerBalances; // Mapping a `tokenOwner` to an `operator` to `amount` of tokens. mapping(address => mapping(address => uint256)) internal _operatorAuthorizedAmount; // --- Token queries /** * @inheritdoc ILSP7DigitalAsset */ function decimals() public view override returns (uint256) { return _isNFT ? 0 : 18; } /** * @inheritdoc ILSP7DigitalAsset */ function totalSupply() public view override returns (uint256) { return _existingTokens; } // --- Token owner queries /** * @inheritdoc ILSP7DigitalAsset */ function balanceOf(address tokenOwner) public view override returns (uint256) { return _tokenOwnerBalances[tokenOwner]; } // --- Operator functionality /** * @inheritdoc ILSP7DigitalAsset */ function authorizeOperator(address operator, uint256 amount) public virtual override { _updateOperator(_msgSender(), operator, amount); } /** * @inheritdoc ILSP7DigitalAsset */ function revokeOperator(address operator) public virtual override { _updateOperator(_msgSender(), operator, 0); } /** * @inheritdoc ILSP7DigitalAsset */ function isOperatorFor(address operator, address tokenOwner) public view virtual override returns (uint256) { if (tokenOwner == operator) { return _tokenOwnerBalances[tokenOwner]; } else { return _operatorAuthorizedAmount[tokenOwner][operator]; } } // --- Transfer functionality /** * @inheritdoc ILSP7DigitalAsset */ function transfer( address from, address to, uint256 amount, bool force, bytes memory data ) public virtual override { address operator = _msgSender(); if (operator != from) { uint256 operatorAmount = _operatorAuthorizedAmount[from][operator]; require( operatorAmount >= amount, "LSP7: transfer amount exceeds operator authorized amount" ); _updateOperator( from, operator, _operatorAuthorizedAmount[from][operator] - amount ); } _transfer(from, to, amount, force, data); } /** * @inheritdoc ILSP7DigitalAsset */ function transferBatch( address[] memory from, address[] memory to, uint256[] memory amount, bool force, bytes[] memory data ) external virtual override { require( from.length == to.length && from.length == amount.length && from.length == data.length, "LSP7: transferBatch list length mismatch" ); for (uint256 i = 0; i < from.length; i++) { // using the public transfer function to handle updates to operator authorized amounts transfer(from[i], to[i], amount[i], force, data[i]); } } /** * @dev Changes token `amount` the `operator` has access to from `tokenOwner` tokens. If the * amount is zero then the operator is being revoked, otherwise the operator amount is being * modified. * * See {isOperatorFor}. * * Emits either {AuthorizedOperator} or {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. * - `operator` cannot be the zero address. */ function _updateOperator( address tokenOwner, address operator, uint256 amount ) internal virtual { require( operator != tokenOwner, "LSP7: updating operator failed, can not use token owner as operator" ); require( operator != address(0), "LSP7: updating operator failed, operator can not be zero address" ); require( tokenOwner != address(0), "LSP7: updating operator failed, can not set operator for zero address" ); _operatorAuthorizedAmount[tokenOwner][operator] = amount; if (amount > 0) { emit AuthorizedOperator(operator, tokenOwner, amount); } else { emit RevokedOperator(operator, tokenOwner); } } /** * @dev Mints `amount` tokens and transfers it to `to`. * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint( address to, uint256 amount, bool force, bytes memory data ) internal virtual { require(to != address(0), "LSP7: mint to the zero address not allowed"); address operator = _msgSender(); _beforeTokenTransfer(address(0), to, amount); _tokenOwnerBalances[to] += amount; emit Transfer(operator, address(0), to, amount, force, data); _notifyTokenReceiver(address(0), to, amount, force, data); } /** * @dev Destroys `amount` tokens. * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens. * - If the caller is not `from`, it must be an operator for `from` with access to at least * `amount` tokens. * * Emits a {Transfer} event. */ function _burn( address from, uint256 amount, bytes memory data ) internal virtual { require(from != address(0), "LSP7: burn from the zero address"); require( _tokenOwnerBalances[from] >= amount, "LSP7: burn amount exceeds tokenOwner balance" ); address operator = _msgSender(); if (operator != from) { require( _operatorAuthorizedAmount[from][operator] >= amount, "LSP7: burn amount exceeds operator authorized amount" ); _operatorAuthorizedAmount[from][operator] -= amount; } _notifyTokenSender(from, address(0), amount, data); _beforeTokenTransfer(from, address(0), amount); _tokenOwnerBalances[from] -= amount; emit Transfer(operator, from, address(0), amount, false, data); } /** * @dev Transfers `amount` tokens from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens. * - If the caller is not `from`, it must be an operator for `from` with access to at least * `amount` tokens. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 amount, bool force, bytes memory data ) internal virtual { require(from != address(0), "LSP7: transfer from the zero address"); require(to != address(0), "LSP7: transfer to the zero address"); require( _tokenOwnerBalances[from] >= amount, "LSP7: transfer amount exceeds tokenOwner balance" ); address operator = _msgSender(); _notifyTokenSender(from, to, amount, data); _beforeTokenTransfer(from, to, amount); _tokenOwnerBalances[from] -= amount; _tokenOwnerBalances[to] += amount; emit Transfer(operator, from, to, amount, force, data); _notifyTokenReceiver(from, to, amount, force, data); } /** * @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 `amount` tokens will be * transferred to `to`. * - When `from` is zero, `amount` tokens will be minted for `to`. * - When `to` is zero, ``from``'s `amount` tokens will be burned. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { // tokens being minted if (from == address(0)) { _existingTokens += amount; } // tokens being burned if (to == address(0)) { _existingTokens -= amount; } } /** * @dev An attempt is made to notify the token sender about the `amount` tokens changing owners using * LSP1 interface. */ function _notifyTokenSender( address from, address to, uint256 amount, bytes memory data ) internal virtual { if ( ERC165Checker.supportsERC165(from) && ERC165Checker.supportsInterface(from, _INTERFACEID_LSP1) ) { bytes memory packedData = abi.encodePacked(from, to, amount, data); ILSP1UniversalReceiver(from).universalReceiver( _TYPEID_LSP7_TOKENSSENDER, packedData ); } } /** * @dev An attempt is made to notify the token receiver about the `amount` tokens changing owners * using LSP1 interface. When force is FALSE the token receiver MUST support LSP1. * * The receiver may revert when the token being sent is not wanted. */ function _notifyTokenReceiver( address from, address to, uint256 amount, bool force, bytes memory data ) internal virtual { if ( ERC165Checker.supportsERC165(to) && ERC165Checker.supportsInterface(to, _INTERFACEID_LSP1) ) { bytes memory packedData = abi.encodePacked(from, to, amount, data); ILSP1UniversalReceiver(to).universalReceiver( _TYPEID_LSP7_TOKENSRECIPIENT, packedData ); } else if (!force) { if (to.isContract()) { revert("LSP7: token receiver contract missing LSP1 interface"); } else { revert("LSP7: token receiver is EOA"); } } } }
@inheritdoc ILSP7DigitalAsset/
function authorizeOperator(address operator, uint256 amount) public virtual override { _updateOperator(_msgSender(), operator, amount); }
12,759,740
/* Copyright 2019 Wanchain Foundation. 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. */ // _ _ _ // __ ____ _ _ __ ___| |__ __ _(_)_ __ __| | _____ __ // \ \ /\ / / _` | '_ \ / __| '_ \ / _` | | '_ \@/ _` |/ _ \ \ / / // \ V V / (_| | | | | (__| | | | (_| | | | | | (_| | __/\ V / // \_/\_/ \__,_|_| |_|\___|_| |_|\__,_|_|_| |_|\__,_|\___| \_/ // // pragma solidity ^0.4.26; pragma experimental ABIEncoderV2; import "./RapidityTxLib.sol"; import "./CrossTypes.sol"; import "../../interfaces/ITokenManager.sol"; // import "../../interfaces/IRC20Protocol.sol"; import "../../interfaces/ISmgFeeProxy.sol"; library RapidityLib { using SafeMath for uint; using RapidityTxLib for RapidityTxLib.Data; /** * * STRUCTURES * */ /// @notice struct of Rapidity storeman mint lock parameters struct RapidityUserMintParams { bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value bytes userShadowAccount; /// account of shadow chain, used to receive token } /// @notice struct of Rapidity storeman mint lock parameters struct RapiditySmgMintParams { bytes32 uniqueID; /// Rapidity random number bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value address userShadowAccount; /// account of shadow chain, used to receive token } /// @notice struct of Rapidity user burn lock parameters struct RapidityUserBurnParams { bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value bytes userOrigAccount; /// account of token original chain, used to receive token } /// @notice struct of Rapidity user burn lock parameters struct RapiditySmgBurnParams { bytes32 uniqueID; /// Rapidity random number bytes32 smgID; /// ID of storeman group which user has selected uint tokenPairID; /// token pair id on cross chain uint value; /// exchange token value address userOrigAccount; /// account of token original chain, used to receive token } /** * * EVENTS * **/ /// @notice event of exchange WRC-20 token with original chain token request /// @notice event invoked by storeman group /// @param smgID ID of storemanGroup /// @param tokenPairID token pair ID of cross chain token /// @param value Rapidity value /// @param userAccount account of shadow chain, used to receive token event UserFastMintLogger(bytes32 indexed smgID, uint indexed tokenPairID, uint value, uint fee, bytes userAccount); /// @notice event of exchange WRC-20 token with original chain token request /// @notice event invoked by storeman group /// @param uniqueID unique random number /// @param smgID ID of storemanGroup /// @param tokenPairID token pair ID of cross chain token /// @param value Rapidity value /// @param userAccount account of original chain, used to receive token event SmgFastMintLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address userAccount); /// @notice event of exchange WRC-20 token with original chain token request /// @notice event invoked by storeman group /// @param smgID ID of storemanGroup /// @param tokenPairID token pair ID of cross chain token /// @param value Rapidity value /// @param userAccount account of shadow chain, used to receive token event UserFastBurnLogger(bytes32 indexed smgID, uint indexed tokenPairID, uint value, uint fee, bytes userAccount); /// @notice event of exchange WRC-20 token with original chain token request /// @notice event invoked by storeman group /// @param uniqueID unique random number /// @param smgID ID of storemanGroup /// @param tokenPairID token pair ID of cross chain token /// @param value Rapidity value /// @param userAccount account of original chain, used to receive token event SmgFastBurnLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address userAccount); /** * * MANIPULATIONS * */ /// @notice mintBridge, user lock token on token original chain /// @notice event invoked by user mint lock /// @param storageData Cross storage data /// @param params parameters for user mint lock token on token original chain function userFastMint(CrossTypes.Data storage storageData, RapidityUserMintParams memory params) public { uint origChainID; uint shadowChainID; bytes memory tokenOrigAccount; (origChainID,tokenOrigAccount,shadowChainID) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID); require(origChainID != 0, "Token does not exist"); uint lockFee = storageData.mapLockFee[origChainID][shadowChainID]; storageData.quota.userFastMint(params.tokenPairID, params.smgID, params.value); if (lockFee > 0) { if (storageData.smgFeeProxy == address(0)) { storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(lockFee); } else { ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(lockFee)(params.smgID); } } address tokenScAddr = CrossTypes.bytesToAddress(tokenOrigAccount); uint left; if (tokenScAddr == address(0)) { left = (msg.value).sub(params.value).sub(lockFee); } else { left = (msg.value).sub(lockFee); // require(IRC20Protocol(tokenScAddr).transferFrom(msg.sender, this, params.value), "Lock token failed"); require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed"); } if (left != 0) { (msg.sender).transfer(left); } emit UserFastMintLogger(params.smgID, params.tokenPairID, params.value, lockFee, params.userShadowAccount); } /// @notice mintBridge, storeman mint lock token on token shadow chain /// @notice event invoked by user mint lock /// @param storageData Cross storage data /// @param params parameters for storeman mint lock token on token shadow chain function smgFastMint(CrossTypes.Data storage storageData, RapiditySmgMintParams memory params) public { storageData.rapidityTxData.addRapidityTx(params.uniqueID); storageData.quota.smgFastMint(params.tokenPairID, params.smgID, params.value); storageData.tokenManager.mintToken(params.tokenPairID, params.userShadowAccount, params.value); emit SmgFastMintLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.userShadowAccount); } /// @notice burnBridge, user lock token on token original chain /// @notice event invoked by user burn lock /// @param storageData Cross storage data /// @param params parameters for user burn lock token on token original chain function userFastBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params) public { uint origChainID; uint shadowChainID; bytes memory tokenShadowAccount; (origChainID,,shadowChainID,tokenShadowAccount) = storageData.tokenManager.getTokenPairInfo(params.tokenPairID); require(origChainID != 0, "Token does not exist"); uint lockFee = storageData.mapLockFee[origChainID][shadowChainID]; storageData.quota.userFastBurn(params.tokenPairID, params.smgID, params.value); address tokenScAddr = CrossTypes.bytesToAddress(tokenShadowAccount); // require(IRC20Protocol(tokenScAddr).transferFrom(msg.sender, this, params.value), "Lock token failed"); require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed"); storageData.tokenManager.burnToken(params.tokenPairID, params.value); if (lockFee > 0) { if (storageData.smgFeeProxy == address(0)) { storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(lockFee); } else { ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(lockFee)(params.smgID); } } uint left = (msg.value).sub(lockFee); if (left != 0) { (msg.sender).transfer(left); } emit UserFastBurnLogger(params.smgID, params.tokenPairID, params.value, lockFee, params.userOrigAccount); } /// @notice burnBridge, storeman burn lock token on token shadow chain /// @notice event invoked by user burn lock /// @param storageData Cross storage data /// @param params parameters for storeman burn lock token on token shadow chain function smgFastBurn(CrossTypes.Data storage storageData, RapiditySmgBurnParams memory params) public { uint origChainID; bytes memory tokenOrigAccount; (origChainID,tokenOrigAccount,) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID); require(origChainID != 0, "Token does not exist"); storageData.rapidityTxData.addRapidityTx(params.uniqueID); storageData.quota.smgFastBurn(params.tokenPairID, params.smgID, params.value); address tokenScAddr = CrossTypes.bytesToAddress(tokenOrigAccount); if (tokenScAddr == address(0)) { (params.userOrigAccount).transfer(params.value); } else { // require(IRC20Protocol(tokenScAddr).transfer(params.userOrigAccount, params.value), "Transfer token failed"); require(CrossTypes.transfer(tokenScAddr, params.userOrigAccount, params.value), "Transfer token failed"); } emit SmgFastBurnLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.userOrigAccount); } }
burnBridge, storeman burn lock token on token shadow chain event invoked by user burn lock storageData Cross storage data params parameters for storeman burn lock token on token shadow chain require(IRC20Protocol(tokenScAddr).transfer(params.userOrigAccount, params.value), "Transfer token failed");
function smgFastBurn(CrossTypes.Data storage storageData, RapiditySmgBurnParams memory params) public { uint origChainID; bytes memory tokenOrigAccount; (origChainID,tokenOrigAccount,) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID); require(origChainID != 0, "Token does not exist"); storageData.rapidityTxData.addRapidityTx(params.uniqueID); storageData.quota.smgFastBurn(params.tokenPairID, params.smgID, params.value); address tokenScAddr = CrossTypes.bytesToAddress(tokenOrigAccount); if (tokenScAddr == address(0)) { (params.userOrigAccount).transfer(params.value); require(CrossTypes.transfer(tokenScAddr, params.userOrigAccount, params.value), "Transfer token failed"); } emit SmgFastBurnLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.userOrigAccount); }
2,486,001
/* 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.6.10; pragma experimental "ABIEncoderV2"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.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 { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol"; import { IController } from "../../interfaces/IController.sol"; import { ISetValuer } from "../../interfaces/ISetValuer.sol"; import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol"; import { Invoke } from "../lib/Invoke.sol"; import { ISetToken } from "../../interfaces/ISetToken.sol"; import { IWETH } from "../../interfaces/external/IWETH.sol"; import { ModuleBase } from "../lib/ModuleBase.sol"; import { Position } from "../lib/Position.sol"; import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol"; import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol"; /** * @title CustomOracleNavIssuanceModule * @author Set Protocol * * Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives * a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using * oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front * running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset). */ contract CustomOracleNavIssuanceModule is ModuleBase, ReentrancyGuard { using AddressArrayUtils for address[]; using Invoke for ISetToken; using Position for ISetToken; using PreciseUnitMath for uint256; using PreciseUnitMath for int256; using ResourceIdentifier for IController; using SafeMath for uint256; using SafeCast for int256; using SafeCast for uint256; using SignedSafeMath for int256; /* ============ Events ============ */ event SetTokenNAVIssued( ISetToken indexed _setToken, address _issuer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event SetTokenNAVRedeemed( ISetToken indexed _setToken, address _redeemer, address _to, address _reserveAsset, address _hookContract, uint256 _setTokenQuantity, uint256 _managerFee, uint256 _premium ); event ReserveAssetAdded( ISetToken indexed _setToken, address _newReserveAsset ); event ReserveAssetRemoved( ISetToken indexed _setToken, address _removedReserveAsset ); event PremiumEdited( ISetToken indexed _setToken, uint256 _newPremium ); event ManagerFeeEdited( ISetToken indexed _setToken, uint256 _newManagerFee, uint256 _index ); event FeeRecipientEdited( ISetToken indexed _setToken, address _feeRecipient ); /* ============ Structs ============ */ struct NAVIssuanceSettings { INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations ISetValuer setValuer; // Optional custom set valuer. If address(0) is provided, fetch the default one from the controller address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle // prices paid by user to the SetToken, which prevents arbitrage and oracle front running uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager) uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the SetToken's position multiplier } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity // During redeem, represents post-premium value uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken // When redeeming, quantity of reserve asset sent to redeemer uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee // When redeeming, quantity of SetToken redeemed uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action uint256 newSetTokenSupply; // SetToken supply after issue/redeem action int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem } /* ============ State Variables ============ */ // Wrapped ETH address IWETH public immutable weth; // Mapping of SetToken to NAV issuance settings struct mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings; // Mapping to efficiently check a SetToken's reserve asset validity // SetToken => reserveAsset => isReserveAsset mapping(ISetToken => mapping(address => bool)) public isReserveAsset; /* ============ Constants ============ */ // 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 1 index stores the manager fee percentage in managerFees array, charged on redeem uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1; // 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1; // 2 index stores the direct protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; // 3 index stores the direct protocol fee % on the controller, charged in the redeem function uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3; /* ============ Constructor ============ */ /** * @param _controller Address of controller contract * @param _weth Address of wrapped eth */ constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) { weth = _weth; } /* ============ External Functions ============ */ /** * Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to issue with * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issue( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, uint256 _minSetTokenReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity); _callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo); _handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo); } /** * Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken * to the specified _to address. * * @param _setToken Instance of the SetToken contract * @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance * @param _to Address to mint SetToken to */ function issueWithEther( ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, address _to ) external payable nonReentrant onlyValidAndInitializedSet(_setToken) { weth.deposit{ value: msg.value }(); _validateCommon(_setToken, address(weth), msg.value); _callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to); ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value); _validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo); _transferWETHAndHandleFees(_setToken, issueInfo); _handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo); } /** * Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available reserve units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _reserveAsset Address of the reserve asset to redeem with * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeem( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, _reserveAsset, _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer the reserve asset back to the user _setToken.strictInvokeTransfer( _reserveAsset, _to, redeemInfo.netFlowQuantity ); _handleRedemptionFees(_setToken, _reserveAsset, redeemInfo); _handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo); } /** * Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken * to the specified _to address. Only valid if there are available WETH units on the SetToken. * * @param _setToken Instance of the SetToken contract * @param _setTokenQuantity Quantity of SetTokens to redeem * @param _minReserveReceiveQuantity Min quantity of reserve asset to receive * @param _to Address to redeem reserve asset to */ function redeemIntoEther( ISetToken _setToken, uint256 _setTokenQuantity, uint256 _minReserveReceiveQuantity, address payable _to ) external nonReentrant onlyValidAndInitializedSet(_setToken) { _validateCommon(_setToken, address(weth), _setTokenQuantity); _callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to); ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity); _validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo); _setToken.burn(msg.sender, _setTokenQuantity); // Instruct the SetToken to transfer WETH from SetToken to module _setToken.strictInvokeTransfer( address(weth), address(this), redeemInfo.netFlowQuantity ); weth.withdraw(redeemInfo.netFlowQuantity); _to.transfer(redeemInfo.netFlowQuantity); _handleRedemptionFees(_setToken, address(weth), redeemInfo); _handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo); } /** * SET MANAGER ONLY. Add an allowed reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to add */ function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists"); navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset); isReserveAsset[_setToken][_reserveAsset] = true; emit ReserveAssetAdded(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Remove a reserve asset * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset to remove */ function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) { require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist"); navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset); delete isReserveAsset[_setToken][_reserveAsset]; emit ReserveAssetRemoved(_setToken, _reserveAsset); } /** * SET MANAGER ONLY. Edit the premium percentage * * @param _setToken Instance of the SetToken * @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%) */ function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) { require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed"); navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage; emit PremiumEdited(_setToken, _premiumPercentage); } /** * SET MANAGER ONLY. Edit manager fee * * @param _setToken Instance of the SetToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ISetToken _setToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidSet(_setToken) { require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed"); navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage; emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex); } /** * SET MANAGER ONLY. Edit the manager fee recipient * * @param _setToken Instance of the SetToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient; emit FeeRecipientEdited(_setToken, _managerFeeRecipient); } /** * SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets, * fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional. * Address(0) means that no hook will be called. * * @param _setToken Instance of the SetToken to issue * @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters */ function initialize( ISetToken _setToken, NAVIssuanceSettings memory _navIssuanceSettings ) external onlySetManager(_setToken, msg.sender) onlyValidAndPendingSet(_setToken) { require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0"); require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%"); require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max"); require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max"); require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max"); require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address."); // Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0 require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0"); for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) { require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique"); isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true; } navIssuanceSettings[_setToken] = _navIssuanceSettings; _setToken.initializeModule(); } /** * Removes this module from the SetToken, via call by the SetToken. Issuance settings and * reserve asset states are deleted. */ function removeModule() external override { ISetToken setToken = ISetToken(msg.sender); for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) { delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]]; } delete navIssuanceSettings[setToken]; } receive() external payable {} /* ============ External Getter Functions ============ */ function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) { return navIssuanceSettings[_setToken].reserveAssets; } function getIssuePremium( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity); } function getRedeemPremium( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); } function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) { return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; } /** * Get the expected SetTokens minted to recipient on issuance * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return uint256 Expected SetTokens to be minted to recipient */ function getExpectedSetTokenIssueQuantity( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (uint256) { (,, uint256 netReserveFlow) = _getFees( _setToken, _reserveAssetQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); uint256 setTotalSupply = _setToken.totalSupply(); return _getSetTokenMintQuantity( _setToken, _reserveAsset, netReserveFlow, setTotalSupply ); } /** * Get the expected reserve asset to be redeemed * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return uint256 Expected reserve asset quantity redeemed */ function getExpectedReserveRedeemQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (uint256) { uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 netReserveFlows) = _getFees( _setToken, preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); return netReserveFlows; } /** * Checks if issue is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _reserveAssetQuantity Quantity of the reserve asset to issue with * * @return bool Returns true if issue is valid */ function isIssueValid( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); return _reserveAssetQuantity != 0 && isReserveAsset[_setToken][_reserveAsset] && setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply; } /** * Checks if redeem is valid * * @param _setToken Instance of the SetToken * @param _reserveAsset Address of the reserve asset * @param _setTokenQuantity Quantity of SetTokens to redeem * * @return bool Returns true if redeem is valid */ function isRedeemValid( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) external view returns (bool) { uint256 setTotalSupply = _setToken.totalSupply(); if ( _setTokenQuantity == 0 || !isReserveAsset[_setToken][_reserveAsset] || setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity) ) { return false; } else { uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (,, uint256 expectedRedeemQuantity) = _getFees( _setToken, totalRedeemValue, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity; } } /* ============ Internal Functions ============ */ function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view { require(_quantity > 0, "Quantity must be > 0"); require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset"); } function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0 require( _issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable issuance" ); require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken"); } function _validateRedemptionInfo( ISetToken _setToken, uint256 _minReserveReceiveQuantity, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view { // Check that new supply is more than min supply needed for redemption // Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0 require( _redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply, "Supply must be greater than minimum to enable redemption" ); require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity"); } function _createIssuanceInfo( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousSetTokenSupply = _setToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees( _setToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.setTokenQuantity = _getSetTokenMintQuantity( _setToken, _reserveAsset, issueInfo.netFlowQuantity, issueInfo.previousSetTokenSupply ); (issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo); issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo); return issueInfo; } function _createRedemptionInfo( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory redeemInfo; redeemInfo.setTokenQuantity = _setTokenQuantity; redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity); (redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees( _setToken, redeemInfo.preFeeReserveQuantity, PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_REDEEM_DIRECT_FEE_INDEX, MANAGER_REDEEM_FEE_INDEX ); redeemInfo.previousSetTokenSupply = _setToken.totalSupply(); (redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo); redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo); return redeemInfo; } /** * Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients */ function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal { transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } /** * Transfer WETH from module to SetToken and fees from module to appropriate fee recipients */ function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal { weth.transfer(address(_setToken), _issueInfo.netFlowQuantity); if (_issueInfo.protocolFees > 0) { weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee); } } function _handleIssueStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _issueInfo ) internal { _setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit); _setToken.mint(_to, _issueInfo.setTokenQuantity); emit SetTokenNAVIssued( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerIssuanceHook), _issueInfo.setTokenQuantity, _issueInfo.managerFee, _issueInfo.protocolFees ); } function _handleRedeemStateUpdates( ISetToken _setToken, address _reserveAsset, address _to, ActionInfo memory _redeemInfo ) internal { _setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier); _setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit); emit SetTokenNAVRedeemed( _setToken, msg.sender, _to, _reserveAsset, address(navIssuanceSettings[_setToken].managerRedemptionHook), _redeemInfo.setTokenQuantity, _redeemInfo.managerFee, _redeemInfo.protocolFees ); } function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal { // Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees); // Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee if (_redeemInfo.managerFee > 0) { _setToken.strictInvokeTransfer( _reserveAsset, navIssuanceSettings[_setToken].feeRecipient, _redeemInfo.managerFee ); } } /** * Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the issuance premium. */ function _getIssuePremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _reserveAssetQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module * and can contain arbitrary logic to calculate the redemption premium. */ function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as follows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _setToken Instance of the SetToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller * @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset * @return uint256 Net reserve to user net of fees */ function _getFees( ISetToken _setToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _setToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee); return (protocolFees, managerFee, netReserveFlow); } function _getProtocolAndManagerFeePercentages( ISetToken _setToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (totalProtocolFeePercentage, managerRevenueSharePercentage); } function _getSetTokenMintQuantity( ISetToken _setToken, address _reserveAsset, uint256 _netReserveFlows, // Value of reserve asset net of fees uint256 _setTotalSupply ) internal view returns (uint256) { uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows); uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage); // If the set manager provided a custom valuer at initialization time, use it. Otherwise get it from the controller // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18) // Reverts if price is not found uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals); // Calculate SetTokens to mint to issuer uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium); return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator); } function _getRedeemReserveQuantity( ISetToken _setToken, address _reserveAsset, uint256 _setTokenQuantity ) internal view returns (uint256) { // Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18) // Reverts if price is not found uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset); uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals); uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity); uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage); return prePremiumReserveQuantity.sub(premiumQuantity); } /** * The new position multiplier is calculated as follows: * inflationPercentage = (newSupply - oldSupply) / newSupply * newMultiplier = (1 - inflationPercentage) * positionMultiplier */ function _getIssuePositionMultiplier( ISetToken _setToken, ActionInfo memory _issueInfo ) internal view returns (uint256, int256) { // Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_issueInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down * * The new position multiplier is calculated as follows: * deflationPercentage = (oldSupply - newSupply) / newSupply * newMultiplier = (1 + deflationPercentage) * positionMultiplier */ function _getRedeemPositionMultiplier( ISetToken _setToken, uint256 _setTokenQuantity, ActionInfo memory _redeemInfo ) internal view returns (uint256, int256) { uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity); int256 newPositionMultiplier = _setToken.positionMultiplier() .mul(_redeemInfo.previousSetTokenSupply.toInt256()) .div(newTotalSupply.toInt256()); return (newTotalSupply, newPositionMultiplier); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity * newUnit = totalReserve / newSetTokenSupply */ function _getIssuePositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _issueInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalReserve = existingUnit .preciseMul(_issueInfo.previousSetTokenSupply) .add(_issueInfo.netFlowQuantity); return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply); } /** * The new position reserve asset unit is calculated as follows: * totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut * newUnit = totalReserve / newSetTokenSupply */ function _getRedeemPositionUnit( ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo ) internal view returns (uint256) { uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256(); uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply); uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee); // Require withdrawable quantity is greater than existing collateral require(totalExistingUnits >= outflow, "Must be greater than total available collateral"); return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply); } /** * If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic * can contain arbitrary logic including validations, external function calls, etc. */ function _callPreIssueHooks( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _caller, address _to ) internal { INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook; if (address(preIssueHook) != address(0)) { preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to); } } /** * If a pre-redeem hook has been configured, call the external-protocol contract. */ function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal { INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook; if (address(preRedeemHook) != address(0)) { preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to); } } /** * If a custom set valuer has been configured, use it. Otherwise fetch the default one form the * controller. */ function _getSetValuer(ISetToken _setToken) internal view returns (ISetValuer) { ISetValuer customValuer = navIssuanceSettings[_setToken].setValuer; return address(customValuer) == address(0) ? controller.getSetValuer() : customValuer; } } // 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; /** * @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); } } // 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; } } /* 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.6.10; /** * @title AddressArrayUtils * @author Set Protocol * * Utility functions to handle Address Arrays */ 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; } } /* 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.6.10; 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.6.10; 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.6.10; import { ISetToken } from "./ISetToken.sol"; interface INAVIssuanceHook { function invokePreIssueHook( ISetToken _setToken, address _reserveAsset, uint256 _reserveAssetQuantity, address _sender, address _to ) external; function invokePreRedeemHook( ISetToken _setToken, uint256 _redeemQuantity, address _sender, address _to ) 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.6.10; 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.6.10; 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 2018 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. */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Set Protocol * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) 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.6.10; 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. */ 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) { require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager"); require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } modifier onlySetManager(ISetToken _setToken, address _caller) { require(isSetManager(_setToken, _caller), "Must be the SetToken manager"); _; } modifier onlyValidAndInitializedSet(ISetToken _setToken) { require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken"); _; } /** * Throws if the sender is not a SetToken's module or module not enabled */ modifier onlyModule(ISetToken _setToken) { require( _setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the SetToken is valid */ modifier onlyValidAndPendingSet(ISetToken _setToken) { require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken"); require(isSetPendingInitialization(_setToken), "Must be pending initialization"); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { 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)); } } /* 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.6.10; 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.6.10; 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 */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal 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; } } /* 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.6.10; 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 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // SetValuer resource will always be resource ID 2 in the system uint256 constant internal 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)); } } // 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; } } /* 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.6.10; 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.6.10; /** * @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; } // 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); } } } } /* 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.6.10; 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.6.10; /** * @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); }
Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module and can contain arbitrary logic to calculate the redemption premium./
function _getRedeemPremium( ISetToken _setToken, address /* _reserveAsset */, uint256 /* _setTokenQuantity */ ) virtual internal view returns (uint256) { return navIssuanceSettings[_setToken].premiumPercentage; }
91,169
./full_match/1/0xa943F863fA69ff4F6D9022843Fb861BBEe45B2ce/sources/TangleBundle0.sol
Gets all farms and their details return All farms and their details
function farms() external view returns (uint, uint, SLib.Farm[] memory) { SLib.S storage s = SLib.getS(); SLib.Farm[] memory farms_ = new SLib.Farm[](s.names.length); for (uint i = 0; i < s.names.length; i++) { farms_[i] = s.farms[s.names[i]]; farms_[i].max = piecesToUnits(farms_[i].max); farms_[i].last = piecesToUnits(farms_[i].last); farms_[i].propSum = farms_[i].propSum; } return (SLib.getS().piecesPerUnit, s.wc, farms_); }
17,007,044
./partial_match/1/0x41353Ef12FCD2BeE88dBCe07e710FEF6D37Fa282/sources/TwapManager.sol
Gets the owner of this contract. return Returns the address of the owner./
function owner () external virtual view returns (address) { return _owner; }
4,005,555
pragma solidity ^0.4.21; interface P3C { function() payable external; function buy(address _playerAddress) payable external returns(uint256); function sell(uint256 _amountOfTokens) external; function reinvest() external; function withdraw() external; function exit() external; function dividendsOf(address _playerAddress) external view returns(uint256); function balanceOf(address _playerAddress) external view returns(uint256); function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool); function stakingRequirement() external view returns(uint256); function myDividends(bool _includeReferralBonus) external view returns(uint256); } contract Crop { address public owner; bool public disabled; address public p3cAddress = 0xDF9AaC76b722B08511A4C561607A9bf3AfA62E49; modifier onlyOwner() { require(msg.sender == owner); _; } function() public payable {} /** * @dev Turn reinvest on / off * @param _disabled bool to determine state of reinvest. */ function disable(bool _disabled) external onlyOwner() { // toggle disabled disabled = _disabled; } /** * @dev Enables anyone with a masternode to earn referral fees on P3D reinvestments. */ function reinvest() external { // reinvest must be enabled require(disabled == false); // setup p3c P3C p3c = P3C(0xDF9AaC76b722B08511A4C561607A9bf3AfA62E49); // withdraw dividends p3c.withdraw(); // reinvest with a referral fee for sender p3c.buy.value(address(this).balance)(msg.sender); } /** * @dev Buy P3D tokens * @param _playerAddress referral address. */ function buy(address _playerAddress) external payable onlyOwner() { P3C(p3cAddress).buy.value(msg.value)(_playerAddress); } /** * @dev Sell P3D tokens and send balance to owner * @param _amountOfTokens amount of tokens to sell. */ function sell(uint256 _amountOfTokens) external onlyOwner() { // sell tokens P3C(p3cAddress).sell(_amountOfTokens); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Withdraw P3D dividends and send balance to owner */ function withdraw() external onlyOwner() { // withdraw dividends P3C(p3cAddress).withdraw(); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Sell P3D tokens, withdraw dividends, and send balance to owner */ function exit() external onlyOwner() { // sell all tokens and withdraw P3C(p3cAddress).exit(); // transfer to owner owner.transfer(address(this).balance); } /** * @dev Transfer P3D tokens * @param _toAddress address to send tokens to. * @param _amountOfTokens amount of tokens to send. */ function transfer(address _toAddress, uint256 _amountOfTokens) external onlyOwner() returns (bool) { return P3C(p3cAddress).transfer(_toAddress, _amountOfTokens); } /** * @dev Get dividends for this contract * @param _includeReferralBonus for including referrals in dividends. */ function dividends(bool _includeReferralBonus) external view returns (uint256) { return P3C(p3cAddress).myDividends(_includeReferralBonus); } }
Transfer P3D tokens _toAddress address to send tokens to. _amountOfTokens amount of tokens to send./
function transfer(address _toAddress, uint256 _amountOfTokens) external onlyOwner() returns (bool) { return P3C(p3cAddress).transfer(_toAddress, _amountOfTokens); }
15,787,834
./partial_match/1/0x0569168709a869e7f4Ba142c49BFF7faA14f76C8/sources/@violetprotocol/mauve-core/contracts/interfaces/IMauveFactory.sol
The interface for the Mauve Factory The Mauve Factory facilitates creation of Mauve pools and control over the protocol fees
interface IMauveFactory { event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); event RoleChanged(address indexed oldRoleAddress, address indexed newRoleAddress, bytes32 roleChanged); function feeAmountTickSpacing(uint24 fee) external view returns (int24); function setRole(address _newRoleAddress, bytes32 roleKey) external; function roles(bytes32 roleKey) external view returns (address); function getMauveTokenIdsAllowedToInteract() external view returns (uint256[] memory); function setMauveTokenIdsAllowedToInteract(uint256[] memory tokenIds) external; function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); function enableFeeAmount(uint24 fee, int24 tickSpacing) external; pragma solidity >=0.5.0; }
9,350,741
// Sources flattened with buidler v1.3.8 https://buidler.dev // SPDX-License-Identifier: MIT // File @openzeppelin/contracts/GSN/[email protected] pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] 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 @animoca/ethereum-contracts-core_library/contracts/access/[email protected] pragma solidity 0.6.8; contract WhitelistedOperators is Ownable { mapping(address => bool) internal _whitelistedOperators; event WhitelistedOperator(address operator, bool enabled); /// @notice Enable or disable address operator access /// @param operator address that will be given/removed operator right. /// @param enabled set whether the operator is enabled or disabled. function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); } /// @notice check whether address `who` is given operator rights. /// @param who The address to query. /// @return whether the address is whitelisted operator function isOperator(address who) public view returns (bool) { return _whitelistedOperators[who]; } } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/introspection/[email protected] pragma solidity ^0.6.0; /** * @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; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Interface for commonly used additional ERC20 interfaces */ interface IERC20Detailed { /** * @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 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. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Interface for additional ERC20 allowance features */ interface IERC20Allowance { /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] /* https://github.com/OpenZeppelin/openzeppelin-contracts The MIT License (MIT) Copyright (c) 2016-2019 zOS Global Limited Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.6.8; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20 is ERC165, Context, IERC20, IERC20Detailed, IERC20Allowance { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor() internal { _registerInterface(type(IERC20).interfaceId); _registerInterface(type(IERC20Detailed).interfaceId); _registerInterface(type(IERC20Allowance).interfaceId); // ERC20Name interfaceId: bytes4(keccak256("name()")) _registerInterface(0x06fdde03); // ERC20Symbol interfaceId: bytes4(keccak256("symbol()")) _registerInterface(0x95d89b41); // ERC20Decimals interfaceId: bytes4(keccak256("decimals()")) _registerInterface(0x313ce567); } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /** * @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; } /////////////////////////////////////////// ERC20Allowance /////////////////////////////////////// /** * @dev See {IERC20Allowance-increaseAllowance}. */ function increaseAllowance( address spender, uint256 addedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev See {IERC20Allowance-decreaseAllowance}. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public virtual override returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /////////////////////////////////////////// Hooks /////////////////////////////////////// /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; abstract contract ERC20WithOperators is ERC20, WhitelistedOperators { /** * NOTICE * This override will allow *any* whitelisted operator to be able to * transfer unresitricted amounts of ERC20WithOperators-based tokens from 'sender' * to 'recipient'. Care must be taken to ensure to integrity of the * whitelisted operator list. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { address msgSender = _msgSender(); // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. _msgSender()). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. if (!isOperator(msgSender)) { _approve(sender, msgSender, allowance(sender, msgSender).sub(amount)); } _transfer(sender, recipient, amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { if (isOperator(spender)) { // allow the front-end to determine whether or not an approval is // necessary, given that the whitelisted operator status of the // spender is unknown. A call to WhitelistedOperators::isOperator() // is more direct, but we want to expose a mechanism by which to // check through the ERC20 interface. return type(uint256).max; } else { return super.allowance(owner, spender); } } function increaseAllowance(address spender, uint256 addedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.increaseAllowance(spender, addedValue); } } function decreaseAllowance(address spender, uint256 subtractedValue) public override returns (bool) { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return true; } else { return super.decreaseAllowance(spender, subtractedValue); } } function _approve(address owner, address spender, uint256 value) internal override { if (isOperator(spender)) { // bypass the internal allowance manipulation and checks for the // whitelisted operator (i.e. spender). as a side-effect, the // 'Approval' event will not be emitted since the allowance was not // updated. return; } else { super._approve(owner, spender, value); } } } // File @animoca/f1dt-ethereum-contracts/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; contract REVV is ERC20WithOperators { string public override constant name = "REVV"; string public override constant symbol = "REVV"; uint8 public override constant decimals = 18; constructor ( address[] memory holders, uint256[] memory amounts ) public ERC20WithOperators() { require(holders.length == amounts.length, "REVV: wrong arguments"); for (uint256 i = 0; i < holders.length; ++i) { _mint(holders[i], amounts[i]); } } }
Enable or disable address operator access operator address that will be given/removed operator right. enabled set whether the operator is enabled or disabled.
function whitelistOperator(address operator, bool enabled) external onlyOwner { _whitelistedOperators[operator] = enabled; emit WhitelistedOperator(operator, enabled); }
2,023,198
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.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); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @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 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(address(this), spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // File: contracts/ens/AbstractENS.sol pragma solidity ^0.5.0; contract AbstractENS { function owner(bytes32 _node) public view returns(address); function resolver(bytes32 _node) public view returns(address); function ttl(bytes32 _node) public view returns(uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 _label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); } // File: contracts/ens/AbstractResolver.sol pragma solidity ^0.5.0; contract AbstractResolver { function supportsInterface(bytes4 _interfaceID) public view returns (bool); function addr(bytes32 _node) public view returns (address ret); function setAddr(bytes32 _node, address _addr) public; function hash(bytes32 _node) public view returns (bytes32 ret); function setHash(bytes32 _node, bytes32 _hash) public; } // File: contracts/misc/SingletonHash.sol pragma solidity ^0.5.0; contract SingletonHash { event HashConsumed(bytes32 indexed hash); /** * @dev Used hash accounting */ mapping(bytes32 => bool) public isHashConsumed; /** * @dev Parameter can be used only once * @param _hash Single usage hash */ function singletonHash(bytes32 _hash) internal { require(!isHashConsumed[_hash]); isHashConsumed[_hash] = true; emit HashConsumed(_hash); } } // File: openzeppelin-solidity/contracts/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } // File: openzeppelin-solidity/contracts/access/roles/SignerRole.sol pragma solidity ^0.5.0; contract SignerRole { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private _signers; constructor () internal { _addSigner(msg.sender); } modifier onlySigner() { require(isSigner(msg.sender)); _; } function isSigner(address account) public view returns (bool) { return _signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(msg.sender); } function _addSigner(address account) internal { _signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { _signers.remove(account); emit SignerRemoved(account); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.0; /** * @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 ECDSA { /** * @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 signature bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (signature.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. // 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))) } // 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 { 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: openzeppelin-solidity/contracts/drafts/SignatureBouncer.sol pragma solidity ^0.5.0; /** * @title SignatureBouncer * @author PhABC, Shrugs and aflesher * @dev SignatureBouncer allows users to submit a signature as a permission to * do an action. * If the signature is from one of the authorized signer addresses, the * signature is valid. * Note that SignatureBouncer offers no protection against replay attacks, users * must add this themselves! * * Signer addresses can be individual servers signing grants or different * users within a decentralized club that have permission to invite other * members. This technique is useful for whitelists and airdrops; instead of * putting all valid addresses on-chain, simply sign a grant of the form * keccak256(abi.encodePacked(`:contractAddress` + `:granteeAddress`)) using a * valid signer address. * Then restrict access to your crowdsale/whitelist/airdrop using the * `onlyValidSignature` modifier (or implement your own using _isValidSignature). * In addition to `onlyValidSignature`, `onlyValidSignatureAndMethod` and * `onlyValidSignatureAndData` can be used to restrict access to only a given * method or a given method with given parameters respectively. * See the tests in SignatureBouncer.test.js for specific usage examples. * * @notice A method that uses the `onlyValidSignatureAndData` modifier must make * the _signature parameter the "last" parameter. You cannot sign a message that * has its own signature in it so the last 128 bytes of msg.data (which * represents the length of the _signature data and the _signaature data itself) * is ignored when validating. Also non fixed sized parameters make constructing * the data in the signature much more complex. * See https://ethereum.stackexchange.com/a/50616 for more details. */ contract SignatureBouncer is SignerRole { using ECDSA for bytes32; // Function selectors are 4 bytes long, as documented in // https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector uint256 private constant _METHOD_ID_SIZE = 4; // Signature size is 65 bytes (tightly packed v + r + s), but gets padded to 96 bytes uint256 private constant _SIGNATURE_SIZE = 96; constructor () internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev requires that a valid signature of a signer was provided */ modifier onlyValidSignature(bytes memory signature) { require(_isValidSignature(msg.sender, signature)); _; } /** * @dev requires that a valid signature with a specifed method of a signer was provided */ modifier onlyValidSignatureAndMethod(bytes memory signature) { require(_isValidSignatureAndMethod(msg.sender, signature)); _; } /** * @dev requires that a valid signature with a specifed method and params of a signer was provided */ modifier onlyValidSignatureAndData(bytes memory signature) { require(_isValidSignatureAndData(msg.sender, signature)); _; } /** * @dev is the signature of `this + sender` from a signer? * @return bool */ function _isValidSignature(address account, bytes memory signature) internal view returns (bool) { return _isValidDataHash(keccak256(abi.encodePacked(address(this), account)), signature); } /** * @dev is the signature of `this + sender + methodId` from a signer? * @return bool */ function _isValidSignatureAndMethod(address account, bytes memory signature) internal view returns (bool) { bytes memory data = new bytes(_METHOD_ID_SIZE); for (uint i = 0; i < data.length; i++) { data[i] = msg.data[i]; } return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature); } /** * @dev is the signature of `this + sender + methodId + params(s)` from a signer? * @notice the signature parameter of the method being validated must be the "last" parameter * @return bool */ function _isValidSignatureAndData(address account, bytes memory signature) internal view returns (bool) { require(msg.data.length > _SIGNATURE_SIZE); bytes memory data = new bytes(msg.data.length - _SIGNATURE_SIZE); for (uint i = 0; i < data.length; i++) { data[i] = msg.data[i]; } return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature); } /** * @dev internal function to convert a hash to an eth signed message * and then recover the signature and check it against the signer role * @return bool */ function _isValidDataHash(bytes32 hash, bytes memory signature) internal view returns (bool) { address signer = hash.toEthSignedMessageHash().recover(signature); return signer != address(0) && isSigner(signer); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.0; /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @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); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return 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 OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/misc/DutchAuction.sol pragma solidity ^0.5.0; /// @title Dutch auction contract - distribution of XRT tokens using an auction. /// @author Stefan George - <[email protected]> /// @author Airalab - <[email protected]> contract DutchAuction is SignatureBouncer, Ownable { using SafeERC20 for ERC20Burnable; /* * Events */ event BidSubmission(address indexed sender, uint256 amount); /* * Constants */ uint constant public WAITING_PERIOD = 0; // 1 days; /* * Storage */ ERC20Burnable public token; address public ambix; address payable public wallet; uint public maxTokenSold; uint public ceiling; uint public priceFactor; uint public startBlock; uint public endTime; uint public totalReceived; uint public finalPrice; mapping (address => uint) public bids; Stages public stage; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, TradingStarted } /* * Modifiers */ modifier atStage(Stages _stage) { // Contract on stage require(stage == _stage); _; } modifier isValidPayload() { require(msg.data.length == 4 || msg.data.length == 164); _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice()) finalizeAuction(); if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD) stage = Stages.TradingStarted; _; } /* * Public functions */ /// @dev Contract constructor function sets owner. /// @param _wallet Multisig wallet. /// @param _maxTokenSold Auction token balance. /// @param _ceiling Auction ceiling. /// @param _priceFactor Auction price factor. constructor(address payable _wallet, uint _maxTokenSold, uint _ceiling, uint _priceFactor) public { require(_wallet != address(0) && _ceiling > 0 && _priceFactor > 0); wallet = _wallet; maxTokenSold = _maxTokenSold; ceiling = _ceiling; priceFactor = _priceFactor; stage = Stages.AuctionDeployed; } /// @dev Setup function sets external contracts' addresses. /// @param _token Token address. /// @param _ambix Distillation cube address. function setup(ERC20Burnable _token, address _ambix) public onlyOwner atStage(Stages.AuctionDeployed) { // Validate argument require(_token != ERC20Burnable(0) && _ambix != address(0)); token = _token; ambix = _ambix; // Validate token balance require(token.balanceOf(address(this)) == maxTokenSold); stage = Stages.AuctionSetUp; } /// @dev Starts auction and sets startBlock. function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) { stage = Stages.AuctionStarted; startBlock = block.number; } /// @dev Calculates current token price. /// @return Returns token price. function calcCurrentTokenPrice() public timedTransitions returns (uint) { if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted) return finalPrice; return calcTokenPrice(); } /// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet. /// @return Returns current auction stage. function updateStage() public timedTransitions returns (Stages) { return stage; } /// @dev Allows to send a bid to the auction. /// @param signature KYC approvement function bid(bytes calldata signature) external payable isValidPayload timedTransitions atStage(Stages.AuctionStarted) onlyValidSignature(signature) returns (uint amount) { require(msg.value > 0); amount = msg.value; address payable receiver = msg.sender; // Prevent that more than 90% of tokens are sold. Only relevant if cap not reached. uint maxWei = maxTokenSold * calcTokenPrice() / 10**9 - totalReceived; uint maxWeiBasedOnTotalReceived = ceiling - totalReceived; if (maxWeiBasedOnTotalReceived < maxWei) maxWei = maxWeiBasedOnTotalReceived; // Only invest maximum possible amount. if (amount > maxWei) { amount = maxWei; // Send change back to receiver address. receiver.transfer(msg.value - amount); } // Forward funding to ether wallet (bool success,) = wallet.call.value(amount)(""); require(success); bids[receiver] += amount; totalReceived += amount; emit BidSubmission(receiver, amount); // Finalize auction when maxWei reached if (amount == maxWei) finalizeAuction(); } /// @dev Claims tokens for bidder after auction. function claimTokens() public isValidPayload timedTransitions atStage(Stages.TradingStarted) { address receiver = msg.sender; uint tokenCount = bids[receiver] * 10**9 / finalPrice; bids[receiver] = 0; token.safeTransfer(receiver, tokenCount); } /// @dev Calculates stop price. /// @return Returns stop price. function calcStopPrice() view public returns (uint) { return totalReceived * 10**9 / maxTokenSold + 1; } /// @dev Calculates token price. /// @return Returns token price. function calcTokenPrice() view public returns (uint) { return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1; } /* * Private functions */ function finalizeAuction() private { stage = Stages.AuctionEnded; finalPrice = totalReceived == ceiling ? calcTokenPrice() : calcStopPrice(); uint soldTokens = totalReceived * 10**9 / finalPrice; if (totalReceived == ceiling) { // Auction contract transfers all unsold tokens to Ambix contract token.safeTransfer(ambix, maxTokenSold - soldTokens); } else { // Auction contract burn all unsold tokens token.burn(maxTokenSold - soldTokens); } endTime = now; } } // File: contracts/misc/SharedCode.sol pragma solidity ^0.5.0; // Inspired by https://github.com/GNSPS/2DProxy library SharedCode { /** * @dev Create tiny proxy without constructor * @param _shared Shared code contract address */ function proxy(address _shared) internal returns (address instance) { bytes memory code = abi.encodePacked( hex"603160008181600b9039f3600080808080368092803773", _shared, hex"5af43d828181803e808314603057f35bfd" ); assembly { instance := create(0, add(code, 0x20), 60) if iszero(extcodesize(instance)) { revert(0, 0) } } } } // File: contracts/robonomics/interface/ILiability.sol pragma solidity ^0.5.0; /** * @title Standard liability smart contract interface */ contract ILiability { /** * @dev Liability termination signal */ event Finalized(bool indexed success, bytes result); /** * @dev Behaviour model multihash */ bytes public model; /** * @dev Objective ROSBAG multihash * @notice ROSBAGv2 is used: http://wiki.ros.org/Bags/Format/2.0 */ bytes public objective; /** * @dev Report ROSBAG multihash * @notice ROSBAGv2 is used: http://wiki.ros.org/Bags/Format/2.0 */ bytes public result; /** * @dev Payment token address */ address public token; /** * @dev Liability cost */ uint256 public cost; /** * @dev Lighthouse fee in wn */ uint256 public lighthouseFee; /** * @dev Validator fee in wn */ uint256 public validatorFee; /** * @dev Robonomics demand message hash */ bytes32 public demandHash; /** * @dev Robonomics offer message hash */ bytes32 public offerHash; /** * @dev Liability promisor address */ address public promisor; /** * @dev Liability promisee address */ address public promisee; /** * @dev Lighthouse assigned to this liability */ address public lighthouse; /** * @dev Liability validator address */ address public validator; /** * @dev Liability success flag */ bool public isSuccess; /** * @dev Liability finalization status flag */ bool public isFinalized; /** * @dev Deserialize robonomics demand message * @notice It can be called by factory only */ function demand( bytes calldata _model, bytes calldata _objective, address _token, uint256 _cost, address _lighthouse, address _validator, uint256 _validator_fee, uint256 _deadline, address _sender, bytes calldata _signature ) external returns (bool); /** * @dev Deserialize robonomics offer message * @notice It can be called by factory only */ function offer( bytes calldata _model, bytes calldata _objective, address _token, uint256 _cost, address _validator, address _lighthouse, uint256 _lighthouse_fee, uint256 _deadline, address _sender, bytes calldata _signature ) external returns (bool); /** * @dev Finalize liability contract * @param _result Result data hash * @param _success Set 'true' when liability has success result * @param _signature Result signature: liability address, result and success flag signed by promisor * @notice It can be called by assigned lighthouse only */ function finalize( bytes calldata _result, bool _success, bytes calldata _signature ) external returns (bool); } // File: contracts/robonomics/interface/ILighthouse.sol pragma solidity ^0.5.0; /** * @title Robonomics lighthouse contract interface */ contract ILighthouse { /** * @dev Provider going online */ event Online(address indexed provider); /** * @dev Provider going offline */ event Offline(address indexed provider); /** * @dev Active robonomics provider */ event Current(address indexed provider, uint256 indexed quota); /** * @dev Robonomics providers list */ address[] public providers; /** * @dev Count of robonomics providers on this lighthouse */ function providersLength() public view returns (uint256) { return providers.length; } /** * @dev Provider stake distribution */ mapping(address => uint256) public stakes; /** * @dev Minimal stake to get one quota */ uint256 public minimalStake; /** * @dev Silence timeout for provider in blocks */ uint256 public timeoutInBlocks; /** * @dev Block number of last transaction from current provider */ uint256 public keepAliveBlock; /** * @dev Round robin provider list marker */ uint256 public marker; /** * @dev Current provider quota */ uint256 public quota; /** * @dev Get quota of provider */ function quotaOf(address _provider) public view returns (uint256) { return stakes[_provider] / minimalStake; } /** * @dev Increase stake and get more quota, * one quota - one transaction in round * @param _value in wn * @notice XRT should be approved before call this */ function refill(uint256 _value) external returns (bool); /** * @dev Decrease stake and get XRT back * @param _value in wn */ function withdraw(uint256 _value) external returns (bool); /** * @dev Create liability smart contract assigned to this lighthouse * @param _demand ABI-encoded demand message * @param _offer ABI-encoded offer message * @notice Only current provider can call it */ function createLiability( bytes calldata _demand, bytes calldata _offer ) external returns (bool); /** * @dev Finalize liability smart contract assigned to this lighthouse * @param _liability smart contract address * @param _result report of work * @param _success work success flag * @param _signature work signature */ function finalizeLiability( address _liability, bytes calldata _result, bool _success, bytes calldata _signature ) external returns (bool); } // File: contracts/robonomics/interface/IFactory.sol pragma solidity ^0.5.0; /** * @title Robonomics liability factory interface */ contract IFactory { /** * @dev New liability created */ event NewLiability(address indexed liability); /** * @dev New lighthouse created */ event NewLighthouse(address indexed lighthouse, string name); /** * @dev Lighthouse address mapping */ mapping(address => bool) public isLighthouse; /** * @dev Nonce accounting */ mapping(address => uint256) public nonceOf; /** * @dev Total GAS utilized by Robonomics network */ uint256 public totalGasConsumed = 0; /** * @dev GAS utilized by liability contracts */ mapping(address => uint256) public gasConsumedOf; /** * @dev The count of consumed gas for switch to next epoch */ uint256 public constant gasEpoch = 347 * 10**10; /** * @dev Current gas price in wei */ uint256 public gasPrice = 10 * 10**9; /** * @dev XRT emission value for consumed gas * @param _gas Gas consumed by robonomics program */ function wnFromGas(uint256 _gas) public view returns (uint256); /** * @dev Create lighthouse smart contract * @param _minimalStake Minimal stake value of XRT token (one quota price) * @param _timeoutInBlocks Max time of lighthouse silence in blocks * @param _name Lighthouse name, * example: 'my-name' will create 'my-name.lighthouse.4.robonomics.eth' domain */ function createLighthouse( uint256 _minimalStake, uint256 _timeoutInBlocks, string calldata _name ) external returns (ILighthouse); /** * @dev Create robot liability smart contract * @param _demand ABI-encoded demand message * @param _offer ABI-encoded offer message * @notice This method is for lighthouse contract use only */ function createLiability( bytes calldata _demand, bytes calldata _offer ) external returns (ILiability); /** * @dev Is called after liability creation * @param _liability Liability contract address * @param _start_gas Transaction start gas level * @notice This method is for lighthouse contract use only */ function liabilityCreated(ILiability _liability, uint256 _start_gas) external returns (bool); /** * @dev Is called after liability finalization * @param _liability Liability contract address * @param _start_gas Transaction start gas level * @notice This method is for lighthouse contract use only */ function liabilityFinalized(ILiability _liability, uint256 _start_gas) external returns (bool); } // File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol pragma solidity ^0.5.0; contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol pragma solidity ^0.5.0; /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/robonomics/XRT.sol pragma solidity ^0.5.0; contract XRT is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor(uint256 _initial_supply) public ERC20Detailed("Robonomics", "XRT", 9) { _mint(msg.sender, _initial_supply); } } // File: contracts/robonomics/Lighthouse.sol pragma solidity ^0.5.0; contract Lighthouse is ILighthouse { using SafeERC20 for XRT; IFactory public factory; XRT public xrt; function setup(XRT _xrt, uint256 _minimalStake, uint256 _timeoutInBlocks) external returns (bool) { require(factory == IFactory(0) && _minimalStake > 0 && _timeoutInBlocks > 0); minimalStake = _minimalStake; timeoutInBlocks = _timeoutInBlocks; factory = IFactory(msg.sender); xrt = _xrt; return true; } /** * @dev Providers index, started from 1 */ mapping(address => uint256) public indexOf; function refill(uint256 _value) external returns (bool) { xrt.safeTransferFrom(msg.sender, address(this), _value); if (stakes[msg.sender] == 0) { require(_value >= minimalStake); providers.push(msg.sender); indexOf[msg.sender] = providers.length; emit Online(msg.sender); } stakes[msg.sender] += _value; return true; } function withdraw(uint256 _value) external returns (bool) { require(stakes[msg.sender] >= _value); stakes[msg.sender] -= _value; xrt.safeTransfer(msg.sender, _value); // Drop member with zero quota if (quotaOf(msg.sender) == 0) { uint256 balance = stakes[msg.sender]; stakes[msg.sender] = 0; xrt.safeTransfer(msg.sender, balance); uint256 senderIndex = indexOf[msg.sender] - 1; uint256 lastIndex = providers.length - 1; if (senderIndex < lastIndex) providers[senderIndex] = providers[lastIndex]; providers.length -= 1; indexOf[msg.sender] = 0; emit Offline(msg.sender); } return true; } function keepAliveTransaction() internal { if (timeoutInBlocks < block.number - keepAliveBlock) { // Set up the marker according to provider index marker = indexOf[msg.sender]; // Thransaction sender should be a registered provider require(marker > 0 && marker <= providers.length); // Allocate new quota quota = quotaOf(providers[marker - 1]); // Current provider signal emit Current(providers[marker - 1], quota); } // Store transaction sending block keepAliveBlock = block.number; } function quotedTransaction() internal { // Don't premit transactions without providers on board require(providers.length > 0); // Zero quota guard // XXX: When quota for some reasons is zero, DoS will be preverted by keepalive transaction require(quota > 0); // Only provider with marker can to send transaction require(msg.sender == providers[marker - 1]); // Consume one quota for transaction sending if (quota > 1) { quota -= 1; } else { // Step over marker marker = marker % providers.length + 1; // Allocate new quota quota = quotaOf(providers[marker - 1]); // Current provider signal emit Current(providers[marker - 1], quota); } } function startGas() internal view returns (uint256 gas) { // the total amount of gas the tx is DataFee + TxFee + ExecutionGas // ExecutionGas gas = gasleft(); // TxFee gas += 21000; // DataFee for (uint256 i = 0; i < msg.data.length; ++i) gas += msg.data[i] == 0 ? 4 : 68; } function createLiability( bytes calldata _demand, bytes calldata _offer ) external returns (bool) { // Gas with estimation error uint256 gas = startGas() + 5292; keepAliveTransaction(); quotedTransaction(); ILiability liability = factory.createLiability(_demand, _offer); require(liability != ILiability(0)); require(factory.liabilityCreated(liability, gas - gasleft())); return true; } function finalizeLiability( address _liability, bytes calldata _result, bool _success, bytes calldata _signature ) external returns (bool) { // Gas with estimation error uint256 gas = startGas() + 23363; keepAliveTransaction(); quotedTransaction(); ILiability liability = ILiability(_liability); require(factory.gasConsumedOf(_liability) > 0); require(liability.finalize(_result, _success, _signature)); require(factory.liabilityFinalized(liability, gas - gasleft())); return true; } } // File: contracts/robonomics/interface/IValidator.sol pragma solidity ^0.5.0; /** * @dev Observing network contract interface */ contract IValidator { /** * @dev Be sure than address is really validator * @return true when validator address in argument */ function isValidator(address _validator) external returns (bool); } // File: contracts/robonomics/Liability.sol pragma solidity ^0.5.0; contract Liability is ILiability { using ECDSA for bytes32; using SafeERC20 for XRT; using SafeERC20 for ERC20; address public factory; XRT public xrt; function setup(XRT _xrt) external returns (bool) { require(factory == address(0)); factory = msg.sender; xrt = _xrt; return true; } function demand( bytes calldata _model, bytes calldata _objective, address _token, uint256 _cost, address _lighthouse, address _validator, uint256 _validator_fee, uint256 _deadline, address _sender, bytes calldata _signature ) external returns (bool) { require(msg.sender == factory); require(block.number < _deadline); model = _model; objective = _objective; token = _token; cost = _cost; lighthouse = _lighthouse; validator = _validator; validatorFee = _validator_fee; demandHash = keccak256(abi.encodePacked( _model , _objective , _token , _cost , _lighthouse , _validator , _validator_fee , _deadline , IFactory(factory).nonceOf(_sender) , _sender )); promisee = demandHash .toEthSignedMessageHash() .recover(_signature); require(promisee == _sender); return true; } function offer( bytes calldata _model, bytes calldata _objective, address _token, uint256 _cost, address _validator, address _lighthouse, uint256 _lighthouse_fee, uint256 _deadline, address _sender, bytes calldata _signature ) external returns (bool) { require(msg.sender == factory); require(block.number < _deadline); require(keccak256(model) == keccak256(_model)); require(keccak256(objective) == keccak256(_objective)); require(_token == token); require(_cost == cost); require(_lighthouse == lighthouse); require(_validator == validator); lighthouseFee = _lighthouse_fee; offerHash = keccak256(abi.encodePacked( _model , _objective , _token , _cost , _validator , _lighthouse , _lighthouse_fee , _deadline , IFactory(factory).nonceOf(_sender) , _sender )); promisor = offerHash .toEthSignedMessageHash() .recover(_signature); require(promisor == _sender); return true; } function finalize( bytes calldata _result, bool _success, bytes calldata _signature ) external returns (bool) { require(msg.sender == lighthouse); require(!isFinalized); isFinalized = true; result = _result; isSuccess = _success; address resultSender = keccak256(abi.encodePacked(this, _result, _success)) .toEthSignedMessageHash() .recover(_signature); if (validator == address(0)) { require(resultSender == promisor); } else { require(IValidator(validator).isValidator(resultSender)); // Transfer validator fee when is set if (validatorFee > 0) xrt.safeTransfer(validator, validatorFee); } if (cost > 0) ERC20(token).safeTransfer(isSuccess ? promisor : promisee, cost); emit Finalized(isSuccess, result); return true; } } // File: contracts/robonomics/Factory.sol pragma solidity ^0.5.0; contract Factory is IFactory, SingletonHash { constructor( address _liability, address _lighthouse, DutchAuction _auction, AbstractENS _ens, XRT _xrt ) public { liabilityCode = _liability; lighthouseCode = _lighthouse; auction = _auction; ens = _ens; xrt = _xrt; } address public liabilityCode; address public lighthouseCode; using SafeERC20 for XRT; using SafeERC20 for ERC20; using SharedCode for address; /** * @dev Robonomics dutch auction contract */ DutchAuction public auction; /** * @dev Ethereum name system */ AbstractENS public ens; /** * @dev Robonomics network protocol token */ XRT public xrt; /** * @dev SMMA filter with function: SMMA(i) = (SMMA(i-1)*(n-1) + PRICE(i)) / n * @param _prePrice PRICE[n-1] * @param _price PRICE[n] * @return filtered price */ function smma(uint256 _prePrice, uint256 _price) internal pure returns (uint256) { return (_prePrice * (smmaPeriod - 1) + _price) / smmaPeriod; } /** * @dev SMMA filter period */ uint256 private constant smmaPeriod = 1000; /** * @dev XRT emission value for utilized gas */ function wnFromGas(uint256 _gas) public view returns (uint256) { // Just return wn=gas when auction isn't finish if (auction.finalPrice() == 0) return _gas; // Current gas utilization epoch uint256 epoch = totalGasConsumed / gasEpoch; // XRT emission with addition coefficient by gas utilzation epoch uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice(); // Check to not permit emission decrease below wn=gas return wn < _gas ? _gas : wn; } modifier onlyLighthouse { require(isLighthouse[msg.sender]); _; } modifier gasPriceEstimate { gasPrice = smma(gasPrice, tx.gasprice); _; } function createLighthouse( uint256 _minimalStake, uint256 _timeoutInBlocks, string calldata _name ) external returns (ILighthouse lighthouse) { bytes32 LIGHTHOUSE_NODE // lighthouse.5.robonomics.eth = 0x8d6c004b56cbe83bbfd9dcbd8f45d1f76398267bbb130a4629d822abc1994b96; bytes32 hname = keccak256(bytes(_name)); // Name reservation check bytes32 subnode = keccak256(abi.encodePacked(LIGHTHOUSE_NODE, hname)); require(ens.resolver(subnode) == address(0)); // Create lighthouse lighthouse = ILighthouse(lighthouseCode.proxy()); require(Lighthouse(address(lighthouse)).setup(xrt, _minimalStake, _timeoutInBlocks)); emit NewLighthouse(address(lighthouse), _name); isLighthouse[address(lighthouse)] = true; // Register subnode ens.setSubnodeOwner(LIGHTHOUSE_NODE, hname, address(this)); // Register lighthouse address AbstractResolver resolver = AbstractResolver(ens.resolver(LIGHTHOUSE_NODE)); ens.setResolver(subnode, address(resolver)); resolver.setAddr(subnode, address(lighthouse)); } function createLiability( bytes calldata _demand, bytes calldata _offer ) external onlyLighthouse returns (ILiability liability) { // Create liability liability = ILiability(liabilityCode.proxy()); require(Liability(address(liability)).setup(xrt)); emit NewLiability(address(liability)); // Parse messages (bool success, bytes memory returnData) = address(liability).call(abi.encodePacked(bytes4(0x48a984e4), _demand)); // liability.demand(...) require(success); singletonHash(liability.demandHash()); nonceOf[liability.promisee()] += 1; (success, returnData) = address(liability).call(abi.encodePacked(bytes4(0x413781d2), _offer)); // liability.offer(...) require(success); singletonHash(liability.offerHash()); nonceOf[liability.promisor()] += 1; // Check lighthouse require(isLighthouse[liability.lighthouse()]); // Transfer lighthouse fee to lighthouse worker directly if (liability.lighthouseFee() > 0) xrt.safeTransferFrom(liability.promisor(), tx.origin, liability.lighthouseFee()); // Transfer liability security and hold on contract ERC20 token = ERC20(liability.token()); if (liability.cost() > 0) token.safeTransferFrom(liability.promisee(), address(liability), liability.cost()); // Transfer validator fee and hold on contract if (liability.validator() != address(0) && liability.validatorFee() > 0) xrt.safeTransferFrom(liability.promisee(), address(liability), liability.validatorFee()); } function liabilityCreated( ILiability _liability, uint256 _gas ) external onlyLighthouse gasPriceEstimate returns (bool) { address liability = address(_liability); totalGasConsumed += _gas; gasConsumedOf[liability] += _gas; return true; } function liabilityFinalized( ILiability _liability, uint256 _gas ) external onlyLighthouse gasPriceEstimate returns (bool) { address liability = address(_liability); totalGasConsumed += _gas; gasConsumedOf[liability] += _gas; require(xrt.mint(tx.origin, wnFromGas(gasConsumedOf[liability]))); return true; } }
Set up the marker according to provider index Thransaction sender should be a registered provider Allocate new quota Current provider signal
function keepAliveTransaction() internal { if (timeoutInBlocks < block.number - keepAliveBlock) { marker = indexOf[msg.sender]; require(marker > 0 && marker <= providers.length); quota = quotaOf(providers[marker - 1]); emit Current(providers[marker - 1], quota); } }
12,972,902
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; library SafeMath { function ADD388(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB906(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB906(a, b, "SafeMath: subtraction overflow"); } function SUB906(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL601(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV456(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV456(a, b, "SafeMath: division by zero"); } function DIV456(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING 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 MOD78(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD78(a, b, "SafeMath: modulo by zero"); } function MOD78(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _MSGSENDER877() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA207() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER734(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE429(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL956(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/utils/Address.sol library Address { function ISCONTRACT600(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function SENDVALUE944(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function FUNCTIONCALL15(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL15(target, data, "Address: low-level call failed"); } function FUNCTIONCALL15(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE358(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE499(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE499(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE358(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE358(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT600(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/token/ERC20/ERC20.sol contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function NAME254() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL669() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS84() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function TOTALSUPPLY738() public view override returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF68(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER734(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(_MSGSENDER877(), recipient, amount); return true; } function ALLOWANCE35(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE429(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, amount); return true; } function TRANSFERFROM531(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING _TRANSFER67(sender, recipient, amount); _APPROVE455(sender, _MSGSENDER877(), _allowances[sender][_MSGSENDER877()].SUB906(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE275(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].ADD388(addedValue)); return true; } function DECREASEALLOWANCE402(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING _APPROVE455(_MSGSENDER877(), spender, _allowances[_MSGSENDER877()][spender].SUB906(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER67(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER81(sender, recipient, amount); _balances[sender] = _balances[sender].SUB906(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD388(amount); emit TRANSFER657(sender, recipient, amount); } function _MINT823(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER81(address(0), account, amount); _totalSupply = _totalSupply.ADD388(amount); _balances[account] = _balances[account].ADD388(amount); emit TRANSFER657(address(0), account, amount); } function _BURN465(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER81(account, address(0), amount); _balances[account] = _balances[account].SUB906(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB906(amount); emit TRANSFER657(account, address(0), amount); } function _APPROVE455(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL956(owner, spender, amount); } function _SETUPDECIMALS854(uint8 decimals_) internal { //inject NONSTANDARD NAMING _decimals = decimals_; } function _BEFORETOKENTRANSFER81(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER331(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFER734.selector, to, value)); } function SAFETRANSFERFROM748(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.TRANSFERFROM531.selector, from, to, value)); } function SAFEAPPROVE284(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE35(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, value)); } function SAFEINCREASEALLOWANCE243(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).ADD388(value); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE653(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE35(address(this), spender).SUB906(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN31(token, abi.encodeWithSelector(token.APPROVE429.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN31(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. 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).FUNCTIONCALL15(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface IVault is IERC20 { function TOKEN190() external view returns (address); //inject NONSTANDARD NAMING function DECIMALS84() external view returns (uint8); //inject NONSTANDARD NAMING function EARN763() external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256) external; //inject NONSTANDARD NAMING function DEPOSITALL187() external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL63() external; //inject NONSTANDARD NAMING function DISTRIBUTE67() external; //inject NONSTANDARD NAMING function SALVAGE929(address, uint256) external; //inject NONSTANDARD NAMING function GETRATIO675() external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_2 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[2] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[2] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[2] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurve3Pool { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[3] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[3] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[3] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(uint256) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveFi_4 { function GET_VIRTUAL_PRICE809() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY50(uint256[4] calldata amounts, uint256 min_mint_amount) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 max_burn_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata amounts) //inject NONSTANDARD NAMING external; function EXCHANGE792( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function BALANCES2(int128) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveZap_4 { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY517(uint256 _amount, uint256[4] calldata min_uamounts) //inject NONSTANDARD NAMING external; function REMOVE_LIQUIDITY_IMBALANCE11( //inject NONSTANDARD NAMING uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function CALC_WITHDRAW_ONE_COIN560(uint256 _token_amount, int128 i) //inject NONSTANDARD NAMING external returns (uint256); function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function WITHDRAW_DONATED_DUST417() external; //inject NONSTANDARD NAMING function COINS352(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function UNDERLYING_COINS1(int128 arg0) external returns (address); //inject NONSTANDARD NAMING function CURVE335() external returns (address); //inject NONSTANDARD NAMING function TOKEN190() external returns (address); //inject NONSTANDARD NAMING } interface ICurveZap { function REMOVE_LIQUIDITY_ONE_COIN125( //inject NONSTANDARD NAMING uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function DEPOSIT115(uint256 _value) external; //inject NONSTANDARD NAMING function DEPOSIT115(uint256 _value, address addr) external; //inject NONSTANDARD NAMING function BALANCEOF68(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value) external; //inject NONSTANDARD NAMING function WITHDRAW593(uint256 _value, bool claim_rewards) external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING function CLAIM_REWARDS536(address addr) external; //inject NONSTANDARD NAMING function CLAIMABLE_TOKENS440(address addr) external returns (uint256); //inject NONSTANDARD NAMING function CLAIMABLE_REWARD978(address addr) external view returns (uint256); //inject NONSTANDARD NAMING function INTEGRATE_FRACTION797(address arg0) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveMintr { function MINT951(address) external; //inject NONSTANDARD NAMING function MINTED257(address arg0, address arg1) external view returns (uint256); //inject NONSTANDARD NAMING } interface ICurveVotingEscrow { function LOCKED178(address arg0) //inject NONSTANDARD NAMING external view returns (int128 amount, uint256 end); function LOCKED__END474(address _addr) external view returns (uint256); //inject NONSTANDARD NAMING function CREATE_LOCK305(uint256, uint256) external; //inject NONSTANDARD NAMING function INCREASE_AMOUNT922(uint256) external; //inject NONSTANDARD NAMING function INCREASE_UNLOCK_TIME38(uint256 _unlock_time) external; //inject NONSTANDARD NAMING function WITHDRAW593() external; //inject NONSTANDARD NAMING function SMART_WALLET_CHECKER846() external returns (address); //inject NONSTANDARD NAMING } interface ICurveSmartContractChecker { function WALLETS237(address) external returns (bool); //inject NONSTANDARD NAMING function APPROVEWALLET249(address _wallet) external; //inject NONSTANDARD NAMING } interface UniswapRouterV2 { function SWAPEXACTTOKENSFORTOKENS167( //inject NONSTANDARD NAMING uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function ADDLIQUIDITY947( //inject NONSTANDARD NAMING 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 ADDLIQUIDITYETH996( //inject NONSTANDARD NAMING address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function REMOVELIQUIDITY801( //inject NONSTANDARD NAMING address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function GETAMOUNTSOUT893(uint256 amountIn, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function GETAMOUNTSIN14(uint256 amountOut, address[] calldata path) //inject NONSTANDARD NAMING external view returns (uint256[] memory amounts); function SWAPETHFOREXACTTOKENS437( //inject NONSTANDARD NAMING uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function SWAPEXACTETHFORTOKENS898( //inject NONSTANDARD NAMING uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event APPROVAL956( //inject NONSTANDARD NAMING address indexed owner, address indexed spender, uint256 value ); event TRANSFER657(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING function NAME254() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL669() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS84() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY738() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE35(address owner, address spender) //inject NONSTANDARD NAMING external view returns (uint256); function APPROVE429(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER734(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM531( //inject NONSTANDARD NAMING address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR578() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH551() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES443(address owner) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT326( //inject NONSTANDARD NAMING address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event MINT405(address indexed sender, uint256 amount0, uint256 amount1); //inject NONSTANDARD NAMING event BURN673( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event SWAP227( //inject NONSTANDARD NAMING address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event SYNC504(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY881() external pure returns (uint256); //inject NONSTANDARD NAMING function FACTORY729() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0644() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1449() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES964() //inject NONSTANDARD NAMING external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function PRICE0CUMULATIVELAST588() external view returns (uint256); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST951() external view returns (uint256); //inject NONSTANDARD NAMING function KLAST390() external view returns (uint256); //inject NONSTANDARD NAMING function MINT951(address to) external returns (uint256 liquidity); //inject NONSTANDARD NAMING function BURN57(address to) //inject NONSTANDARD NAMING external returns (uint256 amount0, uint256 amount1); function SWAP519( //inject NONSTANDARD NAMING uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function SKIM366(address to) external; //inject NONSTANDARD NAMING function SYNC84() external; //inject NONSTANDARD NAMING } interface IUniswapV2Factory { event PAIRCREATED988( //inject NONSTANDARD NAMING address indexed token0, address indexed token1, address pair, uint256 ); function GETPAIR36(address tokenA, address tokenB) //inject NONSTANDARD NAMING external view returns (address pair); function ALLPAIRS303(uint256) external view returns (address pair); //inject NONSTANDARD NAMING function ALLPAIRSLENGTH195() external view returns (uint256); //inject NONSTANDARD NAMING function FEETO341() external view returns (address); //inject NONSTANDARD NAMING function FEETOSETTER863() external view returns (address); //inject NONSTANDARD NAMING function CREATEPAIR664(address tokenA, address tokenB) //inject NONSTANDARD NAMING external returns (address pair); } interface ICurveTBTC { function ADD_LIQUIDITY50( //inject NONSTANDARD NAMING uint256[4] calldata amounts, uint256 min_mint_amount ) external returns (uint256); } interface IKeepRewardsClaimable { function CLAIM_REWARDS536() external; //inject NONSTANDARD NAMING } // Base of all strategy contracts abstract contract VoxStrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees uint256 public treasuryFee = 1000; uint256 public constant treasuryfeemax584 = 2000; //inject NONSTANDARD NAMING uint256 public constant treasuryfeebase971 = 10000; //inject NONSTANDARD NAMING uint256 public strategyFee = 500; uint256 public constant strategyfeemax620 = 5000; //inject NONSTANDARD NAMING uint256 public constant strategyfeebase640 = 10000; //inject NONSTANDARD NAMING uint256 public developerFee = 250; uint256 public constant developerfeemax597 = 500; //inject NONSTANDARD NAMING uint256 public constant developerfeebase561 = 10000; //inject NONSTANDARD NAMING // Withdrawal fee uint256 public withdrawalFee = 15; uint256 public constant withdrawalfeemax274 = 15; //inject NONSTANDARD NAMING uint256 public constant withdrawalfeebase605 = 10000; //inject NONSTANDARD NAMING // Tokens address public underlying; address public constant weth339 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address public constant wbtc162 = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; //inject NONSTANDARD NAMING // User accounts address public governance; address public strategist; address public treasury; address public devfund; address public timelock; address public vault; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public { require(_underlying != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_treasury != address(0)); require(_devfund != address(0)); require(_timelock != address(0)); require(_vault != address(0)); underlying = _underlying; governance = _governance; strategist = _strategist; treasury = _treasury; devfund = _devfund; timelock = _timelock; vault = _vault; } // **** Modifiers **** // modifier RESTRICTED912 { //inject NONSTANDARD NAMING require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function BALANCEOFUNDERLYING222() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(underlying).BALANCEOF68(address(this)); } function BALANCEOFPOOL881() public virtual view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF68() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFUNDERLYING222().ADD388(BALANCEOFPOOL881()); } function GETNAME974() external virtual pure returns (string memory); //inject NONSTANDARD NAMING // **** Setters **** // function SETTREASURYFEE502(uint256 _treasuryFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); treasuryFee = _treasuryFee; } function SETSTRATEGYFEE761(uint256 _strategyFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); strategyFee = _strategyFee; } function SETDEVELOPERFEE113(uint256 _developerFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); developerFee = _developerFee; } function SETWITHDRAWALFEE980(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); withdrawalFee = _withdrawalFee; } function SETSTRATEGIST654(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETGOVERNANCE136(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETTREASURY187(address _treasury) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); treasury = _treasury; } function SETDEVFUND591(address _devfund) external { //inject NONSTANDARD NAMING require(msg.sender == devfund, "!devfund"); devfund = _devfund; } function SETTIMELOCK277(address _timelock) external { //inject NONSTANDARD NAMING require(msg.sender == timelock, "!timelock"); timelock = _timelock; } // **** State mutations **** // function DEPOSIT115() public virtual; //inject NONSTANDARD NAMING // Governance only function to salvage non-underlying assets function SALVAGE929(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); require(underlying != address(_asset), "underlying"); balance = _asset.BALANCEOF68(address(this)); _asset.SAFETRANSFER331(treasury, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW593(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == vault, "!vault"); uint256 _balance = IERC20(underlying).BALANCEOF68(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME235(_amount.SUB906(_balance)); _amount = _amount.ADD388(_balance); } uint256 _withdrawalFee = _amount.MUL601(withdrawalFee).DIV456(withdrawalfeebase605); IERC20(underlying).SAFETRANSFER331(treasury, _withdrawalFee); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, _amount.SUB906(_withdrawalFee)); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL63() external RESTRICTED912 returns (uint256 balance) { //inject NONSTANDARD NAMING _WITHDRAWALL78(); balance = IERC20(underlying).BALANCEOF68(address(this)); require(vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(underlying).SAFETRANSFER331(vault, balance); } function _WITHDRAWALL78() internal { //inject NONSTANDARD NAMING _WITHDRAWSOME235(BALANCEOFPOOL881()); } function _WITHDRAWSOME235(uint256 _amount) internal virtual returns (uint256); //inject NONSTANDARD NAMING function HARVEST372() public virtual; //inject NONSTANDARD NAMING function _DISTRIBUTEANDDEPOSIT388() internal { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { // Treasury fees IERC20(underlying).SAFETRANSFER331( treasury, _underlying.MUL601(treasuryFee).DIV456(treasuryfeebase971) ); // Strategy fee IERC20(underlying).SAFETRANSFER331( strategist, _underlying.MUL601(strategyFee).DIV456(strategyfeebase640) ); // Developer fee IERC20(underlying).SAFETRANSFER331( devfund, _underlying.MUL601(developerFee).DIV456(developerfeebase561) ); DEPOSIT115(); } } // **** Emergency functions **** function EXECUTE807(address _target, bytes memory _data) //inject NONSTANDARD NAMING public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _SWAPUNISWAP503( //inject NONSTANDARD NAMING address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).SAFEAPPROVE284(univ2Router2, 0); IERC20(_from).SAFEAPPROVE284(univ2Router2, _amount); address[] memory path; if (_from == weth339 || _to == weth339) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth339; path[2] = _to; } UniswapRouterV2(univ2Router2).SWAPEXACTTOKENSFORTOKENS167( _amount, 0, path, address(this), now.ADD388(60) ); } } // Base contract for Curve based vault strategies abstract contract VoxStrategyCurveBase is VoxStrategyBase { // curve dao address public curve; address public gauge; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // keep address public keep = 0x85Eee30c52B0b379b046Fb0F85F4f3Dc3009aFEC; address public keep_rewards = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _underlying, address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyBase(_underlying, _governance, _strategist, _treasury, _devfund, _timelock, _vault) { curve = _curve; gauge = _gauge; } // **** Getters **** function BALANCEOFPOOL881() public override view returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).BALANCEOF68(address(this)); } function GETHARVESTABLE58() external returns (uint256) { //inject NONSTANDARD NAMING return ICurveGauge(gauge).CLAIMABLE_TOKENS440(address(this)); } function GETMOSTPREMIUM814() public virtual view returns (address, uint256); //inject NONSTANDARD NAMING // **** Setters **** function SETKEEPCRV171(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function DEPOSIT115() public override { //inject NONSTANDARD NAMING uint256 _underlying = IERC20(underlying).BALANCEOF68(address(this)); if (_underlying > 0) { IERC20(underlying).SAFEAPPROVE284(gauge, 0); IERC20(underlying).SAFEAPPROVE284(gauge, _underlying); ICurveGauge(gauge).DEPOSIT115(_underlying); } } function _WITHDRAWSOME235(uint256 _amount) //inject NONSTANDARD NAMING internal override returns (uint256) { ICurveGauge(gauge).WITHDRAW593(_amount); return _amount; } } contract VoxStrategyCurveTBTC is VoxStrategyCurveBase { // Curve stuff address public tbtc_pool = 0xaa82ca713D94bBA7A89CEAB55314F9EfFEdDc78c; address public tbtc_gauge = 0x6828bcF74279eE32f2723eC536c22c51Eed383C6; address public tbtc_crv = 0x64eda51d3Ad40D56b9dFc5554E06F94e1Dd786Fd; // EVENTS event HARVESTED180(address indexed token, uint256 amount); //inject NONSTANDARD NAMING constructor( address _governance, address _strategist, address _treasury, address _devfund, address _timelock, address _vault ) public VoxStrategyCurveBase( tbtc_pool, tbtc_gauge, tbtc_crv, _governance, _strategist, _treasury, _devfund, _timelock, _vault ) {} // **** Views **** function GETMOSTPREMIUM814() //inject NONSTANDARD NAMING public override view returns (address, uint256) { return (wbtc162, 2); } function GETNAME974() external override pure returns (string memory) { //inject NONSTANDARD NAMING return "VoxStrategyCurveTBTC"; } // **** State Mutations **** function HARVEST372() public RESTRICTED912 override { //inject NONSTANDARD NAMING // bitcoin we want to convert to (address to, uint256 toIndex) = GETMOSTPREMIUM814(); // Collects crv tokens // this also sends KEEP to keep_rewards contract ICurveMintr(mintr).MINT951(gauge); uint256 _crv = IERC20(crv).BALANCEOF68(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.MUL601(keepCRV).DIV456(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).SAFETRANSFER331( treasury, _keepCRV ); } _crv = _crv.SUB906(_keepCRV); _SWAPUNISWAP503(crv, to, _crv); } // Collects keep tokens IKeepRewardsClaimable(keep_rewards).CLAIM_REWARDS536(); uint256 _keep = IERC20(keep).BALANCEOF68(address(this)); if (_keep > 0) { _SWAPUNISWAP503(keep, to, _keep); } // Adds liquidity to curve.fi's pool // to get back underlying (tbtccrv) uint256 _to = IERC20(to).BALANCEOF68(address(this)); if (_to > 0) { IERC20(to).SAFEAPPROVE284(curve, 0); IERC20(to).SAFEAPPROVE284(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveTBTC(curve).ADD_LIQUIDITY50(liquidity, 0); } // Distribute the collected funds and deposit underlying // Emit harvested event _DISTRIBUTEANDDEPOSIT388(); emit HARVESTED180(to, _to); } }
inject NONSTANDARD NAMING
function SUB906(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
12,568,859
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOGBYTES17699(bytes17 p0) internal view {
14,087,627
./partial_match/1/0x1473F3e4d236CBBe3412b9f65B4c210756BE2C0E/sources/src/FrxEthEthDualOracle.sol
first price second price
function _getPrices() internal view returns (bool isBadData, uint256 priceLow, uint256 priceHigh) { uint256 ethPerFrxEthCurveEma = getCurveEmaEthPerFrxEth(); uint256 fraxPerFrxEthTwap = _getUniswapV3Twap(); (bool isBadDataEthUsdChainlink, uint256 usdPerEthChainlink) = getUsdPerEthChainlink(); (bool isBadDataFraxUsdChainlink, uint256 usdPerFraxChainlink) = getChainlinkUsdPerFrax(); (isBadData, priceLow, priceHigh) = _calculatePrices({ ethPerFrxEthCurveEma: ethPerFrxEthCurveEma, fraxPerFrxEthTwap: fraxPerFrxEthTwap, isBadDataEthUsdChainlink: isBadDataEthUsdChainlink, usdPerEthChainlink: usdPerEthChainlink, isBadDataFraxUsdChainlink: isBadDataFraxUsdChainlink, usdPerFraxChainlink: usdPerFraxChainlink }); }
4,389,216
/** *Submitted for verification at Etherscan.io on 2019-09-24 */ pragma solidity >=0.4.21 <0.6.0; contract EventMetadata { address winner_TOD33; function play_TOD33(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD33 = msg.sender; } } function getReward_TOD33() payable public{ winner_TOD33.transfer(msg.value); } event MetadataSet(bytes metadata); // state functions function _setMetadata(bytes memory metadata) internal { emit MetadataSet(metadata); } bool claimed_TOD2 = false; address owner_TOD2; uint256 reward_TOD2; function setReward_TOD2() public payable { require (!claimed_TOD2); require(msg.sender == owner_TOD2); owner_TOD2.transfer(reward_TOD2); reward_TOD2 = msg.value; } function claimReward_TOD2(uint256 submission) public { require (!claimed_TOD2); require(submission < 10); msg.sender.transfer(reward_TOD2); claimed_TOD2 = true; } } contract Operated { bool claimed_TOD22 = false; address owner_TOD22; uint256 reward_TOD22; function setReward_TOD22() public payable { require (!claimed_TOD22); require(msg.sender == owner_TOD22); owner_TOD22.transfer(reward_TOD22); reward_TOD22 = msg.value; } function claimReward_TOD22(uint256 submission) public { require (!claimed_TOD22); require(submission < 10); msg.sender.transfer(reward_TOD22); claimed_TOD22 = true; } address private _operator; bool claimed_TOD12 = false; address owner_TOD12; uint256 reward_TOD12; function setReward_TOD12() public payable { require (!claimed_TOD12); require(msg.sender == owner_TOD12); owner_TOD12.transfer(reward_TOD12); reward_TOD12 = msg.value; } function claimReward_TOD12(uint256 submission) public { require (!claimed_TOD12); require(submission < 10); msg.sender.transfer(reward_TOD12); claimed_TOD12 = true; } bool private _status; address winner_TOD27; function play_TOD27(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD27 = msg.sender; } } function getReward_TOD27() payable public{ winner_TOD27.transfer(msg.value); } event OperatorUpdated(address operator, bool status); // state functions function _setOperator(address operator) internal { require(_operator != operator); _operator = operator; emit OperatorUpdated(operator, hasActiveOperator()); } address winner_TOD17; function play_TOD17(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD17 = msg.sender; } } function getReward_TOD17() payable public{ winner_TOD17.transfer(msg.value); } function _transferOperator(address operator) internal { // transferring operator-ship implies there was an operator set before this require(_operator != address(0)); _setOperator(operator); } address winner_TOD37; function play_TOD37(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD37 = msg.sender; } } function getReward_TOD37() payable public{ winner_TOD37.transfer(msg.value); } function _renounceOperator() internal { require(hasActiveOperator()); _operator = address(0); _status = false; emit OperatorUpdated(address(0), false); } address winner_TOD3; function play_TOD3(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD3 = msg.sender; } } function getReward_TOD3() payable public{ winner_TOD3.transfer(msg.value); } function _activateOperator() internal { require(!hasActiveOperator()); _status = true; emit OperatorUpdated(_operator, true); } address winner_TOD9; function play_TOD9(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD9 = msg.sender; } } function getReward_TOD9() payable public{ winner_TOD9.transfer(msg.value); } function _deactivateOperator() internal { require(hasActiveOperator()); _status = false; emit OperatorUpdated(_operator, false); } address winner_TOD25; function play_TOD25(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD25 = msg.sender; } } function getReward_TOD25() payable public{ winner_TOD25.transfer(msg.value); } // view functions function getOperator() public view returns (address operator) { operator = _operator; } address winner_TOD19; function play_TOD19(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD19 = msg.sender; } } function getReward_TOD19() payable public{ winner_TOD19.transfer(msg.value); } function isOperator(address caller) public view returns (bool ok) { return (caller == getOperator()); } bool claimed_TOD26 = false; address owner_TOD26; uint256 reward_TOD26; function setReward_TOD26() public payable { require (!claimed_TOD26); require(msg.sender == owner_TOD26); owner_TOD26.transfer(reward_TOD26); reward_TOD26 = msg.value; } function claimReward_TOD26(uint256 submission) public { require (!claimed_TOD26); require(submission < 10); msg.sender.transfer(reward_TOD26); claimed_TOD26 = true; } function hasActiveOperator() public view returns (bool ok) { return _status; } bool claimed_TOD20 = false; address owner_TOD20; uint256 reward_TOD20; function setReward_TOD20() public payable { require (!claimed_TOD20); require(msg.sender == owner_TOD20); owner_TOD20.transfer(reward_TOD20); reward_TOD20 = msg.value; } function claimReward_TOD20(uint256 submission) public { require (!claimed_TOD20); require(submission < 10); msg.sender.transfer(reward_TOD20); claimed_TOD20 = true; } function isActiveOperator(address caller) public view returns (bool ok) { return (isOperator(caller) && hasActiveOperator()); } bool claimed_TOD32 = false; address owner_TOD32; uint256 reward_TOD32; function setReward_TOD32() public payable { require (!claimed_TOD32); require(msg.sender == owner_TOD32); owner_TOD32.transfer(reward_TOD32); reward_TOD32 = msg.value; } function claimReward_TOD32(uint256 submission) public { require (!claimed_TOD32); require(submission < 10); msg.sender.transfer(reward_TOD32); claimed_TOD32 = true; } } /** * @title MultiHashWrapper * @dev Contract that handles multi hash data structures and encoding/decoding * Learn more here: https://github.com/multiformats/multihash */ contract MultiHashWrapper { // bytes32 hash first to fill the first storage slot struct MultiHash { bytes32 hash; uint8 hashFunction; uint8 digestSize; } /** * @dev Given a multihash struct, returns the full base58-encoded hash * @param multihash MultiHash struct that has the hashFunction, digestSize and the hash * @return the base58-encoded full hash */ function _combineMultiHash(MultiHash memory multihash) internal pure returns (bytes memory) { bytes memory out = new bytes(34); out[0] = byte(multihash.hashFunction); out[1] = byte(multihash.digestSize); uint8 i; for (i = 0; i < 32; i++) { out[i+2] = multihash.hash[i]; } return out; } bool claimed_TOD38 = false; address owner_TOD38; uint256 reward_TOD38; function setReward_TOD38() public payable { require (!claimed_TOD38); require(msg.sender == owner_TOD38); owner_TOD38.transfer(reward_TOD38); reward_TOD38 = msg.value; } function claimReward_TOD38(uint256 submission) public { require (!claimed_TOD38); require(submission < 10); msg.sender.transfer(reward_TOD38); claimed_TOD38 = true; } /** * @dev Given a base58-encoded hash, divides into its individual parts and returns a struct * @param source base58-encoded hash * @return MultiHash that has the hashFunction, digestSize and the hash */ function _splitMultiHash(bytes memory source) internal pure returns (MultiHash memory) { require(source.length == 34); uint8 hashFunction = uint8(source[0]); uint8 digestSize = uint8(source[1]); bytes32 hash; assembly { hash := mload(add(source, 34)) } return (MultiHash({ hashFunction: hashFunction, digestSize: digestSize, hash: hash })); } bool claimed_TOD4 = false; address owner_TOD4; uint256 reward_TOD4; function setReward_TOD4() public payable { require (!claimed_TOD4); require(msg.sender == owner_TOD4); owner_TOD4.transfer(reward_TOD4); reward_TOD4 = msg.value; } function claimReward_TOD4(uint256 submission) public { require (!claimed_TOD4); require(submission < 10); msg.sender.transfer(reward_TOD4); claimed_TOD4 = true; } } /* TODO: Update eip165 interface * bytes4(keccak256('create(bytes)')) == 0xcf5ba53f * bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf * bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904 * bytes4(keccak256('getImplementation()')) == 0xaaf10f42 * * => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6 */ interface iFactory { event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData); function create(bytes initData) external returns (address instance); function createSalty(bytes initData, bytes32 salt) external returns (address instance); function getInitSelector() external view returns (bytes4 initSelector); function getInstanceRegistry() external view returns (address instanceRegistry); function getTemplate() external view returns (address template); function getSaltyInstance(bytes , bytes32 salt) external view returns (address instance); function getNextInstance(bytes ) external view returns (address instance); function getInstanceCreator(address instance) external view returns (address creator); function getInstanceType() external view returns (bytes4 instanceType); function getInstanceCount() external view returns (uint256 count); function getInstance(uint256 index) external view returns (address instance); function getInstances() external view returns (address[] memory instances); function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances); } contract ProofHash is MultiHashWrapper { address winner_TOD11; function play_TOD11(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD11 = msg.sender; } } function getReward_TOD11() payable public{ winner_TOD11.transfer(msg.value); } MultiHash private _proofHash; address winner_TOD31; function play_TOD31(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD31 = msg.sender; } } function getReward_TOD31() payable public{ winner_TOD31.transfer(msg.value); } event ProofHashSet(address caller, bytes proofHash); // state functions function _setProofHash(bytes memory proofHash) internal { _proofHash = MultiHashWrapper._splitMultiHash(proofHash); emit ProofHashSet(msg.sender, proofHash); } address winner_TOD7; function play_TOD7(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD7 = msg.sender; } } function getReward_TOD7() payable public{ winner_TOD7.transfer(msg.value); } // view functions function getProofHash() public view returns (bytes memory proofHash) { proofHash = MultiHashWrapper._combineMultiHash(_proofHash); } address winner_TOD23; function play_TOD23(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD23 = msg.sender; } } function getReward_TOD23() payable public{ winner_TOD23.transfer(msg.value); } } contract Template { address winner_TOD1; function play_TOD1(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD1 = msg.sender; } } function getReward_TOD1() payable public{ winner_TOD1.transfer(msg.value); } address private _factory; // modifiers modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be delegatecalled from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0); _; } // view functions function getCreator() public view returns (address creator) { // iFactory(...) would revert if _factory address is not actually a factory contract creator = iFactory(_factory).getInstanceCreator(address(this)); } bool claimed_TOD14 = false; address owner_TOD14; uint256 reward_TOD14; function setReward_TOD14() public payable { require (!claimed_TOD14); require(msg.sender == owner_TOD14); owner_TOD14.transfer(reward_TOD14); reward_TOD14 = msg.value; } function claimReward_TOD14(uint256 submission) public { require (!claimed_TOD14); require(submission < 10); msg.sender.transfer(reward_TOD14); claimed_TOD14 = true; } function isCreator(address caller) public view returns (bool ok) { ok = (caller == getCreator()); } bool claimed_TOD30 = false; address owner_TOD30; uint256 reward_TOD30; function setReward_TOD30() public payable { require (!claimed_TOD30); require(msg.sender == owner_TOD30); owner_TOD30.transfer(reward_TOD30); reward_TOD30 = msg.value; } function claimReward_TOD30(uint256 submission) public { require (!claimed_TOD30); require(submission < 10); msg.sender.transfer(reward_TOD30); claimed_TOD30 = true; } function getFactory() public view returns (address factory) { factory = _factory; } bool claimed_TOD8 = false; address owner_TOD8; uint256 reward_TOD8; function setReward_TOD8() public payable { require (!claimed_TOD8); require(msg.sender == owner_TOD8); owner_TOD8.transfer(reward_TOD8); reward_TOD8 = msg.value; } function claimReward_TOD8(uint256 submission) public { require (!claimed_TOD8); require(submission < 10); msg.sender.transfer(reward_TOD8); claimed_TOD8 = true; } } contract Post is ProofHash, Operated, EventMetadata, Template { address winner_TOD13; function play_TOD13(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD13 = msg.sender; } } function getReward_TOD13() payable public{ winner_TOD13.transfer(msg.value); } event Initialized(address operator, bytes multihash, bytes metadata); function initialize( address operator, bytes memory multihash, bytes memory metadata ) public initializeTemplate() { // set storage variables if (multihash.length != 0) { ProofHash._setProofHash(multihash); } // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set metadata if (metadata.length != 0) { EventMetadata._setMetadata(metadata); } // log initialization params emit Initialized(operator, multihash, metadata); } address winner_TOD29; function play_TOD29(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD29 = msg.sender; } } function getReward_TOD29() payable public{ winner_TOD29.transfer(msg.value); } // state functions function setMetadata(bytes memory metadata) public { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender)); // set metadata EventMetadata._setMetadata(metadata); } bool claimed_TOD36 = false; address owner_TOD36; uint256 reward_TOD36; function setReward_TOD36() public payable { require (!claimed_TOD36); require(msg.sender == owner_TOD36); owner_TOD36.transfer(reward_TOD36); reward_TOD36 = msg.value; } function claimReward_TOD36(uint256 submission) public { require (!claimed_TOD36); require(submission < 10); msg.sender.transfer(reward_TOD36); claimed_TOD36 = true; } function transferOperator(address operator) public { // restrict access require(Operated.isActiveOperator(msg.sender)); // transfer operator Operated._transferOperator(operator); } address winner_TOD35; function play_TOD35(bytes32 guess) public{ if (keccak256((guess)) == keccak256(('hello'))) { winner_TOD35 = msg.sender; } } function getReward_TOD35() payable public{ winner_TOD35.transfer(msg.value); } function renounceOperator() public { // restrict access require(Operated.isActiveOperator(msg.sender)); // transfer operator Operated._renounceOperator(); } bool claimed_TOD40 = false; address owner_TOD40; uint256 reward_TOD40; function setReward_TOD40() public payable { require (!claimed_TOD40); require(msg.sender == owner_TOD40); owner_TOD40.transfer(reward_TOD40); reward_TOD40 = msg.value; } function claimReward_TOD40(uint256 submission) public { require (!claimed_TOD40); require(submission < 10); msg.sender.transfer(reward_TOD40); claimed_TOD40 = true; } }
iFactory(...) would revert if _factory address is not actually a factory contract
function getCreator() public view returns (address creator) { creator = iFactory(_factory).getInstanceCreator(address(this)); } bool claimed_TOD14 = false; address owner_TOD14; uint256 reward_TOD14;
1,080,645
pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF367(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER903(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE608(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function DECIMALS810() external view returns (uint); //inject NONSTANDARD NAMING function APPROVE172(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM529(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER904(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL612(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD483(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB518(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB518(a, b, "SafeMath: subtraction overflow"); } function SUB518(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL745(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV989(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV989(a, b, "SafeMath: division by zero"); } function DIV989(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD257(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD257(a, b, "SafeMath: modulo by zero"); } function MOD257(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT560(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } function TOPAYABLE228(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE839(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER392(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFER903.selector, to, value)); } function SAFETRANSFERFROM413(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.TRANSFERFROM529.selector, from, to, value)); } function SAFEAPPROVE740(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE608(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN815(token, abi.encodeWithSelector(token.APPROVE172.selector, spender, value)); } function CALLOPTIONALRETURN815(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT560(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface yVault { function BALANCE390() external view returns (uint); //inject NONSTANDARD NAMING function TOTALSUPPLY3() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF367(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEPOSITALL620() external; //inject NONSTANDARD NAMING function WITHDRAW88(uint _shares) external; //inject NONSTANDARD NAMING function WITHDRAWALL107() external; //inject NONSTANDARD NAMING } interface Controller { function VAULTS407(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES225(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS983() external view returns (address); //inject NONSTANDARD NAMING } interface Strategy { function WITHDRAWALFEE924() external view returns (uint); //inject NONSTANDARD NAMING } interface GemLike { function APPROVE172(address, uint) external; //inject NONSTANDARD NAMING function TRANSFER903(address, uint) external; //inject NONSTANDARD NAMING function TRANSFERFROM529(address, address, uint) external; //inject NONSTANDARD NAMING function DEPOSIT926() external payable; //inject NONSTANDARD NAMING function WITHDRAW88(uint) external; //inject NONSTANDARD NAMING } interface ManagerLike { function CDPCAN839(address, uint, address) external view returns (uint); //inject NONSTANDARD NAMING function ILKS43(uint) external view returns (bytes32); //inject NONSTANDARD NAMING function OWNS815(uint) external view returns (address); //inject NONSTANDARD NAMING function URNS226(uint) external view returns (address); //inject NONSTANDARD NAMING function VAT838() external view returns (address); //inject NONSTANDARD NAMING function OPEN171(bytes32, address) external returns (uint); //inject NONSTANDARD NAMING function GIVE370(uint, address) external; //inject NONSTANDARD NAMING function CDPALLOW83(uint, address, uint) external; //inject NONSTANDARD NAMING function URNALLOW976(address, uint) external; //inject NONSTANDARD NAMING function FROB668(uint, int, int) external; //inject NONSTANDARD NAMING function FLUX641(uint, address, uint) external; //inject NONSTANDARD NAMING function MOVE446(uint, address, uint) external; //inject NONSTANDARD NAMING function EXIT270(address, uint, address, uint) external; //inject NONSTANDARD NAMING function QUIT464(uint, address) external; //inject NONSTANDARD NAMING function ENTER426(address, uint) external; //inject NONSTANDARD NAMING function SHIFT772(uint, uint) external; //inject NONSTANDARD NAMING } interface VatLike { function CAN946(address, address) external view returns (uint); //inject NONSTANDARD NAMING function ILKS43(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING function DAI231(address) external view returns (uint); //inject NONSTANDARD NAMING function URNS226(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING function FROB668(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING function HOPE968(address) external; //inject NONSTANDARD NAMING function MOVE446(address, address, uint) external; //inject NONSTANDARD NAMING } interface GemJoinLike { function DEC260() external returns (uint); //inject NONSTANDARD NAMING function GEM716() external returns (GemLike); //inject NONSTANDARD NAMING function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING function EXIT270(address, uint) external; //inject NONSTANDARD NAMING } interface GNTJoinLike { function BAGS888(address) external view returns (address); //inject NONSTANDARD NAMING function MAKE918(address) external returns (address); //inject NONSTANDARD NAMING } interface DaiJoinLike { function VAT838() external returns (VatLike); //inject NONSTANDARD NAMING function DAI231() external returns (GemLike); //inject NONSTANDARD NAMING function JOIN168(address, uint) external payable; //inject NONSTANDARD NAMING function EXIT270(address, uint) external; //inject NONSTANDARD NAMING } interface HopeLike { function HOPE968(address) external; //inject NONSTANDARD NAMING function NOPE673(address) external; //inject NONSTANDARD NAMING } interface EndLike { function FIX740(bytes32) external view returns (uint); //inject NONSTANDARD NAMING function CASH63(bytes32, uint) external; //inject NONSTANDARD NAMING function FREE803(bytes32) external; //inject NONSTANDARD NAMING function PACK489(uint) external; //inject NONSTANDARD NAMING function SKIM635(bytes32, address) external; //inject NONSTANDARD NAMING } interface JugLike { function DRIP111(bytes32) external returns (uint); //inject NONSTANDARD NAMING } interface PotLike { function PIE0(address) external view returns (uint); //inject NONSTANDARD NAMING function DRIP111() external returns (uint); //inject NONSTANDARD NAMING function JOIN168(uint) external; //inject NONSTANDARD NAMING function EXIT270(uint) external; //inject NONSTANDARD NAMING } interface SpotLike { function ILKS43(bytes32) external view returns (address, uint); //inject NONSTANDARD NAMING } interface OSMedianizer { function READ244() external view returns (uint, bool); //inject NONSTANDARD NAMING function FORESIGHT875() external view returns (uint, bool); //inject NONSTANDARD NAMING } interface Uni { function SWAPEXACTTOKENSFORTOKENS833(uint, uint, address[] calldata, address, uint) external; //inject NONSTANDARD NAMING } contract StrategyMKRVaultDAIDelegate { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address constant public token24 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public want613 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public weth705 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING address constant public dai951 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public cdp_manager = address(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public vat = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address public mcd_join_eth_a = address(0x2F0b23f53734252Bda2277357e97e1517d6B042A); address public mcd_join_dai = address(0x9759A6Ac90977b93B58547b4A71c78317f391A28); address public mcd_spot = address(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); address public jug = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1); address constant public eth_price_oracle260 = address(0xCF63089A8aD2a9D8BD6Bb8022f3190EB7e1eD0f1); //inject NONSTANDARD NAMING address constant public yvaultdai641 = address(0xACd43E627e64355f1861cEC6d3a6688B31a6F952); //inject NONSTANDARD NAMING address constant public unirouter43 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING uint public c = 20000; uint public c_safe = 40000; uint constant public c_base986 = 10000; //inject NONSTANDARD NAMING uint public performanceFee = 500; uint constant public performancemax585 = 10000; //inject NONSTANDARD NAMING uint public withdrawalFee = 50; uint constant public withdrawalmax723 = 10000; //inject NONSTANDARD NAMING bytes32 constant public ilk992 = "ETH-A"; //inject NONSTANDARD NAMING address public governance; address public controller; address public strategist; address public harvester; uint public cdpId; constructor(address _controller) public { governance = msg.sender; strategist = 0x2839df1F230dedA9fDDBF1BCB0D4eB1Ee1f7b7d0; harvester = msg.sender; controller = _controller; cdpId = ManagerLike(cdp_manager).OPEN171(ilk992, address(this)); _APPROVEALL294(); } function GETNAME375() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyMKRVaultDAIDelegate"; } function SETSTRATEGIST884(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function SETHARVESTER998(address _harvester) external { //inject NONSTANDARD NAMING require(msg.sender == harvester || msg.sender == governance, "!allowed"); harvester = _harvester; } function SETWITHDRAWALFEE880(uint _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE535(uint _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETBORROWCOLLATERALIZATIONRATIO782(uint _c) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); c = _c; } function SETWITHDRAWCOLLATERALIZATIONRATIO286(uint _c_safe) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); c_safe = _c_safe; } // optional function SETMCDVALUE234( //inject NONSTANDARD NAMING address _manager, address _ethAdapter, address _daiAdapter, address _spot, address _jug ) external { require(msg.sender == governance, "!governance"); cdp_manager = _manager; vat = ManagerLike(_manager).VAT838(); mcd_join_eth_a = _ethAdapter; mcd_join_dai = _daiAdapter; mcd_spot = _spot; jug = _jug; } function _APPROVEALL294() internal { //inject NONSTANDARD NAMING IERC20(token24).APPROVE172(mcd_join_eth_a, uint(-1)); IERC20(dai951).APPROVE172(mcd_join_dai, uint(-1)); IERC20(dai951).APPROVE172(yvaultdai641, uint(-1)); IERC20(dai951).APPROVE172(unirouter43, uint(-1)); } function DEPOSIT926() public { //inject NONSTANDARD NAMING uint _token = IERC20(token24).BALANCEOF367(address(this)); if (_token > 0) { uint p = _GETPRICE756(); uint _draw = _token.MUL745(p).MUL745(c_base986).DIV989(c).DIV989(1e18); require(_CHECKDEBTCEILING877(_draw), "debt ceiling is reached!"); _LOCKWETHANDDRAWDAI745(_token, _draw); yVault(yvaultdai641).DEPOSITALL620(); } } function _GETPRICE756() internal view returns (uint p) { //inject NONSTANDARD NAMING (uint _read,) = OSMedianizer(eth_price_oracle260).READ244(); (uint _foresight,) = OSMedianizer(eth_price_oracle260).FORESIGHT875(); p = _foresight < _read ? _foresight : _read; } function _CHECKDEBTCEILING877(uint _amt) internal view returns (bool) { //inject NONSTANDARD NAMING (,,,uint _line,) = VatLike(vat).ILKS43(ilk992); uint _debt = GETTOTALDEBTAMOUNT152().ADD483(_amt); if (_line.DIV989(1e27) < _debt) { return false; } return true; } function _LOCKWETHANDDRAWDAI745(uint wad, uint wadD) internal { //inject NONSTANDARD NAMING address urn = ManagerLike(cdp_manager).URNS226(cdpId); GemJoinLike(mcd_join_eth_a).JOIN168(urn, wad); ManagerLike(cdp_manager).FROB668(cdpId, TOINT917(wad), _GETDRAWDART399(urn, wadD)); ManagerLike(cdp_manager).MOVE446(cdpId, address(this), wadD.MUL745(1e27)); if (VatLike(vat).CAN946(address(this), address(mcd_join_dai)) == 0) { VatLike(vat).HOPE968(mcd_join_dai); } DaiJoinLike(mcd_join_dai).EXIT270(address(this), wadD); } function _GETDRAWDART399(address urn, uint wad) internal returns (int dart) { //inject NONSTANDARD NAMING uint rate = JugLike(jug).DRIP111(ilk992); uint _dai = VatLike(vat).DAI231(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (_dai < wad.MUL745(1e27)) { dart = TOINT917(wad.MUL745(1e27).SUB518(_dai).DIV989(rate)); dart = uint(dart).MUL745(rate) < wad.MUL745(1e27) ? dart + 1 : dart; } } function TOINT917(uint x) internal pure returns (int y) { //inject NONSTANDARD NAMING y = int(x); require(y >= 0, "int-overflow"); } // Controller only function for creating additional rewards from dust function WITHDRAW88(IERC20 _asset) external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want613 != address(_asset), "want"); require(dai951 != address(_asset), "dai"); balance = _asset.BALANCEOF367(address(this)); _asset.SAFETRANSFER392(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW88(uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint _balance = IERC20(want613).BALANCEOF367(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME510(_amount.SUB518(_balance)); _amount = _amount.ADD483(_balance); } uint _fee = _amount.MUL745(withdrawalFee).DIV989(withdrawalmax723); IERC20(want613).SAFETRANSFER392(Controller(controller).REWARDS983(), _fee); address _vault = Controller(controller).VAULTS407(address(want613)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want613).SAFETRANSFER392(_vault, _amount.SUB518(_fee)); } function SHOULDREBALANCE692() external view returns (bool) { //inject NONSTANDARD NAMING return GETMVAULTRATIO318() < c_safe.MUL745(1e2); } function REBALANCE223() external { //inject NONSTANDARD NAMING uint safe = c_safe.MUL745(1e2); if (GETMVAULTRATIO318() < safe) { uint d = GETTOTALDEBTAMOUNT152(); uint diff = safe.SUB518(GETMVAULTRATIO318()); uint free = d.MUL745(diff).DIV989(safe); uint p = _GETPRICE756(); _WIPE82(_WITHDRAWDAI331(free.MUL745(p).DIV989(1e18))); } } function FORCEREBALANCE268(uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); uint p = _GETPRICE756(); _WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18))); } function _WITHDRAWSOME510(uint256 _amount) internal returns (uint) { //inject NONSTANDARD NAMING uint p = _GETPRICE756(); if (GETMVAULTRATIONEXT436(_amount) < c_safe.MUL745(1e2)) { _WIPE82(_WITHDRAWDAI331(_amount.MUL745(p).DIV989(1e18))); } // _amount in want _FREEWETH537(_amount); return _amount; } function _FREEWETH537(uint wad) internal { //inject NONSTANDARD NAMING ManagerLike(cdp_manager).FROB668(cdpId, -TOINT917(wad), 0); ManagerLike(cdp_manager).FLUX641(cdpId, address(this), wad); GemJoinLike(mcd_join_eth_a).EXIT270(address(this), wad); } function _WIPE82(uint wad) internal { //inject NONSTANDARD NAMING // wad in DAI address urn = ManagerLike(cdp_manager).URNS226(cdpId); DaiJoinLike(mcd_join_dai).JOIN168(urn, wad); ManagerLike(cdp_manager).FROB668(cdpId, 0, _GETWIPEDART74(VatLike(vat).DAI231(urn), urn)); } function _GETWIPEDART74( //inject NONSTANDARD NAMING uint _dai, address urn ) internal view returns (int dart) { (, uint rate,,,) = VatLike(vat).ILKS43(ilk992); (, uint art) = VatLike(vat).URNS226(ilk992, urn); dart = TOINT917(_dai / rate); dart = uint(dart) <= art ? - dart : - TOINT917(art); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL107() external returns (uint balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL392(); _SWAP138(IERC20(dai951).BALANCEOF367(address(this))); balance = IERC20(want613).BALANCEOF367(address(this)); address _vault = Controller(controller).VAULTS407(address(want613)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want613).SAFETRANSFER392(_vault, balance); } function _WITHDRAWALL392() internal { //inject NONSTANDARD NAMING yVault(yvaultdai641).WITHDRAWALL107(); // get Dai _WIPE82(GETTOTALDEBTAMOUNT152().ADD483(1)); // in case of edge case _FREEWETH537(BALANCEOFMVAULT489()); } function BALANCEOF367() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCEOFWANT874() .ADD483(BALANCEOFMVAULT489()); } function BALANCEOFWANT874() public view returns (uint) { //inject NONSTANDARD NAMING return IERC20(want613).BALANCEOF367(address(this)); } function BALANCEOFMVAULT489() public view returns (uint) { //inject NONSTANDARD NAMING uint ink; address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId); (ink,) = VatLike(vat).URNS226(ilk992, urnHandler); return ink; } function HARVEST338() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == harvester || msg.sender == governance, "!authorized"); uint v = GETUNDERLYINGDAI934(yVault(yvaultdai641).BALANCEOF367(address(this))); uint d = GETTOTALDEBTAMOUNT152(); require(v > d, "profit is not realized yet!"); uint profit = v.SUB518(d); _SWAP138(_WITHDRAWDAI331(profit)); uint _want = IERC20(want613).BALANCEOF367(address(this)); if (_want > 0) { uint _fee = _want.MUL745(performanceFee).DIV989(performancemax585); IERC20(want613).SAFETRANSFER392(strategist, _fee); _want = _want.SUB518(_fee); } DEPOSIT926(); } function PAYBACK925(uint _amount) public { //inject NONSTANDARD NAMING // _amount in Dai _WIPE82(_WITHDRAWDAI331(_amount)); } function GETTOTALDEBTAMOUNT152() public view returns (uint) { //inject NONSTANDARD NAMING uint art; uint rate; address urnHandler = ManagerLike(cdp_manager).URNS226(cdpId); (,art) = VatLike(vat).URNS226(ilk992, urnHandler); (,rate,,,) = VatLike(vat).ILKS43(ilk992); return art.MUL745(rate).DIV989(1e27); } function GETMVAULTRATIONEXT436(uint amount) public view returns (uint) { //inject NONSTANDARD NAMING uint spot; // ray uint liquidationRatio; // ray uint denominator = GETTOTALDEBTAMOUNT152(); (,,spot,,) = VatLike(vat).ILKS43(ilk992); (,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992); uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray uint numerator = (BALANCEOFMVAULT489().SUB518(amount)).MUL745(delayedCPrice).DIV989(1e18); // ray return numerator.DIV989(denominator).DIV989(1e3); } function GETMVAULTRATIO318() public view returns (uint) { //inject NONSTANDARD NAMING uint spot; // ray uint liquidationRatio; // ray uint denominator = GETTOTALDEBTAMOUNT152(); (,,spot,,) = VatLike(vat).ILKS43(ilk992); (,liquidationRatio) = SpotLike(mcd_spot).ILKS43(ilk992); uint delayedCPrice = spot.MUL745(liquidationRatio).DIV989(1e27); // ray uint numerator = BALANCEOFMVAULT489().MUL745(delayedCPrice).DIV989(1e18); // ray return numerator.DIV989(denominator).DIV989(1e3); } function GETUNDERLYINGWITHDRAWALFEE628() public view returns (uint) { //inject NONSTANDARD NAMING address _strategy = Controller(controller).STRATEGIES225(dai951); return Strategy(_strategy).WITHDRAWALFEE924(); } function GETUNDERLYINGDAI934(uint _shares) public view returns (uint) { //inject NONSTANDARD NAMING return (yVault(yvaultdai641).BALANCE390()) .MUL745(_shares).DIV989(yVault(yvaultdai641).TOTALSUPPLY3()) .MUL745(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628())) .DIV989(withdrawalmax723); } function _WITHDRAWDAI331(uint _amount) internal returns (uint) { //inject NONSTANDARD NAMING uint _shares = _amount .MUL745(yVault(yvaultdai641).TOTALSUPPLY3()) .DIV989(yVault(yvaultdai641).BALANCE390()) .MUL745(withdrawalmax723) .DIV989(withdrawalmax723.SUB518(GETUNDERLYINGWITHDRAWALFEE628())); yVault(yvaultdai641).WITHDRAW88(_shares); return IERC20(dai951).BALANCEOF367(address(this)); } function _SWAP138(uint _amountIn) internal { //inject NONSTANDARD NAMING address[] memory path = new address[](2); path[0] = address(dai951); path[1] = address(want613); Uni(unirouter43).SWAPEXACTTOKENSFORTOKENS833(_amountIn, 0, path, address(this), now.ADD483(1 days)); } function SETGOVERNANCE389(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER804(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function DIV989(uint256 a, uint256 b) internal pure returns (uint256) {
12,996,781
./full_match/1/0x1A36c461a902E0bE4Ee334DF0817fb828a357358/sources/FairToken.sol
advertising is simply burning tokens with a message (e.g. "save the whales" or "Nike is great")
function burnToAdvertise(string calldata adMessage, uint adPayment) public returns(uint) {
17,183,633
./full_match/11155111/0x448D095593c979793e3178e3749f78267D5Bf04a/sources/project:/contracts/KLOStake.sol
Owner can change the revenue share rate
function changeRevenueShareRate(uint256 newRate) public onlyOwner { require(newRate >= 0 && newRate <= 100, "Invalid percentage range"); revenueShareRate = newRate; }
3,841,422
pragma solidity ^0.5.0; import { DelegatedERC20 } from "./interfaces/DelegatedERC20.sol"; import { SimplifiedLogic } from "./SimplifiedLogic.sol"; import { TokenFront } from "./TokenFront.sol"; /** * This contract adds a 2-of-3 signature requirement to administrative calls. */ contract Administration { /** * Since a method call requires 3 signatures, when it has one signature it * is in an indeterminate state. */ enum CallStatus { None, Open, Complete } /** * These are the operations available. */ enum Operation { AbortCall, SetResolver, Clawback, Migrate, NewAdmin, Rotate, Bind } /** * Information about the current state of the call */ struct MethodCall { CallStatus status; Operation op; bool sigA; bool sigB; bool sigC; bytes32 argHash; } enum Signer { A, B, C } bool public bound = false; uint256 public maximumClaimedCallNumber = 0; SimplifiedLogic public targetLogic; TokenFront public targetFront; address public cosignerA; address public cosignerB; address public cosignerC; mapping(uint256 => MethodCall) public methodCalls; constructor( address _cosignerA, address _cosignerB, address _cosignerC ) public { cosignerA = _cosignerA; cosignerB = _cosignerB; cosignerC = _cosignerC; } /** * Here we implement the preliminary checks: * - sender must be a cosigner * - call slot must be available * - if the call is in progress the method must match */ function setup(uint256 _callNumber, Operation _op, bytes32 _argHash) internal { require( msg.sender == cosignerA || msg.sender == cosignerB || msg.sender == cosignerC, "method call restricted to cosigners" ); MethodCall storage mc = methodCalls[_callNumber]; require( mc.status == CallStatus.None || mc.status == CallStatus.Open, "method status must be none or open" ); if (mc.status == CallStatus.None) { if (_callNumber > maximumClaimedCallNumber) { maximumClaimedCallNumber = _callNumber; } mc.status = CallStatus.Open; mc.op = _op; mc.argHash = _argHash; } else { require( _argHash == mc.argHash, "same arguments must be passed" ); require( mc.op == _op, "the call on file must match the current call" ); } } /** * Add the senders signature as appropriate. */ function addSig(uint256 _callNumber) internal { MethodCall storage mc = methodCalls[_callNumber]; if (msg.sender == cosignerA) { mc.sigA = true; } else if (msg.sender == cosignerB) { mc.sigB = true; } else if (msg.sender == cosignerC) { mc.sigC = true; } } /** * Check if there are two signatures */ function thresholdMet(uint256 _callNumber) public view returns (bool) { MethodCall storage mc = methodCalls[_callNumber]; return (mc.sigA && mc.sigB) || (mc.sigA && mc.sigC) || (mc.sigB && mc.sigC); } /** * Update the given call to complete state. */ function complete(uint256 _callNumber) internal { methodCalls[_callNumber].status = CallStatus.Complete; } /** * Abort the named call if it is incomplete */ function abortCall(uint256 _callNumber, uint256 _callRef) public { setup( _callNumber, Operation.AbortCall, keccak256(abi.encodePacked(_callRef)) ); addSig(_callNumber); if ( thresholdMet(_callNumber) && methodCalls[_callRef].status == CallStatus.Open ) { complete(_callRef); complete(_callNumber); } } /** * Bind the contract to an S3 token front - token logic pair. */ function bind(uint256 _callNumber, SimplifiedLogic _tokenLogic, TokenFront _tokenFront) public { setup( _callNumber, Operation.Bind, keccak256(abi.encodePacked(_tokenLogic, _tokenFront)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { bound = true; targetLogic = _tokenLogic; targetFront = _tokenFront; complete(_callNumber); } } /** * SimplifiedLogic.setResolver */ function setResolver(uint256 _callNumber, address _resolver) public { setup( _callNumber, Operation.SetResolver, keccak256(abi.encodePacked(_resolver)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { targetLogic.setResolver(_resolver); complete(_callNumber); } } /** * SimplifiedLogic.clawback */ function clawback( uint256 _callNumber, address _src, address _dst, uint256 _amount ) public { setup( _callNumber, Operation.Clawback, keccak256(abi.encodePacked(_src, _dst, _amount)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { targetLogic.clawback(_src, _dst, _amount); complete(_callNumber); } } /** * SimplifiedLogic.migrate & TokenFront.newLogic */ function migrate(uint256 _callNumber, DelegatedERC20 _newLogic) public { setup( _callNumber, Operation.Migrate, keccak256(abi.encodePacked(_newLogic)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { targetLogic.migrate(address(_newLogic)); targetFront.migrate(_newLogic); complete(_callNumber); } } /** * SimplifiedLogic.transferOwnership & TokenFront.transferOwnership */ function newAdmin(uint256 _callNumber, address _newOwner) public { setup( _callNumber, Operation.NewAdmin, keccak256(abi.encodePacked(_newOwner)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { targetLogic.transferOwnership(_newOwner); targetFront.transferOwnership(_newOwner); complete(_callNumber); } } /** * Change a signer */ function rotate(uint256 _callNumber, Signer _s, address _newSigner) public { setup( _callNumber, Operation.Rotate, keccak256(abi.encodePacked(_s, _newSigner)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { if (_s == Signer.A) { cosignerA = _newSigner; } else if (_s == Signer.B) { cosignerB = _newSigner; } else if (_s == Signer.C) { cosignerC = _newSigner; } complete(_callNumber); } } }
SimplifiedLogic.clawback/
function clawback( uint256 _callNumber, address _src, address _dst, uint256 _amount ) public { setup( _callNumber, Operation.Clawback, keccak256(abi.encodePacked(_src, _dst, _amount)) ); addSig(_callNumber); if (thresholdMet(_callNumber)) { targetLogic.clawback(_src, _dst, _amount); complete(_callNumber); } }
5,470,059
pragma solidity 0.5.8; pragma experimental ABIEncoderV2; import "./IERC20.sol"; import "./IERC721.sol"; import "./SafeMath.sol"; /// @title EthlanceJob /// @dev A contract for issuing jobs on Ethereum paying in ETH, ERC20, or ERC721 tokens /// @author Mark Beylin <[email protected]>, Gonçalo Sá <[email protected]>, Kevin Owocki <[email protected]>, Ricardo Guilherme Schmidt (@3esmit), Matt Garnett <[email protected]>, Craig Williams <[email protected]> contract EthlanceJobs { using SafeMath for uint256; /* * Structs */ struct Job { address payable[] issuers; // An array of individuals who have complete control over the job, and can edit any of its parameters address[] approvers; // An array of individuals who are allowed to accept the invoices for a particular job address token; // The address of the token associated with the job (should be disregarded if the tokenVersion is 0) uint tokenVersion; // The version of the token being used for the job (0 for ETH, 20 for ERC20, 721 for ERC721) uint balance; // The number of tokens which the job is able to pay out or refund Invoice[] invoices; // An array of Invoice which store the various submissions which have been made to the job Contribution[] contributions; // An array of Contributions which store the contributions which have been made to the job address[] hiredCandidates; } struct Invoice { address payable issuer; // Address who should receive payouts for a given submission address submitter; uint amount; bool cancelled; } struct Contribution { address payable contributor; // The address of the individual who contributed uint amount; // The amount of tokens the user contributed bool refunded; // A boolean storing whether or not the contribution has been refunded yet } /* * Storage */ uint public numJobs; // An integer storing the total number of jobs in the contract mapping(uint => Job) public jobs; // A mapping of jobIDs to jobs mapping (uint => mapping (uint => bool)) public tokenBalances; // A mapping of jobIds to tokenIds to booleans, storing whether a given job has a given ERC721 token in its balance address public owner; // The address of the individual who's allowed to set the metaTxRelayer address address public metaTxRelayer; // The address of the meta transaction relayer whose _sender is automatically trusted for all contract calls bool public callStarted; // Ensures mutex for the entire contract /* * Modifiers */ modifier callNotStarted(){ require(!callStarted); callStarted = true; _; callStarted = false; } modifier validateJobArrayIndex( uint _index) { require(_index < numJobs); _; } modifier validateContributionArrayIndex( uint _jobId, uint _index) { require(_index < jobs[_jobId].contributions.length); _; } modifier validateInvoiceArrayIndex( uint _jobId, uint _index) { require(_index < jobs[_jobId].invoices.length); _; } modifier validateIssuerArrayIndex( uint _jobId, uint _index) { require(_index < jobs[_jobId].issuers.length); _; } modifier validateApproverArrayIndex( uint _jobId, uint _index) { require(_index < jobs[_jobId].approvers.length); _; } modifier onlyIssuer( address _sender, uint _jobId, uint _issuerId) { require(_sender == jobs[_jobId].issuers[_issuerId]); _; } modifier onlyInvoiceIssuer( address _sender, uint _jobId, uint _invoiceId) { require(_sender == jobs[_jobId].invoices[_invoiceId].issuer); _; } modifier onlyContributor( address _sender, uint _jobId, uint _contributionId) { require(_sender == jobs[_jobId].contributions[_contributionId].contributor); _; } modifier isApprover( address _sender, uint _jobId, uint _approverId) { require(_sender == jobs[_jobId].approvers[_approverId]); _; } modifier hasNotRefunded( uint _jobId, uint _contributionId) { require(!jobs[_jobId].contributions[_contributionId].refunded); _; } modifier senderIsValid( address _sender) { require(msg.sender == _sender || msg.sender == metaTxRelayer); _; } /* * Public functions */ constructor() public { // The owner of the contract is automatically designated to be the deployer of the contract owner = msg.sender; } /// @dev setMetaTxRelayer(): Sets the address of the meta transaction relayer /// @param _relayer the address of the relayer function setMetaTxRelayer(address _relayer) external { require(msg.sender == owner); // Checks that only the owner can call require(metaTxRelayer == address(0)); // Ensures the meta tx relayer can only be set once metaTxRelayer = _relayer; } function contains(address[] memory arr, address x) private pure returns(bool) { bool found = false; uint i = 0; while(i < arr.length && !found){ found = arr[i] == x; i++; } return found; } function acceptCandidate(uint jobId, address candidate) public { // Add the candidate as selected for the job jobs[jobId].hiredCandidates.push(candidate); emit CandidateAccepted(jobId, candidate); } /// @dev issueJob(): creates a new job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _issuers the array of addresses who will be the issuers of the job /// @param _approvers the array of addresses who will be the approvers of the job /// @param _ipfsHash the IPFS hash representing the JSON object storing the details of the job (see docs for schema details) /// @param _token the address of the token which will be used for the job /// @param _tokenVersion the version of the token being used for the job (0 for ETH, 20 for ERC20, 721 for ERC721) function issueJob( address payable _sender, address payable[] memory _issuers, address[] memory _approvers, string memory _ipfsHash, address _token, uint _tokenVersion) public senderIsValid(_sender) returns (uint) { require(_tokenVersion == 0 || _tokenVersion == 20 || _tokenVersion == 721); // Ensures a job can only be issued with a valid token version require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver uint jobId = numJobs; // The next job's index will always equal the number of existing jobs Job storage newJob = jobs[jobId]; newJob.issuers = _issuers; newJob.approvers = _approvers; newJob.tokenVersion = _tokenVersion; if (_tokenVersion != 0){ newJob.token = _token; } numJobs = numJobs.add(1); // Increments the number of jobs, since a new one has just been added emit JobIssued(jobId, _sender, _issuers, _approvers, _ipfsHash, // Instead of storing the string on-chain, it is emitted within the event for easy off-chain consumption _token, _tokenVersion); return (jobId); } /// @param _depositAmount the amount of tokens being deposited to the job, which will create a new contribution to the job function issueAndContribute( address payable _sender, address payable[] memory _issuers, address[] memory _approvers, string memory _ipfsHash, address _token, uint _tokenVersion, uint _depositAmount) public payable returns(uint) { uint jobId = issueJob(_sender, _issuers, _approvers, _ipfsHash, _token, _tokenVersion); contribute(_sender, jobId, _depositAmount); return (jobId); } /// @dev contribute(): Allows users to contribute tokens to a given job. /// Contributing merits no privelages to administer the /// funds in the job or accept submissions. Contributions /// has elapsed, and the job has not yet paid out any funds. /// All funds deposited in a job are at the mercy of a /// job's issuers and approvers, so please be careful! /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _amount the amount of tokens being contributed function contribute( address payable _sender, uint _jobId, uint _amount) public payable senderIsValid(_sender) validateJobArrayIndex(_jobId) callNotStarted { require(_amount > 0); // Contributions of 0 tokens or token ID 0 should fail jobs[_jobId].contributions.push( Contribution(_sender, _amount, false)); // Adds the contribution to the job if (jobs[_jobId].tokenVersion == 0){ jobs[_jobId].balance = jobs[_jobId].balance.add(_amount); // Increments the balance of the job require(msg.value == _amount); } else if (jobs[_jobId].tokenVersion == 20){ jobs[_jobId].balance = jobs[_jobId].balance.add(_amount); // Increments the balance of the job require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds require(IERC20(jobs[_jobId].token).transferFrom(_sender, address(this), _amount)); } else if (jobs[_jobId].tokenVersion == 721){ tokenBalances[_jobId][_amount] = true; // Adds the 721 token to the balance of the job require(msg.value == 0); // Ensures users don't accidentally send ETH alongside a token contribution, locking up funds IERC721(jobs[_jobId].token).transferFrom(_sender, address(this), _amount); } else { revert(); } emit ContributionAdded(_jobId, jobs[_jobId].contributions.length - 1, // The new contributionId _sender, _amount); } /// @dev refundContribution(): Allows users to refund the contributions they've /// made to a particular job, but only if the job /// has not yet paid out /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _issuerId the issuer id for thre job /// @param _jobId the index of the job /// @param _contributionId the index of the contribution being refunded function refundContribution( address _sender, uint _jobId, uint _issuerId, uint _contributionId) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateContributionArrayIndex(_jobId, _contributionId) onlyIssuer(_sender, _jobId, _issuerId) hasNotRefunded(_jobId, _contributionId) callNotStarted { Contribution storage contribution = jobs[_jobId].contributions[_contributionId]; contribution.refunded = true; transferTokens(_jobId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor emit ContributionRefunded(_jobId, _contributionId); } /// @dev refundMyContributions(): Allows users to refund their contributions in bulk /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _contributionIds the array of indexes of the contributions being refunded function refundMyContributions( address _sender, uint _jobId, uint _issuerId, uint[] memory _contributionIds) public senderIsValid(_sender) { for (uint i = 0; i < _contributionIds.length; i++){ refundContribution(_sender, _jobId, _issuerId, _contributionIds[i]); } } /// @dev refundContributions(): Allows users to refund their contributions in bulk /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is making the call /// @param _contributionIds the array of indexes of the contributions being refunded function refundContributions( address _sender, uint _jobId, uint _issuerId, uint[] memory _contributionIds) public senderIsValid(_sender) validateJobArrayIndex(_jobId) onlyIssuer(_sender, _jobId, _issuerId) callNotStarted { for (uint i = 0; i < _contributionIds.length; i++){ require(_contributionIds[i] < jobs[_jobId].contributions.length); Contribution storage contribution = jobs[_jobId].contributions[_contributionIds[i]]; require(!contribution.refunded); contribution.refunded = true; transferTokens(_jobId, contribution.contributor, contribution.amount); // Performs the disbursal of tokens to the contributor } emit ContributionsRefunded(_jobId, _sender, _contributionIds); } /// @dev drainJob(): Allows an issuer to drain the funds from the job /// @notice when using this function, if an issuer doesn't drain the entire balance, some users may be able to refund their contributions, while others may not (which is unfair to them). Please use it wisely, only when necessary /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is making the call /// @param _amounts an array of amounts of tokens to be sent. The length of the array should be 1 if the job is in ETH or ERC20 tokens. If it's an ERC721 job, the array should be the list of tokenIDs. function drainJob( address payable _sender, uint _jobId, uint _issuerId, uint[] memory _amounts) public senderIsValid(_sender) validateJobArrayIndex(_jobId) onlyIssuer(_sender, _jobId, _issuerId) callNotStarted { if (jobs[_jobId].tokenVersion == 0 || jobs[_jobId].tokenVersion == 20){ require(_amounts.length == 1); // ensures there's only 1 amount of tokens to be returned require(_amounts[0] <= jobs[_jobId].balance); // ensures an issuer doesn't try to drain the job of more tokens than their balance permits transferTokens(_jobId, _sender, _amounts[0]); // Performs the draining of tokens to the issuer } else { for (uint i = 0; i < _amounts.length; i++){ require(tokenBalances[_jobId][_amounts[i]]);// ensures an issuer doesn't try to drain the job of a token it doesn't have in its balance transferTokens(_jobId, _sender, _amounts[i]); } } emit JobDrained(_jobId, _sender, _amounts); } /// @dev invoiceJob(): Allows users to invoice the job to get paid out /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _invoiceIssuer The invoice issuer, the addresses which will receive payouts for the submission /// @param _ipfsHash the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details) function invoiceJob( address _sender, uint _jobId, address payable _invoiceIssuer, string memory _ipfsHash, uint _amount) public senderIsValid(_sender) validateJobArrayIndex(_jobId) { require(contains(jobs[_jobId].hiredCandidates, _sender)); jobs[_jobId].invoices.push(Invoice(_invoiceIssuer, _sender, _amount, false)); emit JobInvoice(_jobId, (jobs[_jobId].invoices.length - 1), _invoiceIssuer, _ipfsHash, // The _ipfsHash string is emitted in an event for easy off-chain consumption _sender, _amount); } /// @dev cancelInvoice(): Allows the sender of the invoice to cancel it /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _invoiceId the index of the invoice to be accepted function cancelInvoice( address _sender, uint _jobId, uint _invoiceId ) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateInvoiceArrayIndex(_jobId, _invoiceId) { Invoice storage invoice=jobs[_jobId].invoices[_invoiceId]; if(invoice.submitter != _sender){ revert("Only the original invoice sender can cancel it."); } invoice.cancelled=true; emit InvoiceCancelled(_sender, _jobId, _invoiceId); } /// @dev acceptInvoice(): Allows any of the approvers to accept a given submission /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _invoiceId the index of the invoice to be accepted /// @param _approverId the index of the approver which is making the call function acceptInvoice( address _sender, uint _jobId, uint _invoiceId, uint _approverId ) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateInvoiceArrayIndex(_jobId, _invoiceId) isApprover(_sender, _jobId, _approverId) callNotStarted { Invoice storage invoice = jobs[_jobId].invoices[_invoiceId]; if(invoice.cancelled){ revert("Can't accept a cancelled input"); } transferTokens(_jobId, invoice.issuer,invoice.amount); emit InvoiceAccepted(_jobId, _invoiceId, _sender, invoice.amount); } /// @dev invoiceAndAccept(): Allows any of the approvers to invoice and accept a submission simultaneously /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _invoiceIssuer the array of addresses which will receive payouts for the submission /// @param _ipfsHash the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details) /// @param _approverId the index of the approver which is making the call function invoiceAndAccept( address _sender, uint _jobId, address payable _invoiceIssuer, string memory _ipfsHash, uint _approverId, uint _amount) public senderIsValid(_sender) { // first invoice the job on behalf of the _invoiceIssuer invoiceJob(_sender, _jobId, _invoiceIssuer, _ipfsHash, _amount); // then accepts the invoice acceptInvoice(_sender, _jobId, jobs[_jobId].invoices.length - 1, _approverId ); } /// @dev changeJob(): Allows any of the issuers to change the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _issuers the new array of addresses who will be the issuers of the job /// @param _approvers the new array of addresses who will be the approvers of the job /// @param _ipfsHash the new IPFS hash representing the JSON object storing the details of the job (see docs for schema details) function changeJob( address _sender, uint _jobId, uint _issuerId, address payable[] memory _issuers, address payable[] memory _approvers, string memory _ipfsHash ) public senderIsValid(_sender) { require(_jobId < numJobs); // makes the validateJobArrayIndex modifier in-line to avoid stack too deep errors require(_issuerId < jobs[_jobId].issuers.length); // makes the validateIssuerArrayIndex modifier in-line to avoid stack too deep errors require(_sender == jobs[_jobId].issuers[_issuerId]); // makes the onlyIssuer modifier in-line to avoid stack too deep errors require(_issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck jobs[_jobId].issuers = _issuers; jobs[_jobId].approvers = _approvers; emit JobChanged(_jobId, _sender, _issuers, _approvers, _ipfsHash); } /// @dev changeIssuer(): Allows any of the issuers to change a particular issuer of the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _issuerIdToChange the index of the issuer who is being changed /// @param _newIssuer the address of the new issuer function changeIssuer( address _sender, uint _jobId, uint _issuerId, uint _issuerIdToChange, address payable _newIssuer) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerIdToChange) onlyIssuer(_sender, _jobId, _issuerId) { require(_issuerId < jobs[_jobId].issuers.length || _issuerId == 0); jobs[_jobId].issuers[_issuerIdToChange] = _newIssuer; emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers); } /// @dev changeApprover(): Allows any of the issuers to change a particular approver of the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _approverId the index of the approver who is being changed /// @param _approver the address of the new approver function changeApprover( address _sender, uint _jobId, uint _issuerId, uint _approverId, address payable _approver) external senderIsValid(_sender) validateJobArrayIndex(_jobId) onlyIssuer(_sender, _jobId, _issuerId) validateApproverArrayIndex(_jobId, _approverId) { jobs[_jobId].approvers[_approverId] = _approver; emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers); } /// @dev changeData(): Allows any of the issuers to change the data the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _ipfsHash the new IPFS hash representing the JSON object storing the details of the job (see docs for schema details) function changeData( address _sender, uint _jobId, uint _issuerId, string memory _ipfsHash) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerId) onlyIssuer(_sender, _jobId, _issuerId) { emit JobDataChanged(_jobId, _sender, _ipfsHash); // The new _ipfsHash is emitted within an event rather than being stored on-chain for minimized gas costs } /// @dev addIssuers(): Allows any of the issuers to add more issuers to the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _issuers the array of addresses to add to the list of valid issuers function addIssuers( address _sender, uint _jobId, uint _issuerId, address payable[] memory _issuers) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerId) onlyIssuer(_sender, _jobId, _issuerId) { for (uint i = 0; i < _issuers.length; i++){ jobs[_jobId].issuers.push(_issuers[i]); } emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers); } /// @dev replaceIssuers(): Allows any of the issuers to replace the issuers of the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _issuers the array of addresses to replace the list of valid issuers function replaceIssuers( address _sender, uint _jobId, uint _issuerId, address payable[] memory _issuers) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerId) onlyIssuer(_sender, _jobId, _issuerId) { require(_issuers.length > 0 || jobs[_jobId].approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck jobs[_jobId].issuers = _issuers; emit JobIssuersUpdated(_jobId, _sender, jobs[_jobId].issuers); } /// @dev addApprovers(): Allows any of the issuers to add more approvers to the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _approvers the array of addresses to add to the list of valid approvers function addApprovers( address _sender, uint _jobId, uint _issuerId, address[] memory _approvers) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerId) onlyIssuer(_sender, _jobId, _issuerId) { for (uint i = 0; i < _approvers.length; i++){ jobs[_jobId].approvers.push(_approvers[i]); } emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers); } /// @dev replaceApprovers(): Allows any of the issuers to replace the approvers of the job /// @param _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) /// @param _jobId the index of the job /// @param _issuerId the index of the issuer who is calling the function /// @param _approvers the array of addresses to replace the list of valid approvers function replaceApprovers( address _sender, uint _jobId, uint _issuerId, address[] memory _approvers) public senderIsValid(_sender) validateJobArrayIndex(_jobId) validateIssuerArrayIndex(_jobId, _issuerId) onlyIssuer(_sender, _jobId, _issuerId) { require(jobs[_jobId].issuers.length > 0 || _approvers.length > 0); // Ensures there's at least 1 issuer or approver, so funds don't get stuck jobs[_jobId].approvers = _approvers; emit JobApproversUpdated(_jobId, _sender, jobs[_jobId].approvers); } /// @dev getJob(): Returns the details of the job /// @param _jobId the index of the job /// @return Returns a tuple for the job function getJob(uint _jobId) external view returns (Job memory) { return jobs[_jobId]; } function transferTokens(uint _jobId, address payable _to, uint _amount) internal { if (jobs[_jobId].tokenVersion == 0){ require(_amount > 0); // Sending 0 tokens should throw require(jobs[_jobId].balance >= _amount); jobs[_jobId].balance = jobs[_jobId].balance.sub(_amount); _to.transfer(_amount); } else if (jobs[_jobId].tokenVersion == 20){ require(_amount > 0); // Sending 0 tokens should throw require(jobs[_jobId].balance >= _amount); jobs[_jobId].balance = jobs[_jobId].balance.sub(_amount); require(IERC20(jobs[_jobId].token).transfer(_to, _amount)); } else if (jobs[_jobId].tokenVersion == 721){ require(tokenBalances[_jobId][_amount]); tokenBalances[_jobId][_amount] = false; // Removes the 721 token from the balance of the job IERC721(jobs[_jobId].token).transferFrom(address(this), _to, _amount); } else { revert(); } } /* * Events */ event JobIssued(uint _jobId, address payable _creator, address payable[] _issuers, address[] _approvers, string _ipfsHash, address _token, uint _tokenVersion); event ContributionAdded(uint _jobId, uint _contributionId, address payable _contributor, uint _amount); event ContributionRefunded(uint _jobId, uint _contributionId); event ContributionsRefunded(uint _jobId, address _issuer, uint[] _contributionIds); event JobDrained(uint _jobId, address _issuer, uint[] _amounts); event JobInvoice(uint _jobId, uint _invoiceId, address payable _invoiceIssuer, string _ipfsHash, address _submitter, uint _amount); event InvoiceAccepted(uint _jobId, uint _invoiceId, address _approver, uint _amount); event JobChanged(uint _jobId, address _changer, address payable[] _issuers, address payable[] _approvers, string _ipfsHash); event JobIssuersUpdated(uint _jobId, address _changer, address payable[] _issuers); event JobApproversUpdated(uint _jobId, address _changer, address[] _approvers); event JobDataChanged(uint _jobId, address _changer, string _ipfsHash); event CandidateAccepted(uint _jobId, address _candidate); event InvoiceCancelled(address _sender, uint _jobId, uint _invoiceId); }
invoiceJob(): Allows users to invoice the job to get paid out _sender the sender of the transaction issuing the job (should be the same as msg.sender unless the txn is called by the meta tx relayer) _jobId the index of the job _invoiceIssuer The invoice issuer, the addresses which will receive payouts for the submission _ipfsHash the IPFS hash corresponding to a JSON object which contains the details of the submission (see docs for schema details)
function invoiceJob( address _sender, uint _jobId, address payable _invoiceIssuer, string memory _ipfsHash, uint _amount) public senderIsValid(_sender) validateJobArrayIndex(_jobId) { require(contains(jobs[_jobId].hiredCandidates, _sender)); jobs[_jobId].invoices.push(Invoice(_invoiceIssuer, _sender, _amount, false)); emit JobInvoice(_jobId, (jobs[_jobId].invoices.length - 1), _invoiceIssuer, _sender, _amount); }
12,943,832