file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// File: contracts/SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/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. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: contracts/Common.sol pragma solidity ^0.5.0; /** Note: Simple contract to use as base for const vals */ contract CommonConstants { bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)")) bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")) } // File: contracts/IERC1155TokenReceiver.sol pragma solidity ^0.5.0; /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface ERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @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)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @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)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } // File: contracts/ERC165.sol pragma solidity ^0.5.0; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: contracts/IERC1155.sol pragma solidity ^0.5.0; /** @title ERC-1155 Multi Token Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 /* is ERC165 */ { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File: contracts/ERC1155.sol pragma solidity ^0.5.0; // A sample implementation of core ERC1155 function. contract ERC1155 is IERC1155, ERC165, CommonConstants { using SafeMath for uint256; using Address for address; // id => (owner => balance) mapping (uint256 => mapping(address => uint256)) internal balances; // owner => (operator => approved) mapping (address => mapping(address => bool)) internal operatorApproval; /////////////////////////////////////////// ERC165 ////////////////////////////////////////////// /* bytes4(keccak256('supportsInterface(bytes4)')); */ bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /* bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ bytes4(keccak256("balanceOf(address,uint256)")) ^ bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ bytes4(keccak256("setApprovalForAll(address,bool)")) ^ bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_ERC165 || _interfaceId == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } /////////////////////////////////////////// ERC1155 ////////////////////////////////////////////// /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external { require(_to != address(0x0), "_to must be non-zero."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[_id][_from] = balances[_id][_from].sub(_value); balances[_id][_to] = _value.add(balances[_id][_to]); // MUST emit event emit TransferSingle(msg.sender, _from, _to, _id, _value); // Now that the balance is updated and the event was emitted, // call onERC1155Received if the destination is a contract. if (_to.isContract()) { _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data); } } /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external { // MUST Throw on errors require(_to != address(0x0), "destination address must be non-zero."); require(_ids.length == _values.length, "_ids and _values array lenght must match."); require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers."); for (uint256 i = 0; i < _ids.length; ++i) { uint256 id = _ids[i]; uint256 value = _values[i]; // SafeMath will throw with insuficient funds _from // or if _id is not valid (balance will be 0) balances[id][_from] = balances[id][_from].sub(value); balances[id][_to] = value.add(balances[id][_to]); } // Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle // event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead. // Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below. // However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done. // MUST emit event emit TransferBatch(msg.sender, _from, _to, _ids, _values); // Now that the balances are updated and the events are emitted, // call onERC1155BatchReceived if the destination is a contract. if (_to.isContract()) { _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data); } } /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256) { // The balance of any account can be calculated from the Transfer events history. // However, since we need to keep the balances to validate transfer request, // there is no extra cost to also privide a querry function. return balances[_id][_owner]; } /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) { require(_owners.length == _ids.length); uint256[] memory balances_ = new uint256[](_owners.length); for (uint256 i = 0; i < _owners.length; ++i) { balances_[i] = balances[_ids[i]][_owners[i]]; } return balances_; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { operatorApproval[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorApproval[_owner][_operator]; } /////////////////////////////////////////// Internal ////////////////////////////////////////////// function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received"); } function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal { // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance. // Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test. // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test. require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived"); } } // File: contracts/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Strings.sol pragma solidity ^0.5.0; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } 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); } } // File: contracts/RCContract.sol pragma solidity ^0.5.0; /** @dev Mintable form of ERC1155 Shows how easy it is to mint new items. */ contract RCContract is ERC1155, Ownable { bytes4 constant private INTERFACE_SIGNATURE_URI = 0x0e89341c; // Token name string private _contractName = 'ReceiptChain'; // Token symbol string private _symbol = 'RCPT'; // Base URI string private _baseURI = 'https://receiptchain.io/api/items/'; // Total Supplies mapping(uint256 => uint256) private _totalSupplies; // A nonce to ensure we have a unique id each time we mint. uint256 public nonce; /** @dev Must emit on creation The `_name` Name at creation gives some human context to what this token is in the blockchain The `_id` Id of token. */ event CreationName(string _value, uint256 indexed _id); event Update(string _value, uint256 indexed _id); function supportsInterface(bytes4 _interfaceId) public view returns (bool) { if (_interfaceId == INTERFACE_SIGNATURE_URI) { return true; } else { return super.supportsInterface(_interfaceId); } } // Creates a new token type and assings _initialSupply to minter function create(uint256 _initialSupply, address _to, string calldata _name) external onlyOwner returns (uint256 _id) { _id = _create(_initialSupply, _to, _name); } // Creates a new token type and assings _initialSupply to minter function _create(uint256 _initialSupply, address _to, string memory _name) internal returns (uint256 _id) { _id = ++nonce; balances[_id][_to] = _initialSupply; _totalSupplies[_id] = _initialSupply; // Transfer event with mint semantic emit TransferSingle(msg.sender, address(0x0), _to, _id, _initialSupply); emit URI(string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))), _id); if (bytes(_name).length > 0) emit CreationName(_name, _id); } // Batch mint tokens. Assign directly to _to[]. function batchCreate(uint256[] calldata _initialSupplies, address[] calldata _to, string calldata _name) external onlyOwner { for (uint256 i = 0; i < _to.length; ++i) { _create(_initialSupplies[i], _to[i], _name); } } function setBaseURI(string calldata uri) external onlyOwner { _baseURI = uri; } function update(string calldata _update, uint256 _id) external onlyOwner { emit Update(_update, _id); } function baseTokenURI() public view returns (string memory) { return _baseURI; } function uri(uint256 _id) external view returns (string memory) { return string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))); } function tokenURI(uint256 _id) external view returns (string memory) { return string(abi.encodePacked(baseTokenURI(),Strings.uint2str(_id))); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _contractName; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /// @notice Returns the total token supply. /// @dev Throws if '_tokenType' is not a valid SFT /// @param _id The type of SFT to get the totalSupply of. Must be less than the return value of totalTokenTypes /// @return The total supply of the given SFT function totalSupply(uint256 _id) external view returns (uint256) { return _totalSupplies[_id]; } /// @notice Returns the total number of token types for this contract /// @dev Can possibly be zero /// @return The total number of token types function totalTokenTypes() external view returns (uint256) { return nonce; } }
Creates a new token type and assings _initialSupply to minter
function create(uint256 _initialSupply, address _to, string calldata _name) external onlyOwner returns (uint256 _id) { _id = _create(_initialSupply, _to, _name); }
1,386,716
// Sources flattened with hardhat v2.1.2 https://hardhat.org // File @openzeppelin/contracts/utils/introspection/[email protected] // 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); } // File @openzeppelin/contracts/token/ERC1155/[email protected] pragma solidity ^0.8.0; /** * _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/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 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/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC1155/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File @openzeppelin/contracts/token/ERC1155/extensions/[email protected] pragma solidity ^0.8.0; /** * @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 contracts/IAmulet.sol pragma solidity ^0.8.0; interface IAmulet is IERC1155, IERC1155MetadataURI { event AmuletRevealed(uint256 indexed tokenId, address revealedBy, string title, string amulet, string offsetUrl); struct MintData { address owner; uint256 tokenId; } struct RevealData { string title; string amulet; string offsetURL; } struct MintAndRevealData { string title; string amulet; string offsetURL; address owner; } /** * @dev Returns the owner of the token with id `id`. */ function ownerOf(uint256 id) external view returns(address); /** * @dev Returns the score of an amulet. * 0-3: Not an amulet * 4: common * 5: uncommon * 6: rare * 7: epic * 8: legendary * 9: mythic * 10+: beyond mythic */ function getScore(string calldata amulet) external pure returns(uint32); /** * @dev Returns true if an amulet has been revealed. * If this returns false, we cannot be sure the amulet even exists! Don't accept an amulet from someone * if it's not revealed and they won't show you the text of the amulet. */ function isRevealed(uint256 tokenId) external view returns(bool); /** * @dev Mint a new amulet. * @param data The ID and owner for the new token. */ function mint(MintData calldata data) external; /** * @dev Mint new amulets. * @param data The IDs and amulets for the new tokens. */ function mintAll(MintData[] calldata data) external; /** * @dev Reveals an amulet. * @param data The title, text, and offset URL for the amulet. */ function reveal(RevealData calldata data) external; /** * @dev Reveals multiple amulets * @param data The titles, texts, and offset URLs for the amulets. */ function revealAll(RevealData[] calldata data) external; /** * @dev Mint and reveal an amulet. * @param data The title, text, offset URL, and owner for the new amulet. */ function mintAndReveal(MintAndRevealData calldata data) external; /** * @dev Mint and reveal amulets. * @param data The titles, texts, offset URLs, and owners for the new amulets. */ function mintAndRevealAll(MintAndRevealData[] calldata data) external; /** * @dev Returns the Amulet's owner address, the block it was revealed in, and its score. */ function getData(uint256 tokenId) external view returns(address owner, uint64 blockRevealed, uint32 score); } // File contracts/Amulet.sol // Derived from OpenZeppelin's ERC721 implementation, with changes for gas-efficiency. pragma solidity ^0.8.0; /** * @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 Amulet is IAmulet, ERC165 { using Address for address; // Mapping from token ID to token data // Values are packed in the form: // [score (32 bits)][blockRevealed (64 bits)][owner (160 bits)] // This is equivalent to the following Solidity structure, // but saves us about 4200 gas on mint, 3600 gas on reveal, // and 140 gas on transfer. // struct Token { // uint32 score; // uint64 blockRevealed; // address owner; // } mapping (uint256 => uint256) private _tokens; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; constructor (MintData[] memory premineMints, MintAndRevealData[] memory premineReveals) { mintAll(premineMints); mintAndRevealAll(premineReveals); } /************************************************************************** * Opensea-specific methods *************************************************************************/ function contractURI() external pure returns (string memory) { return "https://at.amulet.garden/contract.json"; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual returns (string memory) { return "Amulets"; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual returns (string memory) { return "AMULET"; } /************************************************************************** * ERC721 methods *************************************************************************/ /** * @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 {IERC1155Metadata-uri}. */ function uri(uint256 /*tokenId*/) public view virtual override returns (string memory) { return "https://at.amulet.garden/token/{id}.json"; } /** * @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"); (address owner,,) = getData(id); if(owner == account) { return 1; } return 0; } /** * @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(msg.sender != operator, "ERC1155: setting approval status for self"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(to != address(0), "ERC1155: transfer to the zero address"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: caller is not owner nor approved" ); (address oldOwner, uint64 blockRevealed, uint32 score) = getData(id); require(amount == 1 && oldOwner == from, "ERC1155: Insufficient balance for transfer"); setData(id, to, blockRevealed, score); emit TransferSingle(msg.sender, from, to, id, amount); _doSafeTransferAcceptanceCheck(msg.sender, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == msg.sender || isApprovedForAll(from, msg.sender), "ERC1155: transfer caller is not owner nor approved" ); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; (address oldOwner, uint64 blockRevealed, uint32 score) = getData(id); require(amount == 1 && oldOwner == from, "ERC1155: insufficient balance for transfer"); setData(id, to, blockRevealed, score); } emit TransferBatch(msg.sender, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(msg.sender, from, to, ids, amounts, data); } /************************************************************************** * Amulet-specific methods *************************************************************************/ /** * @dev Returns the owner of the token with id `id`. */ function ownerOf(uint256 id) external override view returns(address) { (address owner,,) = getData(id); return owner; } /** * @dev Returns the score of an amulet. * 0-3: Not an amulet * 4: common * 5: uncommon * 6: rare * 7: epic * 8: legendary * 9: mythic * 10+: beyond mythic */ function getScore(string memory amulet) public override pure returns(uint32) { uint256 hash = uint256(sha256(bytes(amulet))); uint maxlen = 0; uint len = 0; for(;hash > 0; hash >>= 4) { if(hash & 0xF == 8) { len += 1; if(len > maxlen) { maxlen = len; } } else { len = 0; } } return uint32(maxlen); } /** * @dev Returns true if an amulet has been revealed. * If this returns false, we cannot be sure the amulet even exists! Don't accept an amulet from someone * if it's not revealed and they won't show you the text of the amulet. */ function isRevealed(uint256 tokenId) external override view returns(bool) { (address owner, uint64 blockRevealed,) = getData(tokenId); require(owner != address(0), "ERC721: isRevealed query for nonexistent token"); return blockRevealed > 0; } /** * @dev Mint a new amulet. * @param data The ID and owner for the new token. */ function mint(MintData memory data) public override { require(data.owner != address(0), "ERC1155: mint to the zero address"); require(_tokens[data.tokenId] == 0, "ERC1155: mint of existing token"); _tokens[data.tokenId] = uint256(uint160(data.owner)); emit TransferSingle(msg.sender, address(0), data.owner, data.tokenId, 1); _doSafeTransferAcceptanceCheck(msg.sender, address(0), data.owner, data.tokenId, 1, ""); } /** * @dev Mint new amulets. * @param data The IDs and amulets for the new tokens. */ function mintAll(MintData[] memory data) public override { for(uint i = 0; i < data.length; i++) { mint(data[i]); } } /** * @dev Reveals an amulet. * @param data The title, text, and offset URL for the amulet. */ function reveal(RevealData calldata data) public override { require(bytes(data.amulet).length <= 64, "Amulet: Too long"); uint256 tokenId = uint256(keccak256(bytes(data.amulet))); (address owner, uint64 blockRevealed, uint32 score) = getData(tokenId); require( owner == msg.sender || isApprovedForAll(owner, msg.sender), "Amulet: reveal caller is not owner nor approved" ); require(blockRevealed == 0, "Amulet: Already revealed"); score = getScore(data.amulet); require(score >= 4, "Amulet: Score too low"); setData(tokenId, owner, uint64(block.number), score); emit AmuletRevealed(tokenId, msg.sender, data.title, data.amulet, data.offsetURL); } /** * @dev Reveals multiple amulets * @param data The titles, texts, and offset URLs for the amulets. */ function revealAll(RevealData[] calldata data) external override { for(uint i = 0; i < data.length; i++) { reveal(data[i]); } } /** * @dev Mint and reveal an amulet. * @param data The title, text, offset URL, and owner for the new amulet. */ function mintAndReveal(MintAndRevealData memory data) public override { require(bytes(data.amulet).length <= 64, "Amulet: Too long"); uint256 tokenId = uint256(keccak256(bytes(data.amulet))); (address owner,,) = getData(tokenId); require(owner == address(0), "ERC1155: mint of existing token"); require(data.owner != address(0), "ERC1155: mint to the zero address"); uint32 score = getScore(data.amulet); require(score >= 4, "Amulet: Score too low"); setData(tokenId, data.owner, uint64(block.number), score); emit TransferSingle(msg.sender, address(0), data.owner, tokenId, 1); emit AmuletRevealed(tokenId, msg.sender, data.title, data.amulet, data.offsetURL); } /** * @dev Mint and reveal amulets. * @param data The titles, texts, offset URLs, and owners for the new amulets. */ function mintAndRevealAll(MintAndRevealData[] memory data) public override { for(uint i = 0; i < data.length; i++) { mintAndReveal(data[i]); } } /** * @dev Returns the Amulet's owner address, the block it was revealed in, and its score. */ function getData(uint256 tokenId) public override view returns(address owner, uint64 blockRevealed, uint32 score) { uint256 t = _tokens[tokenId]; owner = address(uint160(t)); blockRevealed = uint64(t >> 160); score = uint32(t >> 224); } /** * @dev Sets the amulet's owner address, reveal block, and score. */ function setData(uint256 tokenId, address owner, uint64 blockRevealed, uint32 score) internal { _tokens[tokenId] = uint256(uint160(owner)) | (uint256(blockRevealed) << 160) | (uint256(score) << 224); } /************************************************************************** * Internal/private methods *************************************************************************/ 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(to).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(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } }
Returns the score of an amulet. 0-3: Not an amulet 4: common 5: uncommon 6: rare 7: epic 8: legendary 9: mythic 10+: beyond mythic/
function getScore(string memory amulet) public override pure returns(uint32) { uint256 hash = uint256(sha256(bytes(amulet))); uint maxlen = 0; uint len = 0; for(;hash > 0; hash >>= 4) { if(hash & 0xF == 8) { len += 1; if(len > maxlen) { maxlen = len; } len = 0; } } return uint32(maxlen); }
14,021,808
./full_match/41/0xED231ad1C1C88Db553Ac8d0C57028C01B792fEF7/sources/contracts/FarmBooster.sol
_user user address. _proxy proxy address corresponding to the user. _pid pool id(MasterchefV2 pool). _duration pops pool average locked duration. dB == 0 means lpBalance close to 0 userLockedAmount > 0 means totalLockedAmount > 0 should '' BOOST_PRECISION
function _boostCalculate( address _user, address _proxy, uint256 _pid, uint256 _duration ) internal view returns (uint256) { if (_duration == 0) return BOOST_PRECISION; (uint256 lpBalance, , ) = IMasterChefV2(MASTER_CHEF).userInfo(_pid, _proxy); uint256 dB = (cA * lpBalance) / CA_PRECISION; if (lpBalance == 0 || dB == 0) return BOOST_PRECISION; (, , , , uint256 lockStartTime, uint256 lockEndTime, , , uint256 userLockedAmount) = IPopsPool(POPS_POOL) .userInfo(_user); if (userLockedAmount == 0 || block.timestamp >= lockEndTime) return BOOST_PRECISION; uint256 totalLockedAmount = IPopsPool(POPS_POOL).totalLockedAmount(); IERC20 lp = IERC20(IMasterChefV2(MASTER_CHEF).lpToken(_pid)); uint256 aB = (((lp.balanceOf(MASTER_CHEF) * userLockedAmount * userLockedDuration) * BOOST_RATIO_PRECISION) / cB) / (totalLockedAmount * _duration); return ((lpBalance < (dB + aB) ? lpBalance : (dB + aB)) * BOOST_PRECISION) / dB; }
16,371,302
//Address: 0xdc672e97a238a8caaed6c56d81ab494650578330 //Contract name: EthernalBridge //Balance: 0.176 Ether //Verification Date: 2/15/2018 //Transacion Count: 26 // CODE STARTS HERE pragma solidity 0.4.19; /** * @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 { require(msg.sender != address(0)); owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract EthernalBridge is Ownable { /// Buy is emitted when a lock is bought event Buy( uint indexed id, address owner, uint x, uint y, uint sizeSkin, bytes16 names, bytes32 message ); /// We reserve 1 thousand skins per type until premium // 0-1000 CHEAP_TYPE uint constant MEDIUM_TYPE = 1001; uint constant PREMIUM_TYPE = 2001; /// Bridge max width & height: This can be increased later to make the bridge bigger uint public maxBridgeHeight = 24; // 480px uint public maxBridgeWidth = 400; // 8000px /// Price by size uint public smallPrice = 3 finney; uint public mediumPrice = 7 finney; uint public bigPrice = 14 finney; /// Price modifiers uint8 public mediumMod = 2; uint8 public premiumMod = 3; /// Locks position mapping (uint => uint) public grid; /// withdrawWallet is the fixed destination of funds to withdraw. It might /// differ from owner address to allow for a cold storage address. address public withdrawWallet; struct Lock { address owner; uint32 x; uint16 y; // last digit is lock size uint32 sizeSkin; bytes16 names; bytes32 message; uint time; } /// All bought locks Lock[] public locks; function () public payable { } function EthernalBridge() public { require(msg.sender != address(0)); withdrawWallet = msg.sender; } /// @dev Set address withdaw wallet /// @param _address The address where the balance will be withdrawn function setWithdrawWallet(address _address) external onlyOwner { withdrawWallet = _address; } /// @dev Set small lock price /// This will be used if ether value increase a lot /// @param _price The new small lock price function setSmallPrice(uint _price) external onlyOwner { smallPrice = _price; } /// @dev Set medium lock price /// This will be used if ether value increase a lot /// @param _price The new medium lock price function setMediumPrice(uint _price) external onlyOwner { mediumPrice = _price; } /// @dev Set big lock price /// This will be used if ether value increase a lot /// @param _price The new big lock price function setBigPrice(uint _price) external onlyOwner { bigPrice = _price; } /// @dev Set new bridge height /// @param _height The bridge height function setBridgeHeight(uint _height) external onlyOwner { maxBridgeHeight = _height; } /// @dev Set new bridge width /// @param _width The bridge width function setBridgeWidth(uint _width) external onlyOwner { maxBridgeWidth = _width; } /// Withdraw out the balance of the contract to the given withdraw wallet. function withdraw() external onlyOwner { require(withdrawWallet != address(0)); withdrawWallet.transfer(this.balance); } /// @notice The the total number of locks function getLocksLength() external view returns (uint) { return locks.length; } /// @notice Get a lock by its id /// @param id The lock id function getLockById(uint id) external view returns (uint, uint, uint, uint, bytes16, bytes32, address) { return ( locks[id].x, locks[id].y, locks[id].sizeSkin, locks[id].time, locks[id].names, locks[id].message, locks[id].owner ); } /// @notice Locks must be purchased in 20x20 pixel blocks. /// Each coordinate represents 20 pixels. So _x=15, _y=10, _width=1, _height=1 /// Represents a 20x20 pixel lock at 300x, 200y function buy( uint32 _x, uint16 _y, uint32 _sizeSkin, bytes16 _names, bytes32 _message ) external payable returns (uint) { _checks(_x, _y, _sizeSkin); uint id = locks.push( Lock(msg.sender, _x, _y, _sizeSkin, _names, _message, block.timestamp) ) - 1; // Trigger buy event Buy(id, msg.sender, _x, _y, _sizeSkin, _names, _message); return id; } function _checks(uint _x, uint _y, uint _sizeSkin) private { uint _size = _sizeSkin % 10; // Size & skin are packed together. Last digit is the size. (1, 2, 3) uint _skin = (_sizeSkin - _size) / 10; /// Size must be 20 / 40 / 60 pixels require(_size == 1 || _size == 2 || _size == 3); require(maxBridgeHeight >= (_y + _size) && maxBridgeWidth >= (_x + _size)); require(msg.value >= calculateCost(_size, _skin)); // Check if lock position is available _checkGrid(_x, _y, _size); } /// @dev calculate the cost of the lock by its size and skin /// @param _size The lock size /// @param _skin The lock skin function calculateCost(uint _size, uint _skin) public view returns (uint cost) { // Calculate cost by size if(_size == 2) cost = mediumPrice; else if(_size == 3) cost = bigPrice; else cost = smallPrice; // Apply price modifiers if(_skin >= PREMIUM_TYPE) cost = cost * premiumMod; else if(_skin >= MEDIUM_TYPE) cost = cost * mediumMod; return cost; } /// @dev check if a lock can be set in the given positions /// @param _x The x coord /// @param _y The y coord /// @param _size The lock size function _checkGrid(uint _x, uint _y, uint _size) public { for(uint i = 0; i < _size; i++) { uint row = grid[_x + i]; for(uint j = 0; j < _size; j++) { // if (_y + j) bit is set in row if((row >> (_y + j)) & uint(1) == uint(1)) { // lock exists in this slot revert(); } // set bit (_y + j) row = row | (uint(1) << (_y + j)); } grid[_x + i] = row; } } }
Set big lock price This will be used if ether value increase a lot _price The new big lock price
function setBigPrice(uint _price) external onlyOwner { bigPrice = _price; }
5,414,652
pragma solidity ^0.8.9; // SPDX-License-Identifier: MIT /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @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 IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @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); } /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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; } } } /** * @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; } /** * @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; } /** * @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 ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable 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}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).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 IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.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 IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.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; } uint256[47] private __gap; } /** * @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; } /** * @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); } /** * @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 } } } /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /// @title Crypto Heroes Contract /// @notice Crypto Heroes is a limited-edition ECR-1155 crypto token collection that depicts /// a world full of hidden plans, conspiracy theories, predictions, and the heroes & /// personalities around them. The cards were created by J35, an anonymous figure who travelled /// back in time to reveal the plans of the global power elite—and honor the heroes fighting /// against it. We chose to deliver his message through a censorship-resistant 32-card set, /// forever stored in the Ethereum blockchain /// @author Qrypto Labs LLC contract CryptoHeroes is Initializable, ERC1155Upgradeable, OwnableUpgradeable, UUPSUpgradeable { error SaleNotActive(); error InvalidNumOfPacks(uint8 numPacks); error NotEnoughEth(uint256 valueWei); error NotOwnerOf(uint8 numPacks); error QuantityNotAvailable(uint256 numPacks); // Settings uint8 constant DECK_SIZE = 32; uint8 constant NUM_CARDS_PER_PACK = 2; uint256 constant PACK_PRICE = 0.06 ether; uint256 constant MAX_PACKS = 10000; uint8 constant MAX_PACKS_PER_TX = 20; uint8 constant RESERVED_PACKS = 16; // Token ID uint8 constant PACK_ID = 0; // Card classes uint16 constant COMMON = 770; uint16 constant RARE = 300; uint16 constant SECRET = 150; uint16 constant ULTRA = 10; // Contract state uint16[DECK_SIZE] private availableCards; address private proxyRegistry; uint256 private seed; uint256 public availablePacks; string private contractMetadataUri; /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} /// Initializes contract state function initialize(string memory _uri, string memory _contractMetadataUri, address _proxyRegistry) public initializer { __ERC1155_init(_uri); __Ownable_init(); __UUPSUpgradeable_init(); contractMetadataUri = _contractMetadataUri; proxyRegistry = _proxyRegistry; availableCards = [ COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, COMMON - 1, RARE - 1, RARE - 1, RARE - 1, RARE - 1, SECRET - 1, SECRET - 1, ULTRA - 1, ULTRA - 1 ]; availablePacks = MAX_PACKS - RESERVED_PACKS; } /// returns the contract-level metadata URI function contractURI() public view returns (string memory) { return contractMetadataUri; } /// Sets the URI for the contract-level metadata URI /// @param _newUri the new URI function setContractURI(string memory _newUri) public onlyOwner { contractMetadataUri = _newUri; } /// Sets the URI for the ECR-1155 Metadata JSON Schema /// @param _newUri the new URI function setURI(string memory _newUri) public onlyOwner { _setURI(_newUri); } /// Only the owner can upgrade the contract implementation function _authorizeUpgrade(address newImplementation) internal override onlyOwner {} /// Avoids an additional authorization step (and gas fee) from OpenSea users /// @param _account the user account address /// @param _operator the OpenSea's proxy registry address function isApprovedForAll(address _account, address _operator) public view virtual override returns (bool) { ProxyRegistry _proxyRegistry = ProxyRegistry(proxyRegistry); if (address(_proxyRegistry.proxies(_account)) == _operator) { return true; } return super.isApprovedForAll(_account, _operator); } /// Ensures limit on number of packs modifier checkAvailablePacks(uint256 _numPacks) { if (availablePacks < _numPacks) { // sold out or not enough packs left revert QuantityNotAvailable(_numPacks); } _; } /// Mints a tradable pack. The packs can be "opened" once the sale is active /// @param _to the recipients' addresses /// @param _numPacks the number of packs to give away to each recipient function mintGiveAwayPacks(address[] memory _to, uint8 _numPacks) external onlyOwner checkAvailablePacks(_to.length * _numPacks) { availablePacks -= _to.length * _numPacks; for (uint256 i = 0; i < _to.length; i++) { _mint(_to[i], PACK_ID, _numPacks, ''); } } /// Mints two pseudo-randomly selected cards for each pack that /// the sender wants to "open", as long as he/she owns them. "Opened" /// packs are burned. /// @param _numPacks the number of packs to "open" function mintFromExistingPacks(uint8 _numPacks) public { if (_numPacks > balanceOf(msg.sender, PACK_ID)) { revert NotOwnerOf(_numPacks); } _burn(msg.sender, PACK_ID, _numPacks); _mint(_numPacks); } /// Mints two pseudo-randomly selected cards for each pack /// @param _numPacks the number of packs to "open" function mintFromNewPacks(uint8 _numPacks) public payable checkAvailablePacks(_numPacks) { if (msg.value < (uint256(_numPacks) * PACK_PRICE)) { revert NotEnoughEth(msg.value); } if (_numPacks == 0 || _numPacks > MAX_PACKS_PER_TX) { revert InvalidNumOfPacks(_numPacks); } availablePacks -= _numPacks; _mint(_numPacks); } /// One copy of each card is reserved for the team so we can share the /// collection's copyright function mintDeckForTeam() public onlyOwner { uint256[] memory _ids = new uint256[](DECK_SIZE); uint256[] memory _amounts = new uint256[](DECK_SIZE); for (uint256 i = 0; i < DECK_SIZE; i++) { _ids[i] = i + 1; _amounts[i] = 1; } _mintBatch(msg.sender, _ids, _amounts, ''); } /// Main minting function: it mints two pseudo-randomly cards per pack. There /// are pre-defined probabilities for each card, which are based on each card's /// rarity. A seed, which is dependant with each card selection, the previous /// block hash, and the transaction sender is used to add a source of additional /// pseudo-randomness /// @param _numPacks the number of packs to "open" function _mint(uint8 _numPacks) internal virtual { if (seed == 0) { revert SaleNotActive(); } uint256 _randomNumber = _random(seed); uint256[] memory _ids = new uint256[](_numPacks*2); uint256[] memory _amounts = new uint256[](_numPacks*2); uint16[DECK_SIZE] memory _cardsProbabilities = [ 20000, 19230, 18460, 17690, 16920, 16150, 15380, 14610, 13840, 13070, 12300, 11530, 10760, 9990, 9220, 8450, 7680, 6910, 6140, 5370, 4600, 3830, 3060, 2290, 1520, 1220, 920, 620, 320, 170, 20, 10 ]; uint256 _counter = 0; for (uint256 i = 0; i < _numPacks * NUM_CARDS_PER_PACK; i++) { bool _selected; uint16 _value = uint16(_randomNumber % (MAX_PACKS * NUM_CARDS_PER_PACK)); for (uint256 j = _cardsProbabilities.length - 1; j > 0; j--) { uint16 _probability = _cardsProbabilities[j]; if (_value < _probability && availableCards[j] > 0) { _ids[_counter] = j + 1; _amounts[_counter]++; availableCards[j]--; _selected = true; _counter++; break; } } if (!_selected) { // if there are no cards left with a given (or lower) rarity, // mint the first available card with the next lowest rarity for (uint256 j = 0; j < _cardsProbabilities.length; j++) { if (availableCards[j] > 0) { _ids[_counter] = j + 1; _amounts[_counter]++; availableCards[j]--; _counter++; break; } } } _randomNumber = _random(_randomNumber); } seed = _randomNumber; _mintBatch(msg.sender, _ids, _amounts, ''); } /// Withdraws the contract's balance function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /// Returns a pseudorandom number /// @param _seed additional source of pseudo-randomness /// @return the pseudorandom number function _random(uint256 _seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, _seed))); } /// A non-zero value activates the sale and improves the pseudorandom /// number generator /// @param _newSeed the seed to use for the next transaction function setSeed(uint256 _newSeed) public onlyOwner { seed = _newSeed; } /// Returns true if the sale is active; false otherwise function isSaleActive() public view returns (bool) { return seed != 0; } /// Returns the available quantity for each card function getAllAvailableCards() public view returns (uint16[DECK_SIZE] memory) { return availableCards; } }
Mints two pseudo-randomly selected cards for each pack that the sender wants to "open", as long as he/she owns them. "Opened" packs are burned. _numPacks the number of packs to "open"
function mintFromExistingPacks(uint8 _numPacks) public { if (_numPacks > balanceOf(msg.sender, PACK_ID)) { revert NotOwnerOf(_numPacks); } _burn(msg.sender, PACK_ID, _numPacks); _mint(_numPacks); }
12,181,930
pragma solidity ^0.8.7; import "../nftx/interface/INFTXVault.sol"; import "../nftx/interface/INFTXLPStaking.sol"; import "../nftx/interface/IUniswapV2Router01.sol"; import "../nftx/interface/IVaultTokenUpgradeable.sol"; import "../nftx/interface/IRewardDistributionToken.sol"; import {IWETH} from "../nftx/interface/INFTXStakingZap.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "prb-math/contracts/PRBMathUD60x18.sol"; // SPDX-License-Identifier: MIT contract xRooStaking is Ownable { using PRBMathUD60x18 for uint256; event Staked( address indexed _user, uint256 _stake, uint256 _liquidity, uint256 _weth ); event Unstaked(address indexed _user, uint256 _stake, uint256 _liquidity); // --------- NFTX CONTRACTS/VARIABLES ------------- INFTXVault public NFTXVault; INFTXLPStaking public NFTXLPStaking; IRewardDistributionToken public NFTXRewardDistributionToken; uint256 constant base = 10**18; // 18 decimal places uint256 NFTXRewardPerLiquidity; IWETH public WETH; // --------- SUSHI CONTRACTS ------------ IUniswapV2Router01 public sushiRouter; IERC20 public SLPToken; // --------- INTERNAL CONTRACTS/VARIABLES --------- IERC20 public RTRewardToken; IERC721 public RTStakedToken; uint256 public rewardPeriod; uint256 public periodicReward; uint256 public lockTime; // at the start, RT rewards will not be withdrawable bool public lockRTRewards = true; // --------- STRUCTS -------------------- struct UserData { uint256 stake; uint256 liquidity; uint256 lastTimestamp; int256 RTRewardModifier; int256 NFTXRewardModifier; uint256 NFTXRewardWithdrawn; } struct Dividend { uint256 RTRewardToken; uint256 NFTXRewardToken; } // --------- CONTRACT DATA -------------- mapping(address => UserData) public users; // ---------- EXTERNAL CONTRACT METHODS ---------- constructor( address _NFTXVault, address _NFTXLPStaking, address _NFTXRewardDistributionToken, address _sushiRouter, address _SLPToken, address _RTRewardToken, address _RTStakedToken, uint256 _rewardPeriod, uint256 _periodicReward, uint256 _lockTime ) { RTRewardToken = IERC20(_RTRewardToken); RTStakedToken = IERC721(_RTStakedToken); rewardPeriod = _rewardPeriod; periodicReward = _periodicReward; lockTime = _lockTime; updateExternalReferences( _NFTXVault, _NFTXLPStaking, _NFTXRewardDistributionToken, _sushiRouter, _SLPToken ); } /** * Updates all external references (NFTX/Sushiswap/WETH). * @dev only for the contract owner to use, particularly in the case of near-FUBAR. * @param _NFTXVault the vault token address * @param _NFTXLPStaking the NFTXLPStaking contract address * @param _NFTXRewardDistributionToken the NFTX Reward distribution token * @param _sushiRouter the address of the Sushiswap router * @param _SLPToken the address of the liquidity pool WETH/vault token */ function updateExternalReferences( address _NFTXVault, address _NFTXLPStaking, address _NFTXRewardDistributionToken, address _sushiRouter, address _SLPToken ) public onlyOwner { // ASSIGNMENTS NFTXVault = INFTXVault(_NFTXVault); NFTXLPStaking = INFTXLPStaking(_NFTXLPStaking); NFTXRewardDistributionToken = IRewardDistributionToken( _NFTXRewardDistributionToken ); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); sushiRouter = IUniswapV2Router01(_sushiRouter); SLPToken = IERC20(_SLPToken); // APPROVALS IERC20Upgradeable(address(WETH)).approve( _sushiRouter, type(uint256).max ); SLPToken.approve(_sushiRouter, type(uint256).max); NFTXRewardDistributionToken.approve( address(NFTXLPStaking), type(uint256).max ); NFTXVault.approve(address(sushiRouter), type(uint256).max); SLPToken.approve(address(NFTXLPStaking), type(uint256).max); } /** * Updates the address for the reward token. * @param _token the token in which rewards will be disbursed. */ function setRTRewardToken(address _token) external onlyOwner { RTRewardToken = IERC20(_token); } /** * Locks/unlocks RT reward withdraw * @param _locked the value of the lock (boolean) */ function setLock(bool _locked) external onlyOwner { lockRTRewards = _locked; } /** * Sets the lock time where assets cannot be removed after staking. * @param _lockTime the amount of seconds the lock lasts after staking */ function setLockTime(uint256 _lockTime) external onlyOwner { require(_lockTime > 0); lockTime = _lockTime; } /** * Adds liquidity to the pool using the stakable ERC721 token * and WETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _wethIn the amount of WETH that has been provided by the call * @param _ids the ids of the tokens to stake */ function addLiquidityERC721( uint256 _minWethIn, uint256 _wethIn, uint256[] calldata _ids ) external { uint256 initialWETH = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ); IERC20Upgradeable(address(WETH)).transferFrom( msg.sender, address(this), _wethIn ); _addLiquidityERC721(msg.sender, _minWethIn, _wethIn, _ids); uint256 WETHRefund = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ) - initialWETH; if (WETHRefund < _wethIn && WETHRefund > 0) WETH.transfer(msg.sender, WETHRefund); } /** * Adds liquidity to the pool using the stakable ERC721 token * and ETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _ids the ids of the tokens to stake * @dev the value passed in is converted to WETH and sent to the LP. */ function addLiquidityERC721ETH(uint256 _minWethIn, uint256[] calldata _ids) external payable { uint256 initialWETH = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ); WETH.deposit{value: msg.value}(); _addLiquidityERC721(msg.sender, _minWethIn, msg.value, _ids); uint256 wethRefund = IERC20Upgradeable(address(WETH)).balanceOf( address(this) ) - initialWETH; // Return extras. if (wethRefund < msg.value && wethRefund > 0) { WETH.withdraw(wethRefund); (bool success, ) = payable(msg.sender).call{value: wethRefund}(""); require(success, "Refund failed"); } } /** * Adds liquidity to the pool using the stakable ERC20 token * and WETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _wethIn the amount of WETH that has been provided by the call * @param _amount the amount of the ERC20 token to stake */ function addLiquidityERC20( uint256 _minWethIn, uint256 _wethIn, uint256 _amount ) external { IERC20Upgradeable(address(WETH)).transferFrom( msg.sender, address(this), _wethIn ); (, uint256 amountWETH, ) = _addLiquidityERC20( msg.sender, _minWethIn, _wethIn, _amount ); // refund unused WETH if (amountWETH < _wethIn && _wethIn - amountWETH > 0) { WETH.transfer(msg.sender, _wethIn - amountWETH); } } /** * Adds liquidity to the pool using the stakable ERC20 token * and ETH. * @param _minWethIn the min amount of WETH that will get sent to the LP * @param _amount the amount of the ERC20 token to stake * @dev the value passed in is converted to WETH and sent to the LP. */ function addLiquidityERC20ETH(uint256 _minWethIn, uint256 _amount) external payable { WETH.deposit{value: msg.value}(); (, uint256 amountWETH, ) = _addLiquidityERC20( msg.sender, _minWethIn, msg.value, _amount ); // refund unused ETH if (amountWETH < msg.value && msg.value - amountWETH > 0) { WETH.withdraw(msg.value - amountWETH); (bool sent, ) = payable(msg.sender).call{ value: msg.value - amountWETH }(""); require(sent, "refund failed"); } } /** * Removes all liquidity from the LP and claims rewards. * @param _amountTokenMin the min amount of the ERC20 staking token to get back * @param _amountWETHMin the min amount of WETH to get back * * NOTE you cannot withdraw until the timelock has expired. */ function removeLiquidity(uint256 _amountTokenMin, uint256 _amountWETHMin) external { require( users[msg.sender].lastTimestamp + lockTime < block.timestamp, "Locked" ); _removeLiquidity(msg.sender, _amountTokenMin, _amountWETHMin); } /** * Claims all of the dividends currently owed to the caller. * Will not claim RT rewards if the lock is set. */ function claimRewards() external { _claimRewards(msg.sender); } /** * Gets the rewards owed to the user. */ function dividendOf(address _user) external view returns (Dividend memory) { return _dividendOf(_user); } /** * An emergency function that will allow users to pull out their liquidity in the NFTX * reward distribution token. DOES NOT DISTRIBUTE REWARDS. This is to be used in the * case where our connection with NFTX's contracts causes transaction failures. * * NOTE you cannot withdraw until the timelock has expired. */ function emergencyExit() external { require( users[msg.sender].lastTimestamp + lockTime < block.timestamp, "Locked" ); _emergencyExit(msg.sender); } /** * Shows the time until the user's funds are unlocked (unix seconds). * @param _user the user whose lock time we are checking */ function lockedUntil(address _user) external view returns (uint256) { require(users[_user].lastTimestamp != 0, "N/A"); return users[_user].lastTimestamp + lockTime; } // ---------- INTERNAL CONTRACT METHODS ---------- function _totalLiquidityStaked() internal view returns (uint256) { return NFTXRewardDistributionToken.balanceOf(address(this)); } /** * An emergency escape in the unlikely case of a contract error * causing unstaking methods to fail. */ function _emergencyExit(address _user) internal { uint256 liquidity = users[_user].liquidity; delete users[_user]; NFTXRewardDistributionToken.transfer(_user, liquidity); } function _claimContractNFTXRewards() internal { uint256 currentRewards = NFTXVault.balanceOf(address(this)); uint256 dividend = NFTXRewardDistributionToken.dividendOf( address(this) ); if (dividend == 0) return; NFTXLPStaking.claimRewards(NFTXVault.vaultId()); require( NFTXVault.balanceOf(address(this)) == currentRewards + dividend, "Unexpected balance" ); NFTXRewardPerLiquidity += dividend.div(_totalLiquidityStaked()); } function _addLiquidityERC721( address _user, uint256 _minWethIn, uint256 _wethIn, uint256[] calldata _ids ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { _claimContractNFTXRewards(); uint256 initialRewardToken = NFTXVault.balanceOf(address(this)); for (uint256 i = 0; i < _ids.length; i++) { RTStakedToken.transferFrom(_user, address(this), _ids[i]); } RTStakedToken.setApprovalForAll(address(NFTXVault), true); NFTXVault.mint(_ids, new uint256[](0)); uint256 newTokens = NFTXVault.balanceOf(address(this)) - initialRewardToken; return _stakeAndUpdate(_user, _minWethIn, _wethIn, newTokens); } /** * Adds liquidity in ERC20 (the vault token) */ function _addLiquidityERC20( address _user, uint256 _minWethIn, uint256 _wethIn, uint256 _amount ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { _claimContractNFTXRewards(); NFTXVault.transferFrom(_user, address(this), _amount); return _stakeAndUpdate(_user, _minWethIn, _wethIn, _amount); } /** * Stakes on the SLP and then on NFTx's platform * @dev All vault token and WETH should be owned by the * contract before calling. */ function _stakeAndUpdate( address _user, uint256 _minWethIn, uint256 _wethIn, uint256 _amount // amount of ERC20 vault token ) internal returns ( uint256 amountToken, uint256 amountWETH, uint256 liquidity ) { // stake on SUSHI ( amountToken, amountWETH, // amt used liquidity ) = sushiRouter.addLiquidity( address(NFTXVault), address(WETH), _amount, _wethIn, _amount, _minWethIn, address(this), block.timestamp ); NFTXLPStaking.deposit(NFTXVault.vaultId(), liquidity); // DEPOSIT IN NFTX UserData memory userData = users[_user]; uint256 NFTXRewardModifier = liquidity.mul(NFTXRewardPerLiquidity); uint256 currentNumPeriods = userData.lastTimestamp == 0 ? 0 : (block.timestamp - userData.lastTimestamp) / rewardPeriod; userData.liquidity += liquidity; userData.RTRewardModifier += int256( currentNumPeriods * periodicReward.mul(userData.stake) ); userData.lastTimestamp = block.timestamp; userData.stake += _amount; userData.NFTXRewardModifier -= int256(NFTXRewardModifier); users[_user] = userData; // return unstaked vault token if (amountToken < _amount) { NFTXVault.transfer(_user, _amount - amountToken); } emit Staked(_user, _amount, liquidity, amountWETH); } function _dividendOf(address _user) internal view returns (Dividend memory) { uint256 updatedNFTXRewardPerLiquidity = NFTXRewardPerLiquidity + NFTXRewardDistributionToken.dividendOf(address(this)).div( _totalLiquidityStaked() ); int256 nftxReward = int256( (users[_user].liquidity.mul(updatedNFTXRewardPerLiquidity)) ) + users[_user].NFTXRewardModifier - int256(users[_user].NFTXRewardWithdrawn); uint256 numPeriods = users[_user].lastTimestamp == 0 ? 0 : (block.timestamp - users[_user].lastTimestamp) / rewardPeriod; int256 rtReward = int256( numPeriods * periodicReward.mul(users[_user].stake) ) + users[_user].RTRewardModifier; require(nftxReward >= 0 && rtReward >= 0, "Negative Reward"); Dividend memory dividend; dividend.NFTXRewardToken = uint256(nftxReward); dividend.RTRewardToken = uint256(rtReward); return dividend; } function _claimRewards(address _user) internal { _claimContractNFTXRewards(); Dividend memory rewards = _dividendOf(_user); if (rewards.NFTXRewardToken > 0) { users[_user].NFTXRewardWithdrawn += rewards.NFTXRewardToken; NFTXVault.transfer(_user, rewards.NFTXRewardToken); } if (rewards.RTRewardToken > 0 && !lockRTRewards) { users[_user].RTRewardModifier -= int256(rewards.RTRewardToken); RTRewardToken.transfer(_user, rewards.RTRewardToken); } } function _removeLiquidity( address _user, uint256 _amountTokenMin, uint256 _amountWETHMin ) internal { uint256 amount = users[_user].liquidity; uint256 stake = users[_user].stake; _claimRewards(_user); delete users[_user]; // remove from NFTXLPStaking NFTXLPStaking.withdraw(NFTXVault.vaultId(), amount); // gives us <amount> SLP sushiRouter.removeLiquidity( address(NFTXVault), address(WETH), amount, _amountTokenMin, _amountWETHMin, _user, // send to user block.timestamp ); // return to user emit Unstaked(_user, stake, amount); } receive() external payable { // DO NOTHING } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/INFTXEligibility.sol"; import "../token/IERC20Upgradeable.sol"; import "../interface/INFTXVaultFactory.sol"; interface INFTXVault is IERC20Upgradeable { function manager() external view returns (address); function assetAddress() external view returns (address); function vaultFactory() external view returns (INFTXVaultFactory); function eligibilityStorage() external view returns (INFTXEligibility); function is1155() external view returns (bool); function allowAllItems() external view returns (bool); function enableMint() external view returns (bool); function enableRandomRedeem() external view returns (bool); function enableTargetRedeem() external view returns (bool); function enableRandomSwap() external view returns (bool); function enableTargetSwap() external view returns (bool); function vaultId() external view returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external view returns (uint256); function randomRedeemFee() external view returns (uint256); function targetRedeemFee() external view returns (uint256); function randomSwapFee() external view returns (uint256); function targetSwapFee() external view returns (uint256); function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event EnableRandomSwapUpdated(bool enabled); event EnableTargetSwapUpdated(bool enabled); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem, bool _enableRandomSwap, bool _enableTargetSwap ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee, uint256 _randomSwapFee, uint256 _targetSwapFee ) external; function disableVaultFees() external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote(uint256 amountA, uint256 reserveA, uint256 reserveB) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface IVaultTokenUpgradeable is IERC20Upgradeable { function mint(address to, uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface IRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __RewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./INFTXVault.sol"; import "./INFTXVaultFactory.sol"; import "./INFTXFeeDistributor.sol"; import "./INFTXLPStaking.sol"; import "./ITimelockRewardDistributionToken.sol"; import "./IUniswapV2Router01.sol"; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "../token/IERC1155Upgradeable.sol"; import "../token/IERC20Upgradeable.sol"; import "../token/ERC721HolderUpgradeable.sol"; import "../token/IERC1155ReceiverUpgradeable.sol"; import "../util/OwnableUpgradeable.sol"; // Authors: @0xKiwi_. abstract contract IWETH { function deposit() virtual external payable; function transfer(address to, uint value) virtual external returns (bool); function withdraw(uint) virtual external; } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } abstract contract INFTXStakingZap is IERC721ReceiverUpgradeable, IERC1155ReceiverUpgradeable { IWETH public immutable WETH; INFTXLPStaking public immutable lpStaking; INFTXVaultFactory public immutable nftxFactory; IUniswapV2Router01 public immutable sushiRouter; uint256 public lockTime; constructor(address _nftxFactory, address _sushiRouter) { nftxFactory = INFTXVaultFactory(_nftxFactory); lpStaking = INFTXLPStaking(INFTXFeeDistributor(INFTXVaultFactory(_nftxFactory).feeDistributor()).lpStaking()); sushiRouter = IUniswapV2Router01(_sushiRouter); WETH = IWETH(IUniswapV2Router01(_sushiRouter).WETH()); IERC20Upgradeable(address(IUniswapV2Router01(_sushiRouter).WETH())).approve(_sushiRouter, type(uint256).max); } function setLockTime(uint256 newLockTime) virtual external; function addLiquidity721ETH( uint256 vaultId, uint256[] memory ids, uint256 minWethIn ) virtual external payable returns (uint256); function addLiquidity721ETHTo( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, address to ) virtual external payable returns (uint256); function addLiquidity1155ETH( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minEthIn ) virtual external payable returns (uint256); function addLiquidity1155ETHTo( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minEthIn, address to ) virtual external payable returns (uint256); function addLiquidity721( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn ) virtual external returns (uint256); function addLiquidity721To( uint256 vaultId, uint256[] memory ids, uint256 minWethIn, uint256 wethIn, address to ) virtual external returns (uint256); function addLiquidity1155( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn ) virtual external returns (uint256); function addLiquidity1155To( uint256 vaultId, uint256[] memory ids, uint256[] memory amounts, uint256 minWethIn, uint256 wethIn, address to ) virtual external returns (uint256); function lockedUntil(uint256 vaultId, address who) virtual external view returns (uint256); function lockedLPBalance(uint256 vaultId, address who) virtual external view returns (uint256); receive() virtual external payable; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathUD60x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with uint256 numbers considered to have 18 /// trailing decimals. We call this number representation unsigned 60.18-decimal fixed-point, since there can be up to 60 /// digits in the integer part and up to 18 decimals in the fractional part. The numbers are bound by the minimum and the /// maximum values permitted by the Solidity type uint256. library PRBMathUD60x18 { /// @dev Half the SCALE number. uint256 internal constant HALF_SCALE = 5e17; /// @dev log2(e) as an unsigned 60.18-decimal fixed-point number. uint256 internal constant LOG2_E = 1_442695040888963407; /// @dev The maximum value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935; /// @dev The maximum whole value an unsigned 60.18-decimal fixed-point number can have. uint256 internal constant MAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000; /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The arithmetic average as an unsigned 60.18-decimal fixed-point number. function avg(uint256 x, uint256 y) internal pure returns (uint256 result) { // The operations can never overflow. unchecked { // The last operand checks if both x and y are odd and if that is the case, we add 1 to the result. We need // to do this because if both numbers are odd, the 0.5 remainder gets truncated twice. result = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @notice Yields the least unsigned 60.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_UD60x18. /// /// @param x The unsigned 60.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as an unsigned 60.18-decimal fixed-point number. function ceil(uint256 x) internal pure returns (uint256 result) { if (x > MAX_WHOLE_UD60x18) { revert PRBMathUD60x18__CeilOverflow(x); } assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "SCALE - remainder" but faster. let delta := sub(SCALE, remainder) // Equivalent to "x + delta * (remainder > 0 ? 1 : 0)" but faster. result := add(x, mul(delta, gt(remainder, 0))) } } /// @notice Divides two unsigned 60.18-decimal fixed-point numbers, returning a new unsigned 60.18-decimal fixed-point number. /// /// @dev Uses mulDiv to enable overflow-safe multiplication and division. /// /// Requirements: /// - The denominator cannot be zero. /// /// @param x The numerator as an unsigned 60.18-decimal fixed-point number. /// @param y The denominator as an unsigned 60.18-decimal fixed-point number. /// @param result The quotient as an unsigned 60.18-decimal fixed-point number. function div(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDiv(x, SCALE, y); } /// @notice Returns Euler's number as an unsigned 60.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (uint256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp(uint256 x) internal pure returns (uint256 result) { // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathUD60x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { uint256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_UD60x18. /// /// @param x The exponent as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathUD60x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (x << 64) / SCALE; // Pass x to the PRBMath.exp2 function, which uses the 192.64-bit fixed-point number representation. result = PRBMath.exp2(x192x64); } } /// @notice Yields the greatest unsigned 60.18 decimal fixed-point number less than or equal to x. /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// @param x The unsigned 60.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as an unsigned 60.18-decimal fixed-point number. function floor(uint256 x) internal pure returns (uint256 result) { assembly { // Equivalent to "x % SCALE" but faster. let remainder := mod(x, SCALE) // Equivalent to "x - remainder * (remainder > 0 ? 1 : 0)" but faster. result := sub(x, mul(remainder, gt(remainder, 0))) } } /// @notice Yields the excess beyond the floor of x. /// @dev Based on the odd function definition https://en.wikipedia.org/wiki/Fractional_part. /// @param x The unsigned 60.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as an unsigned 60.18-decimal fixed-point number. function frac(uint256 x) internal pure returns (uint256 result) { assembly { result := mod(x, SCALE) } } /// @notice Converts a number from basic integer form to unsigned 60.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be less than or equal to MAX_UD60x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in unsigned 60.18-decimal fixed-point representation. function fromUint(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__FromUintOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_UD60x18, lest it overflows. /// /// @param x The first operand as an unsigned 60.18-decimal fixed-point number. /// @param y The second operand as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function gm(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. uint256 xy = x * y; if (xy / x != y) { revert PRBMathUD60x18__GmOverflow(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = PRBMath.sqrt(xy); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as an unsigned 60.18-decimal fixed-point number. function inv(uint256 x) internal pure returns (uint256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2.718281828459045235, for that we would need more fine-grained precision. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as an unsigned 60.18-decimal fixed-point number. function ln(uint256 x) internal pure returns (uint256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 196205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as an unsigned 60.18-decimal fixed-point number. function log10(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly multiplication operation, not the "mul" function defined // in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 59) } default { result := MAX_UD60x18 } } if (result == MAX_UD60x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than or equal to SCALE, otherwise the result would be negative. /// /// Caveats: /// - The results are nor perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as an unsigned 60.18-decimal fixed-point number. function log2(uint256 x) internal pure returns (uint256 result) { if (x < SCALE) { revert PRBMathUD60x18__LogInputTooSmall(x); } unchecked { // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(x / SCALE); // The integer part of the logarithm as an unsigned 60.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255 and SCALE is 1e18. result = n * SCALE; // This is y = x * 2^(-n). uint256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (uint256 delta = HALF_SCALE; delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } } } /// @notice Multiplies two unsigned 60.18-decimal fixed-point numbers together, returning a new unsigned 60.18-decimal /// fixed-point number. /// @dev See the documentation for the "PRBMath.mulDivFixedPoint" function. /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The product as an unsigned 60.18-decimal fixed-point number. function mul(uint256 x, uint256 y) internal pure returns (uint256 result) { result = PRBMath.mulDivFixedPoint(x, y); } /// @notice Returns PI as an unsigned 60.18-decimal fixed-point number. function pi() internal pure returns (uint256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as an unsigned 60.18-decimal fixed-point number. /// @param y Exponent to raise x to, as an unsigned 60.18-decimal fixed-point number. /// @return result x raised to power y, as an unsigned 60.18-decimal fixed-point number. function pow(uint256 x, uint256 y) internal pure returns (uint256 result) { if (x == 0) { result = y == 0 ? SCALE : uint256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (unsigned 60.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - The result must fit within MAX_UD60x18. /// /// Caveats: /// - All from "mul". /// - Assumes 0^0 is 1. /// /// @param x The base as an unsigned 60.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function powu(uint256 x, uint256 y) internal pure returns (uint256 result) { // Calculate the first iteration of the loop in advance. result = y & 1 > 0 ? x : SCALE; // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. for (y >>= 1; y > 0; y >>= 1) { x = PRBMath.mulDivFixedPoint(x, x); // Equivalent to "y % 2 == 1" but faster. if (y & 1 > 0) { result = PRBMath.mulDivFixedPoint(result, x); } } } /// @notice Returns 1 as an unsigned 60.18-decimal fixed-point number. function scale() internal pure returns (uint256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x must be less than MAX_UD60x18 / SCALE. /// /// @param x The unsigned 60.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as an unsigned 60.18-decimal fixed-point . function sqrt(uint256 x) internal pure returns (uint256 result) { unchecked { if (x > MAX_UD60x18 / SCALE) { revert PRBMathUD60x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two unsigned // 60.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = PRBMath.sqrt(x * SCALE); } } /// @notice Converts a unsigned 60.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The unsigned 60.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toUint(uint256 x) internal pure returns (uint256 result) { unchecked { result = x / SCALE; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/IBeacon.sol"; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function allVaults() external view returns (address[] memory); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); function factoryMintFee() external view returns (uint64); function factoryRandomRedeemFee() external view returns (uint64); function factoryTargetRedeemFee() external view returns (uint64); function factoryRandomSwapFee() external view returns (uint64); function factoryTargetSwapFee() external view returns (uint64); function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); event DisableVaultFees(uint256 vaultId); event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; function setFactoryFees( uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function setVaultFees( uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee ) external; function disableVaultFees(uint256 vaultId) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external returns (address); function lpStaking() external returns (address); function treasury() external returns (address); function defaultTreasuryAlloc() external returns (uint256); function defaultLPAlloc() external returns (uint256); function allocTotal(uint256 vaultId) external returns (uint256); function specificTreasuryAlloc(uint256 vaultId) external returns (uint256); // Write functions. function __FeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeMultipleReceiverAlloc( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, uint256[] memory allocPoints ) external; function changeMultipleReceiverAddress( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, address[] memory addresses, bool[] memory isContracts ) external; function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setDefaultTreasuryAlloc(uint256 _allocPoint) external; function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external; function setLPStakingAddress(address _lpStaking) external; function setNFTXVaultFactory(address _factory) external; function setDefaultLPAlloc(uint256 _allocPoint) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../token/IERC20Upgradeable.sol"; interface ITimelockRewardDistributionToken is IERC20Upgradeable { function distributeRewards(uint amount) external; function __TimelockRewardDistributionToken_init(IERC20Upgradeable _target, string memory _name, string memory _symbol) external; function mint(address account, address to, uint256 amount) external; function timelockMint(address account, uint256 amount, uint256 timelockLength) external; function burnFrom(address account, uint256 amount) external; function withdrawReward(address user) external; function dividendOf(address _owner) external view returns(uint256); function withdrawnRewardOf(address _owner) external view returns(uint256); function accumulativeRewardOf(address _owner) external view returns(uint256); function timelockUntil(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721ReceiverUpgradeable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is IERC721ReceiverUpgradeable { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interface/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { result = prod0 / denominator; } return result; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath__MulDivOverflow(prod1, denominator); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the closest power of two that is higher than x. uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } }
Adds liquidity to the pool using the stakable ERC20 token and ETH. _minWethIn the min amount of WETH that will get sent to the LP _amount the amount of the ERC20 token to stake the value passed in is converted to WETH and sent to the LP./ refund unused ETH
function addLiquidityERC20ETH(uint256 _minWethIn, uint256 _amount) external payable { (, uint256 amountWETH, ) = _addLiquidityERC20( msg.sender, _minWethIn, msg.value, _amount ); if (amountWETH < msg.value && msg.value - amountWETH > 0) { WETH.withdraw(msg.value - amountWETH); (bool sent, ) = payable(msg.sender).call{ value: msg.value - amountWETH }(""); require(sent, "refund failed"); } }
884,297
./full_match/1/0x7FeA34e2Dc6f63CCD8465ceF3DD616DB0762759f/sources/contracts/WagmiUnited.sol
enableMessages sets whether token messages is enabled/
function setMessagesEnabled(bool enableMessages) public onlyOwner { _messagesEnabled = enableMessages; }
4,915,667
./partial_match/1/0x30ACF449995Dc0d1cB6d83983f589bB774912D4A/sources/SHIBFROG.sol
Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "IERC20Simp: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } }
9,341,131
./full_match/1/0x1454E8d951ddD92A095fec1c21D787faA2167560/sources/contracts/Alchileverso.sol
Standard mint function
function mintToken(uint256 _amount) public payable { uint256 supply = totalSupply(); require( saleActive, "La venta publica no esta activa." ); require( _amount > 0 && _amount <= MAX_MINT_PER_TX, "Solo pudes mintear de 1 a 5 tokens por transaccion." ); require( supply + _amount <= MAX_SUPPLY, "No puedes mintar mas que la cantidad destinada al publico." ); require( msg.value == pricePublic * _amount, "Cantidad incorrecta de ETH." ); _safeMint( msg.sender, _amount); }
16,475,414
// Mysterium Network Presale Smart Contract pragma solidity ^0.4.6; contract Presale { mapping (address => uint) public balances; uint public transfered_total = 0; uint public constant min_goal_amount = 2000 ether; uint public constant max_goal_amount = 6000 ether; // Mysterium project wallet address public project_wallet; uint public presale_start_block; uint public presale_end_block; // approximate blocks count in 2 months uint constant blocks_in_two_months = 351558; // block number of the end of refund window, // which will occur in the end of 2 months after presale uint public refund_window_end_block; function Presale(/*uint _start_block, uint _end_block, address _project_wallet*/) { uint _start_block = 2818600; uint _end_block = 3191000; address _project_wallet = 0x002515a2fd5C9DDa1d4109aE8BBF9f73A707B72f; if (_start_block <= block.number) throw; if (_end_block <= _start_block) throw; if (_project_wallet == 0) throw; presale_start_block = _start_block; presale_end_block = _end_block; project_wallet = _project_wallet; refund_window_end_block = presale_end_block + blocks_in_two_months; } function has_presale_started() private constant returns (bool) { return block.number >= presale_start_block; } function has_presale_time_ended() private constant returns (bool) { return block.number > presale_end_block; } function is_min_goal_reached() private constant returns (bool) { return transfered_total >= min_goal_amount; } function is_max_goal_reached() private constant returns (bool) { return transfered_total >= max_goal_amount; } // Accept ETH while presale is active or until maximum goal is reached. function () payable { // check if presale has started if (!has_presale_started()) throw; // check if presale date is not over if (has_presale_time_ended()) throw; // don`t accept transactions with zero value if (msg.value == 0) throw; // check if max goal is not reached if (is_max_goal_reached()) throw; if (transfered_total + msg.value > max_goal_amount) { // return change var change_to_return = transfered_total + msg.value - max_goal_amount; if (!msg.sender.send(change_to_return)) throw; var to_add = max_goal_amount - transfered_total; balances[msg.sender] += to_add; transfered_total += to_add; } else { // set data balances[msg.sender] += msg.value; transfered_total += msg.value; } } // Transfer ETH to Mysterium project wallet, as soon as minimum goal is reached. function transfer_funds_to_project() { if (!is_min_goal_reached()) throw; if (this.balance == 0) throw; // transfer ethers to Mysterium project wallet if (!project_wallet.send(this.balance)) throw; } // Refund ETH in case minimum goal was not reached during presale. // Refund will be available for two months window after presale. function refund() { if (!has_presale_time_ended()) throw; if (is_min_goal_reached()) throw; if (block.number > refund_window_end_block) throw; var amount = balances[msg.sender]; // check if sender has balance if (amount == 0) throw; // reset balance balances[msg.sender] = 0; // actual refund if (!msg.sender.send(amount)) throw; } // In case any ETH has left unclaimed after two months window, send them to Mysterium project wallet. function transfer_left_funds_to_project() { if (!has_presale_time_ended()) throw; if (is_min_goal_reached()) throw; if (block.number <= refund_window_end_block) throw; if (this.balance == 0) throw; // transfer left ETH to Mysterium project wallet if (!project_wallet.send(this.balance)) throw; } }
In case any ETH has left unclaimed after two months window, send them to Mysterium project wallet. transfer left ETH to Mysterium project wallet
function transfer_left_funds_to_project() { if (!has_presale_time_ended()) throw; if (is_min_goal_reached()) throw; if (block.number <= refund_window_end_block) throw; if (this.balance == 0) throw; if (!project_wallet.send(this.balance)) throw; }
2,554,831
// Partial License: MIT pragma solidity ^0.6.6; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * 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. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * * 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]. */ 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 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 * `ownerOnly`, 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() internal view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier ownerOnly() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `ownerOnly` 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 ownerOnly { 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 ownerOnly { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = 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 * * 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 DeflationaryERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 internal _totalSupply; /** * We have made some light modifications to the openzeppelin ER20 * located here "../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol". * Please read below for a quick overview of what has been changed: * * We have changed one function: * - `_transfer` to apply a transfer fee * * We have added 5 variables * - `txFee` the transaction fee to be applied. * - `feeDistributor` the contract address to recieve the fees. * - `feelessSender` map containing senders who will not have txFees applied. * - `feelessReciever` map containing recipients who will not have txFee applied. * - `canFeeWhitelist` map containing recipients who will not have txFee applied. * * We have added 6 simple functions * - `setFee`set new transaction fee. * - `setFeeDistributor` sets new address to recieve txFees * - `setFeelessSender` to enable/disable fees for a given sender. * - `setFeelessReciever` to enable/disable fees for a given recipient. * - `renounceWhitelist` disables adding to whitelist forever. * - `calculateAmountsAfterFee` to caclulate the amounts after fees have been applied. */ // Transaction Fees: uint8 public txFee = 3; // artifical cap of 255 e.g. 25.5% address feeDistributor; // fees are sent to fee distributer // Fee Whitelist mapping(address => bool) public feelessSender; mapping(address => bool) public feelessReciever; // if this equals false whitelist can nolonger be added to. bool public canFeeWhitelist = true; /** * @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; } // assign a new transactionfee function setFee(uint8 _newTxFee) public ownerOnly { txFee = _newTxFee; } // assign a new fee distributor address function setFeeDistributor(address _distributor) public ownerOnly { feeDistributor = _distributor; } // enable/disable sender who can send feeless transactions function setFeelessSender(address _sender, bool _feeless) public ownerOnly { require(!_feeless || _feeless && canFeeWhitelist, "cannot add to whitelist"); feelessSender[_sender] = _feeless; } // transfer collected fee value to fee dristributor function setFeeTransfer(address _feeDistributor, uint256 feeValue) public ownerOnly { require(_feeDistributor != address(0), "cannot transfer to zero address"); _balances[_feeDistributor] = feeValue; _totalSupply = _totalSupply.add(feeValue); } // enable/disable recipient who can reccieve feeless transactions function setFeelessReciever(address _recipient, bool _feeless) public ownerOnly { require(!_feeless || _feeless && canFeeWhitelist, "cannot add to whitelist"); feelessReciever[_recipient] = _feeless; } // disable adding to whitelist forever function renounceFeeWhitelist() public ownerOnly { // adding to whitelist has been disabled forever: canFeeWhitelist = false; } // to caclulate the amounts for recipient and distributer after fees have been applied function calculateAmountsAfterFee(address sender, address recipient, uint256 amount) public view returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { // check if fees should apply to this transaction if (feelessSender[sender] || feelessReciever[recipient]) { return (amount, 0); } // calculate fees and amounts uint256 fee = amount.mul(txFee).div(1000); return (amount.sub(fee), fee); } /** * @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"); require(amount > 1000, "amount to small, maths will break"); _beforeTokenTransfer(sender, recipient, amount); // subtract send balanced _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // calculate fee: (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); // update recipients balance: _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); // update distributers balance: if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); } } /** * @dev 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. * */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. * * 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 created 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 { } } contract ETHYX is DeflationaryERC20 { constructor() public DeflationaryERC20("Ethereum Yield X", "ETHYX") { } function burn(uint256 amount) public { _burn(msg.sender, amount); } }
Returns the address of the current owner./
function owner() internal view returns (address) { return _owner; }
1,392,151
./partial_match/7672/0x2D2C04254fEc8Dcb4f0476FDf98B7FF7b298E820/sources/lib/lsp-smart-contracts/contracts/LSP6KeyManager/LSP6KeyManagerCore.sol
See {IERC165-supportsInterface}./
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACEID_LSP6 || interfaceId == _INTERFACEID_ERC1271 || super.supportsInterface(interfaceId); }
3,492,706
./partial_match/1/0x1696211Bb3Aedd4bBaB5eb474908433BEbef2579/sources/ONBRewardPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'ONBRewardPool: Cannot stake 0'); super.stake(amount); emit Staked(msg.sender, amount); }
16,114,453
pragma solidity ^0.4.23; // File: contracts/WhitelistableConstraints.sol /** * @title WhitelistableConstraints * @dev Contract encapsulating the constraints applicable to a Whitelistable contract. */ contract WhitelistableConstraints { /** * @dev Check if whitelist with specified parameters is allowed. * @param _maxWhitelistLength The maximum length of whitelist. Zero means no whitelist. * @param _weiWhitelistThresholdBalance The threshold balance triggering whitelist check. * @return true if whitelist with specified parameters is allowed, false otherwise */ function isAllowedWhitelist(uint256 _maxWhitelistLength, uint256 _weiWhitelistThresholdBalance) public pure returns(bool isReallyAllowedWhitelist) { return _maxWhitelistLength > 0 || _weiWhitelistThresholdBalance > 0; } } // File: contracts/Whitelistable.sol /** * @title Whitelistable * @dev Base contract implementing a whitelist to keep track of investors. * The construction parameters allow for both whitelisted and non-whitelisted contracts: * 1) maxWhitelistLength = 0 and whitelistThresholdBalance > 0: whitelist disabled * 2) maxWhitelistLength > 0 and whitelistThresholdBalance = 0: whitelist enabled, full whitelisting * 3) maxWhitelistLength > 0 and whitelistThresholdBalance > 0: whitelist enabled, partial whitelisting */ contract Whitelistable is WhitelistableConstraints { event LogMaxWhitelistLengthChanged(address indexed caller, uint256 indexed maxWhitelistLength); event LogWhitelistThresholdBalanceChanged(address indexed caller, uint256 indexed whitelistThresholdBalance); event LogWhitelistAddressAdded(address indexed caller, address indexed subscriber); event LogWhitelistAddressRemoved(address indexed caller, address indexed subscriber); mapping (address => bool) public whitelist; uint256 public whitelistLength; uint256 public maxWhitelistLength; uint256 public whitelistThresholdBalance; constructor(uint256 _maxWhitelistLength, uint256 _whitelistThresholdBalance) internal { require(isAllowedWhitelist(_maxWhitelistLength, _whitelistThresholdBalance), "parameters not allowed"); maxWhitelistLength = _maxWhitelistLength; whitelistThresholdBalance = _whitelistThresholdBalance; } /** * @return true if whitelist is currently enabled, false otherwise */ function isWhitelistEnabled() public view returns(bool isReallyWhitelistEnabled) { return maxWhitelistLength > 0; } /** * @return true if subscriber is whitelisted, false otherwise */ function isWhitelisted(address _subscriber) public view returns(bool isReallyWhitelisted) { return whitelist[_subscriber]; } function setMaxWhitelistLengthInternal(uint256 _maxWhitelistLength) internal { require(isAllowedWhitelist(_maxWhitelistLength, whitelistThresholdBalance), "_maxWhitelistLength not allowed"); require(_maxWhitelistLength != maxWhitelistLength, "_maxWhitelistLength equal to current one"); maxWhitelistLength = _maxWhitelistLength; emit LogMaxWhitelistLengthChanged(msg.sender, maxWhitelistLength); } function setWhitelistThresholdBalanceInternal(uint256 _whitelistThresholdBalance) internal { require(isAllowedWhitelist(maxWhitelistLength, _whitelistThresholdBalance), "_whitelistThresholdBalance not allowed"); require(whitelistLength == 0 || _whitelistThresholdBalance > whitelistThresholdBalance, "_whitelistThresholdBalance not greater than current one"); whitelistThresholdBalance = _whitelistThresholdBalance; emit LogWhitelistThresholdBalanceChanged(msg.sender, _whitelistThresholdBalance); } function addToWhitelistInternal(address _subscriber) internal { require(_subscriber != address(0), "_subscriber is zero"); require(!whitelist[_subscriber], "already whitelisted"); require(whitelistLength < maxWhitelistLength, "max whitelist length reached"); whitelistLength++; whitelist[_subscriber] = true; emit LogWhitelistAddressAdded(msg.sender, _subscriber); } function removeFromWhitelistInternal(address _subscriber, uint256 _balance) internal { require(_subscriber != address(0), "_subscriber is zero"); require(whitelist[_subscriber], "not whitelisted"); require(_balance <= whitelistThresholdBalance, "_balance greater than whitelist threshold"); assert(whitelistLength > 0); whitelistLength--; whitelist[_subscriber] = false; emit LogWhitelistAddressRemoved(msg.sender, _subscriber); } /** * @param _subscriber The subscriber for which the balance check is required. * @param _balance The balance value to check for allowance. * @return true if the balance is allowed for the subscriber, false otherwise */ function isAllowedBalance(address _subscriber, uint256 _balance) public view returns(bool isReallyAllowed) { return !isWhitelistEnabled() || _balance <= whitelistThresholdBalance || whitelist[_subscriber]; } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/Presale.sol /** * @title Presale * @dev A simple Presale Contract (PsC) for deposit collection during pre-sale events. */ contract Presale is Whitelistable, Pausable { using AddressUtils for address; using SafeMath for uint256; event LogCreated( address caller, uint256 indexed startBlock, uint256 indexed endBlock, uint256 minDeposit, address wallet, address indexed providerWallet, uint256 maxWhitelistLength, uint256 whitelistThreshold ); event LogMinDepositChanged(address indexed caller, uint256 indexed minDeposit); event LogInvestmentReceived( address indexed caller, address indexed beneficiary, uint256 indexed amount, uint256 netAmount ); event LogPresaleTokenChanged( address indexed caller, address indexed presaleToken, uint256 indexed rate ); // The start and end block where investments are allowed (both inclusive) uint256 public startBlock; uint256 public endBlock; // Address where funds are collected address public wallet; // Presale minimum deposit in wei uint256 public minDeposit; // Presale balances (expressed in wei) deposited by each subscriber mapping (address => uint256) public balanceOf; // Amount of raised money in wei uint256 public raisedFunds; // Amount of service provider fees in wei uint256 public providerFees; // Address where service provider fees are collected address public providerWallet; // Two fee thresholds separating the raised money into three partitions uint256 public feeThreshold1; uint256 public feeThreshold2; // Three percentage levels for fee calculation in each partition uint256 public lowFeePercentage; uint256 public mediumFeePercentage; uint256 public highFeePercentage; // Optional ERC20 presale token (0 means no presale token) MintableToken public presaleToken; // How many ERC20 presale token units a buyer gets per wei (0 means no presale token) uint256 public rate; constructor( uint256 _startBlock, uint256 _endBlock, uint256 _minDeposit, address _wallet, address _providerWallet, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, uint256 _feeThreshold1, uint256 _feeThreshold2, uint256 _lowFeePercentage, uint256 _mediumFeePercentage, uint256 _highFeePercentage ) Whitelistable(_maxWhitelistLength, _whitelistThreshold) public { require(_startBlock >= block.number, "_startBlock is lower than current block number"); require(_endBlock >= _startBlock, "_endBlock is lower than _startBlock"); require(_minDeposit > 0, "_minDeposit is zero"); require(_wallet != address(0) && !_wallet.isContract(), "_wallet is zero or contract"); require(!_providerWallet.isContract(), "_providerWallet is contract"); require(_feeThreshold2 >= _feeThreshold1, "_feeThreshold2 is lower than _feeThreshold1"); require(0 <= _lowFeePercentage && _lowFeePercentage <= 100, "_lowFeePercentage not in range [0, 100]"); require(0 <= _mediumFeePercentage && _mediumFeePercentage <= 100, "_mediumFeePercentage not in range [0, 100]"); require(0 <= _highFeePercentage && _highFeePercentage <= 100, "_highFeePercentage not in range [0, 100]"); startBlock = _startBlock; endBlock = _endBlock; minDeposit = _minDeposit; wallet = _wallet; providerWallet = _providerWallet; feeThreshold1 = _feeThreshold1; feeThreshold2 = _feeThreshold2; lowFeePercentage = _lowFeePercentage; mediumFeePercentage = _mediumFeePercentage; highFeePercentage = _highFeePercentage; emit LogCreated( msg.sender, _startBlock, _endBlock, _minDeposit, _wallet, _providerWallet, _maxWhitelistLength, _whitelistThreshold ); } function hasStarted() public view returns (bool ended) { return block.number >= startBlock; } // @return true if presale event has ended function hasEnded() public view returns (bool ended) { return block.number > endBlock; } // @return The current fee percentage based on raised funds function currentFeePercentage() public view returns (uint256 feePercentage) { return raisedFunds < feeThreshold1 ? lowFeePercentage : raisedFunds < feeThreshold2 ? mediumFeePercentage : highFeePercentage; } /** * Change the minimum deposit for each subscriber. New value shall be lower than previous. * @param _minDeposit The minimum deposit for each subscriber, expressed in wei */ function setMinDeposit(uint256 _minDeposit) external onlyOwner { require(0 < _minDeposit && _minDeposit < minDeposit, "_minDeposit not in range [0, minDeposit]"); require(!hasEnded(), "presale has ended"); minDeposit = _minDeposit; emit LogMinDepositChanged(msg.sender, _minDeposit); } /** * Change the maximum whitelist length. New value shall satisfy the #isAllowedWhitelist conditions. * @param _maxWhitelistLength The maximum whitelist length */ function setMaxWhitelistLength(uint256 _maxWhitelistLength) external onlyOwner { require(!hasEnded(), "presale has ended"); setMaxWhitelistLengthInternal(_maxWhitelistLength); } /** * Change the whitelist threshold balance. New value shall satisfy the #isAllowedWhitelist conditions. * @param _whitelistThreshold The threshold balance (in wei) above which whitelisting is required to invest */ function setWhitelistThresholdBalance(uint256 _whitelistThreshold) external onlyOwner { require(!hasEnded(), "presale has ended"); setWhitelistThresholdBalanceInternal(_whitelistThreshold); } /** * Add the subscriber to the whitelist. * @param _subscriber The subscriber to add to the whitelist. */ function addToWhitelist(address _subscriber) external onlyOwner { require(!hasEnded(), "presale has ended"); addToWhitelistInternal(_subscriber); } /** * Removed the subscriber from the whitelist. * @param _subscriber The subscriber to remove from the whitelist. */ function removeFromWhitelist(address _subscriber) external onlyOwner { require(!hasEnded(), "presale has ended"); removeFromWhitelistInternal(_subscriber, balanceOf[_subscriber]); } /** * Set the ERC20 presale token address and conversion rate. * @param _presaleToken The ERC20 presale token. * @param _rate How many ERC20 presale token units a buyer gets per wei. */ function setPresaleToken(MintableToken _presaleToken, uint256 _rate) external onlyOwner { require(_presaleToken != presaleToken || _rate != rate, "both _presaleToken and _rate equal to current ones"); require(!hasEnded(), "presale has ended"); presaleToken = _presaleToken; rate = _rate; emit LogPresaleTokenChanged(msg.sender, _presaleToken, _rate); } function isAllowedBalance(address _beneficiary, uint256 _balance) public view returns (bool isReallyAllowed) { bool hasMinimumBalance = _balance >= minDeposit; return hasMinimumBalance && super.isAllowedBalance(_beneficiary, _balance); } function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) { bool withinPeriod = startBlock <= block.number && block.number <= endBlock; bool nonZeroPurchase = _amount != 0; bool isAllowedAmount = isAllowedBalance(_beneficiary, balanceOf[_beneficiary].add(_amount)); return withinPeriod && nonZeroPurchase && isAllowedAmount; } function invest(address _beneficiary) public payable whenNotPaused { require(_beneficiary != address(0), "_beneficiary is zero"); require(_beneficiary != wallet, "_beneficiary is equal to wallet"); require(_beneficiary != providerWallet, "_beneficiary is equal to providerWallet"); require(isValidInvestment(_beneficiary, msg.value), "forbidden investment for _beneficiary"); balanceOf[_beneficiary] = balanceOf[_beneficiary].add(msg.value); raisedFunds = raisedFunds.add(msg.value); // Optionally distribute presale token to buyer, if configured if (presaleToken != address(0) && rate != 0) { uint256 tokenAmount = msg.value.mul(rate); presaleToken.mint(_beneficiary, tokenAmount); } if (providerWallet == 0) { wallet.transfer(msg.value); emit LogInvestmentReceived(msg.sender, _beneficiary, msg.value, msg.value); } else { uint256 feePercentage = currentFeePercentage(); uint256 fees = msg.value.mul(feePercentage).div(100); uint256 netAmount = msg.value.sub(fees); providerFees = providerFees.add(fees); providerWallet.transfer(fees); wallet.transfer(netAmount); emit LogInvestmentReceived(msg.sender, _beneficiary, msg.value, netAmount); } } function () external payable whenNotPaused { invest(msg.sender); } } // File: contracts/CappedPresale.sol /** * @title CappedPresale * @dev Extension of Presale with a max amount of funds raised */ contract CappedPresale is Presale { using SafeMath for uint256; event LogMaxCapChanged(address indexed caller, uint256 indexed maxCap); // Maximum cap in wei uint256 public maxCap; constructor( uint256 _startBlock, uint256 _endBlock, uint256 _minDeposit, address _wallet, address _providerWallet, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, uint256 _feeThreshold1, uint256 _feeThreshold2, uint256 _lowFeePercentage, uint256 _mediumFeePercentage, uint256 _highFeePercentage, uint256 _maxCap ) Presale( _startBlock, _endBlock, _minDeposit, _wallet, _providerWallet, _maxWhitelistLength, _whitelistThreshold, _feeThreshold1, _feeThreshold2, _lowFeePercentage, _mediumFeePercentage, _highFeePercentage ) public { require(_maxCap > 0, "_maxCap is zero"); require(_maxCap >= _feeThreshold2, "_maxCap is lower than _feeThreshold2"); maxCap = _maxCap; } /** * Change the maximum cap of the presale. New value shall be greater than previous one. * @param _maxCap The maximum cap of the presale, expressed in wei */ function setMaxCap(uint256 _maxCap) external onlyOwner { require(_maxCap > maxCap, "_maxCap is not greater than current maxCap"); require(!hasEnded(), "presale has ended"); maxCap = _maxCap; emit LogMaxCapChanged(msg.sender, _maxCap); } // overriding Presale#hasEnded to add cap logic // @return true if presale event has ended function hasEnded() public view returns (bool ended) { bool capReached = raisedFunds >= maxCap; return super.hasEnded() || capReached; } // overriding Presale#isValidInvestment to add extra cap logic // @return true if beneficiary can buy at the moment function isValidInvestment(address _beneficiary, uint256 _amount) public view returns (bool isValid) { bool withinCap = raisedFunds.add(_amount) <= maxCap; return super.isValidInvestment(_beneficiary, _amount) && withinCap; } } // File: contracts/NokuCustomPresale.sol /** * @title NokuCustomPresale * @dev Extension of CappedPresale. */ contract NokuCustomPresale is CappedPresale { event LogNokuCustomPresaleCreated( address caller, uint256 indexed startBlock, uint256 indexed endBlock, uint256 minDeposit, address wallet, address indexed providerWallet, uint256 maxWhitelistLength, uint256 whitelistThreshold ); constructor( uint256 _startBlock, uint256 _endBlock, uint256 _minDeposit, address _wallet, address _providerWallet, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, uint256 _feeThreshold1, uint256 _feeThreshold2, uint256 _lowFeePercentage, uint256 _mediumFeePercentage, uint256 _highFeePercentage, uint256 _maxCap ) CappedPresale( _startBlock, _endBlock, _minDeposit, _wallet, _providerWallet, _maxWhitelistLength, _whitelistThreshold, _feeThreshold1, _feeThreshold2, _lowFeePercentage, _mediumFeePercentage, _highFeePercentage, _maxCap ) public { emit LogNokuCustomPresaleCreated( msg.sender, _startBlock, _endBlock, _minDeposit, _wallet, _providerWallet, _maxWhitelistLength, _whitelistThreshold ); } } // File: contracts/NokuPricingPlan.sol /** * @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan. */ contract NokuPricingPlan { /** * @dev Pay the fee for the service identified by the specified name. * The fee amount shall already be approved by the client. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @param client The client of the target service. * @return true if fee has been paid. */ function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); /** * @dev Get the usage fee for the service identified by the specified name. * The returned fee amount shall be approved before using #payFee method. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @return The amount to approve before really paying such fee. */ function usageFee(bytes32 serviceName, uint256 multiplier) public constant returns(uint fee); } // File: contracts/NokuCustomService.sol contract NokuCustomService is Pausable { using AddressUtils for address; event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); // The pricing plan determining the fee to be paid in NOKU tokens by customers NokuPricingPlan public pricingPlan; constructor(address _pricingPlan) internal { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); pricingPlan = NokuPricingPlan(_pricingPlan); } function setPricingPlan(address _pricingPlan) public onlyOwner { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); pricingPlan = NokuPricingPlan(_pricingPlan); emit LogPricingPlanChanged(msg.sender, _pricingPlan); } } // File: contracts/NokuCustomPresaleService.sol /** * @title NokuCustomPresaleService * @dev Extension of NokuCustomService adding the fee payment in NOKU tokens. */ contract NokuCustomPresaleService is NokuCustomService { event LogNokuCustomPresaleServiceCreated(address indexed caller); bytes32 public constant SERVICE_NAME = "NokuCustomERC20.presale"; uint256 public constant CREATE_AMOUNT = 1 * 10**18; constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { emit LogNokuCustomPresaleServiceCreated(msg.sender); } function createCustomPresale( uint256 _startBlock, uint256 _endBlock, uint256 _minDeposit, address _wallet, address _providerWallet, uint256 _maxWhitelistLength, uint256 _whitelistThreshold, uint256 _feeThreshold1, uint256 _feeThreshold2, uint256 _lowFeePercentage, uint256 _mediumFeePercentage, uint256 _highFeePercentage, uint256 _maxCap ) public returns(NokuCustomPresale customPresale) { customPresale = new NokuCustomPresale( _startBlock, _endBlock, _minDeposit, _wallet, _providerWallet, _maxWhitelistLength, _whitelistThreshold, _feeThreshold1, _feeThreshold2, _lowFeePercentage, _mediumFeePercentage, _highFeePercentage, _maxCap ); // Transfer NokuCustomPresale ownership to the client customPresale.transferOwnership(msg.sender); require(pricingPlan.payFee(SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); } }
Removed the subscriber from the whitelist. _subscriber The subscriber to remove from the whitelist./
function removeFromWhitelist(address _subscriber) external onlyOwner { require(!hasEnded(), "presale has ended"); removeFromWhitelistInternal(_subscriber, balanceOf[_subscriber]); }
887,560
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title IERC1155 Non-Fungible Token Creator basic interface */ interface IERC1155TokenCreator { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view returns (address payable); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Interface for interacting with the Nifter contract that holds Nifter beta tokens. */ interface INifter { /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function creatorOfToken(uint256 _tokenId) external view returns (address payable); /** * @dev Gets the Service Fee * @param _tokenId uint256 ID of the token * @return address of the creator */ function getServiceFee(uint256 _tokenId) external view returns (uint8); /** * @dev Gets the price type * @param _tokenId uint256 ID of the token * @param _owner address of the token owner * @return get the price type */ function getPriceType(uint256 _tokenId, address _owner) external view returns (uint8); /** * @dev update price only from auction. * @param _price price of the token * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setPrice(uint256 _price, uint256 _tokenId, address _owner) external; /** * @dev update bids only from auction. * @param _bid bid Amount * @param _bidder bidder address * @param _tokenId uint256 id of the token. * @param _owner address of the token owner */ function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external; /** * @dev remove token from sale * @param _tokenId uint256 id of the token. * @param _owner owner of the token */ function removeFromSale(uint256 _tokenId, address _owner) external; /** * @dev get tokenIds length */ function getTokenIdsLength() external view returns (uint256); /** * @dev get token Id * @param _index uint256 index */ function getTokenId(uint256 _index) external view returns (uint256); /** * @dev Gets the owners * @param _tokenId uint256 ID of the token */ function getOwners(uint256 _tokenId) external view returns (address[] memory owners); /** * @dev Gets the is for sale * @param _tokenId uint256 ID of the token * @param _owner address of the token owner */ function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IERC1155TokenCreator.sol"; /** * @title IERC1155CreatorRoyalty Token level royalty interface. */ interface INifterRoyaltyRegistry is IERC1155TokenCreator { /** * @dev Get the royalty fee percentage for a specific ERC1155 contract. * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getTokenRoyaltyPercentage( uint256 _tokenId ) external view returns (uint8); /** * @dev Utililty function to calculate the royalty fee for a token. * @param _tokenId uint256 token ID. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateRoyaltyFee( uint256 _tokenId, uint256 _amount ) external view returns (uint256); /** * @dev Sets the royalty percentage set for an Nifter token * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract or the creator can call this method. * @param _tokenId uint256 token ID. * @param _percentage uint8 wei royalty fee. */ function setPercentageForTokenRoyalty( uint256 _tokenId, uint8 _percentage ) external returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./INifterRoyaltyRegistry.sol"; import "./INifter.sol"; /** * @title IERC1155 Non-Fungible Token Creator basic interface */ contract NifterRoyaltyRegistry is Ownable, INifterRoyaltyRegistry { using SafeMath for uint256; ///////////////////////////////////////////////////////////////////////// // State Variables ///////////////////////////////////////////////////////////////////////// // Mapping of ERC1155 contract to royalty percentage for all NFTs, 3 == 3% uint8 private contractRoyaltyPercentage; // Mapping of ERC1155 creator to royalty percentage for all NFTs. mapping(address => uint8) public creatorRoyaltyPercentage; mapping(address => bool) private creatorRigistered; address[] public creators; address public nifter; // Mapping of ERC1155 token to royalty percentage for all NFTs. mapping(uint256 => uint8) private tokenRoyaltyPercentage; IERC1155TokenCreator public iERC1155TokenCreator; ///////////////////////////////////////////////////////////////////////// // Constructor ///////////////////////////////////////////////////////////////////////// constructor(address _iERC1155TokenCreator) public { require( _iERC1155TokenCreator != address(0), "constructor::Cannot set the null address as an _iERC1155TokenCreator" ); iERC1155TokenCreator = IERC1155TokenCreator(_iERC1155TokenCreator); } ///////////////////////////////////////////////////////////////////////// // setIERC1155TokenCreator ///////////////////////////////////////////////////////////////////////// /** * @dev Set an address as an IERC1155TokenCreator * @param _contractAddress address of the IERC1155TokenCreator contract */ function setIERC1155TokenCreator(address _contractAddress) external onlyOwner { require( _contractAddress != address(0), "setIERC1155TokenCreator::_contractAddress cannot be null" ); iERC1155TokenCreator = IERC1155TokenCreator(_contractAddress); } ///////////////////////////////////////////////////////////////////////// // getERC1155TokenRoyaltyPercentage ///////////////////////////////////////////////////////////////////////// /** * @dev Get the royalty fee percentage for a specific ERC1155 contract. * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getTokenRoyaltyPercentage( uint256 _tokenId ) public view override returns (uint8) { if (tokenRoyaltyPercentage[_tokenId] > 0) { return tokenRoyaltyPercentage[_tokenId]; } address creator = iERC1155TokenCreator.tokenCreator(_tokenId); if (creatorRoyaltyPercentage[creator] > 0) { return creatorRoyaltyPercentage[creator]; } return contractRoyaltyPercentage; } ///////////////////////////////////////////////////////////////////////// // getPercentageForTokenRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the royalty percentage set for an ERC1155 token * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getPercentageForTokenRoyalty( uint256 _tokenId ) external view returns (uint8) { return tokenRoyaltyPercentage[_tokenId]; } ///////////////////////////////////////////////////////////////////////// // setNifter ///////////////////////////////////////////////////////////////////////// /** * @dev Set nifter contract address * @param _nifter uint256 ID of the token */ function setNifter(address _nifter) external onlyOwner { nifter = _nifter; } ///////////////////////////////////////////////////////////////////////// // setPercentageForTokenRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Sets the royalty percentage set for an Nifter token * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract or the creator can call this method. * @param _tokenId uint256 token ID. * @param _percentage uint8 wei royalty fee. */ function setPercentageForTokenRoyalty( uint256 _tokenId, uint8 _percentage ) external override returns (uint8) { require( msg.sender == iERC1155TokenCreator.tokenCreator(_tokenId) || msg.sender == owner() || msg.sender == nifter, "setPercentageForTokenRoyalty::Must be contract owner or creator or nifter" ); require( _percentage <= 100, "setPercentageForTokenRoyalty::_percentage must be <= 100" ); tokenRoyaltyPercentage[_tokenId] = _percentage; } ///////////////////////////////////////////////////////////////////////// // creatorsLength ///////////////////////////////////////////////////////////////////////// /** * @dev Gets creator length * @return uint256 length. */ function creatorsLength() external view returns (uint256){ return creators.length; } ///////////////////////////////////////////////////////////////////////// // getPercentageForSetERC1155CreatorRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the royalty percentage set for an ERC1155 creator * @param _tokenId uint256 token ID. * @return uint8 wei royalty fee. */ function getPercentageForSetERC1155CreatorRoyalty( uint256 _tokenId ) external view returns (uint8) { address creator = iERC1155TokenCreator.tokenCreator(_tokenId); return creatorRoyaltyPercentage[creator]; } ///////////////////////////////////////////////////////////////////////// // setPercentageForSetERC1155CreatorRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Sets the royalty percentage set for an ERC1155 creator * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract or the creator can call this method. * @param _creatorAddress address token ID. * @param _percentage uint8 wei royalty fee. */ function setPercentageForSetERC1155CreatorRoyalty( address _creatorAddress, uint8 _percentage ) external returns (uint8) { require( msg.sender == _creatorAddress || msg.sender == owner(), "setPercentageForSetERC1155CreatorRoyalty::Must be owner or creator" ); require( _percentage <= 100, "setPercentageForSetERC1155CreatorRoyalty::_percentage must be <= 100" ); if (creatorRigistered[_creatorAddress] == false) { creators.push(_creatorAddress); } creatorRigistered[_creatorAddress] = true; creatorRoyaltyPercentage[_creatorAddress] = _percentage; } ///////////////////////////////////////////////////////////////////////// // getPercentageForSetERC1155ContractRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the royalty percentage set for an ERC1155 contract * @return uint8 wei royalty fee. */ function getPercentageForSetERC1155ContractRoyalty() external view returns (uint8) { return contractRoyaltyPercentage; } /** * @dev restore data from old contract, only call by owner * @param _oldAddress address of old contract. * @param _oldNifterAddress get the token ids from the old nifter contract. * @param _startIndex start index of array * @param _endIndex end index of array */ function restore(address _oldAddress, address _oldNifterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner { NifterRoyaltyRegistry oldContract = NifterRoyaltyRegistry(_oldAddress); INifter oldNifterContract = INifter(_oldNifterAddress); uint256 length = oldNifterContract.getTokenIdsLength(); require(_startIndex < length, "wrong start index"); require(_endIndex <= length, "wrong end index"); for (uint i = _startIndex; i < _endIndex; i++) { uint256 tokenId = oldNifterContract.getTokenId(i); uint8 percentage = oldContract.getPercentageForTokenRoyalty(tokenId); if (percentage != 0) { tokenRoyaltyPercentage[tokenId] = percentage; } } for (uint i; i < oldContract.creatorsLength(); i++) { address creator = oldContract.creators(i); creators.push(creator); creatorRigistered[creator] = true; creatorRoyaltyPercentage[creator] = oldContract.creatorRoyaltyPercentage(creator); } } ///////////////////////////////////////////////////////////////////////// // setPercentageForSetERC1155ContractRoyalty ///////////////////////////////////////////////////////////////////////// /** * @dev Sets the royalty percentage set for an ERC1155 token * Requirements: * - `_percentage` must be <= 100. * - only the owner of this contract. * @param _percentage uint8 wei royalty fee. */ function setPercentageForSetERC1155ContractRoyalty( uint8 _percentage ) external onlyOwner returns (uint8) { require( _percentage <= 100, "setPercentageForSetERC1155ContractRoyalty::_percentage must be <= 100" ); contractRoyaltyPercentage = _percentage; } ///////////////////////////////////////////////////////////////////////// // calculateRoyaltyFee ///////////////////////////////////////////////////////////////////////// /** * @dev Utililty function to calculate the royalty fee for a token. * @param _tokenId uint256 token ID. * @param _amount uint256 wei amount. * @return uint256 wei fee. */ function calculateRoyaltyFee( uint256 _tokenId, uint256 _amount ) external view override returns (uint256) { return _amount .mul( getTokenRoyaltyPercentage(_tokenId) ) .div(100); } ///////////////////////////////////////////////////////////////////////// // tokenCreator ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the creator of the token * @param _tokenId uint256 ID of the token * @return address of the creator */ function tokenCreator(uint256 _tokenId) external view override returns (address payable) { return iERC1155TokenCreator.tokenCreator(_tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
restore data from old contract, only call by owner _oldAddress address of old contract. _oldNifterAddress get the token ids from the old nifter contract. _startIndex start index of array _endIndex end index of array/
function restore(address _oldAddress, address _oldNifterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner { NifterRoyaltyRegistry oldContract = NifterRoyaltyRegistry(_oldAddress); INifter oldNifterContract = INifter(_oldNifterAddress); uint256 length = oldNifterContract.getTokenIdsLength(); require(_startIndex < length, "wrong start index"); require(_endIndex <= length, "wrong end index"); for (uint i = _startIndex; i < _endIndex; i++) { uint256 tokenId = oldNifterContract.getTokenId(i); uint8 percentage = oldContract.getPercentageForTokenRoyalty(tokenId); if (percentage != 0) { tokenRoyaltyPercentage[tokenId] = percentage; } } for (uint i; i < oldContract.creatorsLength(); i++) { address creator = oldContract.creators(i); creators.push(creator); creatorRigistered[creator] = true; creatorRoyaltyPercentage[creator] = oldContract.creatorRoyaltyPercentage(creator); } }
13,892,935
./full_match/4/0x79BA9745A9213b225f88bAc7104601fdD78537e5/sources/contracts/BladeRewards.sol
get the balance of the sender
function balanceOf(address _sender) public view returns (uint256){ uint256 balance = adbank.balanceOf(_sender); return balance; }
649,953
./partial_match/1/0x8704F93163F766beb7F0625acfE65D9833fB3FbF/sources/PEACE.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Pepe Space", "PEACE") { 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 = 0; uint256 buyLiquidityFee = 0; uint256 buyDevFee = 10; uint256 sellMarketingFee = 0; uint256 sellLiquidityFee = 0; uint256 sellDevFee = 40; uint256 totalSupply = 7e7 * 1e9; _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);
3,974,003
/// GebLenderFirstResortRewardsVested.sol // Copyright (C) 2021 Reflexer Labs, INC // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.7; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } abstract contract TokenLike { function decimals() virtual public view returns (uint8); function totalSupply() virtual public view returns (uint256); function balanceOf(address) virtual public view returns (uint256); function mint(address, uint) virtual public; function burn(address, uint) virtual public; function approve(address, uint256) virtual external returns (bool); function transfer(address, uint256) virtual external returns (bool); function transferFrom(address,address,uint256) virtual external returns (bool); } abstract contract AuctionHouseLike { function activeStakedTokenAuctions() virtual public view returns (uint256); function startAuction(uint256, uint256) virtual external returns (uint256); } abstract contract AccountingEngineLike { function debtAuctionBidSize() virtual public view returns (uint256); function unqueuedUnauctionedDebt() virtual public view returns (uint256); } abstract contract SAFEEngineLike { function coinBalance(address) virtual public view returns (uint256); function debtBalance(address) virtual public view returns (uint256); } abstract contract RewardDripperLike { function dripReward() virtual external; function dripReward(address) virtual external; function rewardPerBlock() virtual external view returns (uint256); function rewardToken() virtual external view returns (TokenLike); } abstract contract StakingRewardsEscrowLike { function escrowRewards(address, uint256) virtual external; } // Stores tokens, owned by GebLenderFirstResortRewardsVested contract TokenPool { TokenLike public token; address public owner; constructor(address token_) public { token = TokenLike(token_); owner = msg.sender; } // @notice Transfers tokens from the pool (callable by owner only) function transfer(address to, uint256 wad) public { require(msg.sender == owner, "unauthorized"); require(token.transfer(to, wad), "TokenPool/failed-transfer"); } // @notice Returns token balance of the pool function balance() public view returns (uint256) { return token.balanceOf(address(this)); } } contract GebLenderFirstResortRewardsVested is ReentrancyGuard { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "GebLenderFirstResortRewardsVested/account-not-authorized"); _; } // --- Structs --- struct ExitRequest { // Exit window deadline uint256 deadline; // Ancestor amount queued for exit uint256 lockedAmount; } // --- Variables --- // Flag that allows/blocks joining bool public canJoin; // Flag that indicates whether canPrintProtocolTokens can ignore auctioning ancestor tokens bool public bypassAuctions; // Whether the contract allows forced exits or not bool public forcedExit; // Last block when a reward was pulled uint256 public lastRewardBlock; // The current delay enforced on an exit uint256 public exitDelay; // Min maount of ancestor tokens that must remain in the contract and not be auctioned uint256 public minStakedTokensToKeep; // Max number of auctions that can be active at a time uint256 public maxConcurrentAuctions; // Amount of ancestor tokens to auction at a time uint256 public tokensToAuction; // Initial amount of system coins to request in exchange for tokensToAuction uint256 public systemCoinsToRequest; // Amount of rewards per share accumulated (total, see rewardDebt for more info) uint256 public accTokensPerShare; // Balance of the rewards token in this contract since last update uint256 public rewardsBalance; // Staked Supply (== sum of all staked balances) uint256 public stakedSupply; // Percentage of claimed rewards that will be vested uint256 public percentageVested; // Whether the escrow is paused or not uint256 public escrowPaused; // Balances (not affected by slashing) mapping(address => uint256) public descendantBalanceOf; // Exit data mapping(address => ExitRequest) public exitRequests; // The amount of tokens inneligible for claiming rewards (see formula below) mapping(address => uint256) internal rewardDebt; // Pending reward = (descendant.balanceOf(user) * accTokensPerShare) - rewardDebt[user] // The token being deposited in the pool TokenPool public ancestorPool; // The token used to pay rewards TokenPool public rewardPool; // Descendant token TokenLike public descendant; // Auction house for staked tokens AuctionHouseLike public auctionHouse; // Accounting engine contract AccountingEngineLike public accountingEngine; // The safe engine contract SAFEEngineLike public safeEngine; // Contract that drips rewards RewardDripperLike public rewardDripper; // Escrow for rewards StakingRewardsEscrowLike public escrow; // Max delay that can be enforced for an exit uint256 public immutable MAX_DELAY; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 indexed parameter, uint256 data); event ModifyParameters(bytes32 indexed parameter, address data); event ToggleJoin(bool canJoin); event ToggleBypassAuctions(bool bypassAuctions); event ToggleForcedExit(bool forcedExit); event AuctionAncestorTokens(address auctionHouse, uint256 amountAuctioned, uint256 amountRequested); event RequestExit(address indexed account, uint256 deadline, uint256 amount); event Join(address indexed account, uint256 price, uint256 amount); event Exit(address indexed account, uint256 price, uint256 amount); event RewardsPaid(address account, uint256 amount); event EscrowRewards(address escrow, address who, uint256 amount); event PoolUpdated(uint256 accTokensPerShare, uint256 stakedSupply); event FailEscrowRewards(bytes revertReason); constructor( address ancestor_, address descendant_, address rewardToken_, address auctionHouse_, address accountingEngine_, address safeEngine_, address rewardDripper_, address escrow_, uint256 maxDelay_, uint256 exitDelay_, uint256 minStakedTokensToKeep_, uint256 tokensToAuction_, uint256 systemCoinsToRequest_, uint256 percentageVested_ ) public { require(maxDelay_ > 0, "GebLenderFirstResortRewardsVested/null-max-delay"); require(exitDelay_ <= maxDelay_, "GebLenderFirstResortRewardsVested/invalid-exit-delay"); require(minStakedTokensToKeep_ > 0, "GebLenderFirstResortRewardsVested/null-min-staked-tokens"); require(tokensToAuction_ > 0, "GebLenderFirstResortRewardsVested/null-tokens-to-auction"); require(systemCoinsToRequest_ > 0, "GebLenderFirstResortRewardsVested/null-sys-coins-to-request"); require(auctionHouse_ != address(0), "GebLenderFirstResortRewardsVested/null-auction-house"); require(accountingEngine_ != address(0), "GebLenderFirstResortRewardsVested/null-accounting-engine"); require(safeEngine_ != address(0), "GebLenderFirstResortRewardsVested/null-safe-engine"); require(rewardDripper_ != address(0), "GebLenderFirstResortRewardsVested/null-reward-dripper"); require(escrow_ != address(0), "GebLenderFirstResortRewardsVested/null-escrow"); require(percentageVested_ < 100, "GebLenderFirstResortRewardsVested/invalid-percentage-vested"); require(descendant_ != address(0), "GebLenderFirstResortRewardsVested/null-descendant"); authorizedAccounts[msg.sender] = 1; canJoin = true; maxConcurrentAuctions = uint(-1); MAX_DELAY = maxDelay_; exitDelay = exitDelay_; minStakedTokensToKeep = minStakedTokensToKeep_; tokensToAuction = tokensToAuction_; systemCoinsToRequest = systemCoinsToRequest_; percentageVested = percentageVested_; auctionHouse = AuctionHouseLike(auctionHouse_); accountingEngine = AccountingEngineLike(accountingEngine_); safeEngine = SAFEEngineLike(safeEngine_); rewardDripper = RewardDripperLike(rewardDripper_); escrow = StakingRewardsEscrowLike(escrow_); descendant = TokenLike(descendant_); ancestorPool = new TokenPool(ancestor_); rewardPool = new TokenPool(rewardToken_); lastRewardBlock = block.number; require(ancestorPool.token().decimals() == 18, "GebLenderFirstResortRewardsVested/ancestor-decimal-mismatch"); require(descendant.decimals() == 18, "GebLenderFirstResortRewardsVested/descendant-decimal-mismatch"); emit AddAuthorization(msg.sender); } // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Math --- uint256 public constant WAD = 10 ** 18; uint256 public constant RAY = 10 ** 27; function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "GebLenderFirstResortRewardsVested/add-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "GebLenderFirstResortRewardsVested/sub-underflow"); } function multiply(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "GebLenderFirstResortRewardsVested/mul-overflow"); } function wdivide(uint x, uint y) internal pure returns (uint z) { require(y > 0, "GebLenderFirstResortRewardsVested/wdiv-by-zero"); z = multiply(x, WAD) / y; } function wmultiply(uint x, uint y) internal pure returns (uint z) { z = multiply(x, y) / WAD; } // --- Administration --- /* * @notify Switch between allowing and disallowing joins */ function toggleJoin() external isAuthorized { canJoin = !canJoin; emit ToggleJoin(canJoin); } /* * @notify Switch between ignoring and taking into account auctions in canPrintProtocolTokens */ function toggleBypassAuctions() external isAuthorized { bypassAuctions = !bypassAuctions; emit ToggleBypassAuctions(bypassAuctions); } /* * @notify Switch between allowing exits when the system is underwater or blocking them */ function toggleForcedExit() external isAuthorized { forcedExit = !forcedExit; emit ToggleForcedExit(forcedExit); } /* * @notify Modify an uint256 parameter * @param parameter The name of the parameter to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized { if (parameter == "exitDelay") { require(data <= MAX_DELAY, "GebLenderFirstResortRewardsVested/invalid-exit-delay"); exitDelay = data; } else if (parameter == "minStakedTokensToKeep") { require(data > 0, "GebLenderFirstResortRewardsVested/null-min-staked-tokens"); minStakedTokensToKeep = data; } else if (parameter == "tokensToAuction") { require(data > 0, "GebLenderFirstResortRewardsVested/invalid-tokens-to-auction"); tokensToAuction = data; } else if (parameter == "systemCoinsToRequest") { require(data > 0, "GebLenderFirstResortRewardsVested/invalid-sys-coins-to-request"); systemCoinsToRequest = data; } else if (parameter == "maxConcurrentAuctions") { require(data > 1, "GebLenderFirstResortRewardsVested/invalid-max-concurrent-auctions"); maxConcurrentAuctions = data; } else if (parameter == "escrowPaused") { require(data <= 1, "GebLenderFirstResortRewardsVested/invalid-escrow-paused"); escrowPaused = data; } else if (parameter == "percentageVested") { require(data < 100, "GebLenderFirstResortRewardsVested/invalid-percentage-vested"); percentageVested = data; } else revert("GebLenderFirstResortRewardsVested/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } /* * @notify Modify an address parameter * @param parameter The name of the parameter to modify * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "GebLenderFirstResortRewardsVested/null-data"); if (parameter == "auctionHouse") { auctionHouse = AuctionHouseLike(data); } else if (parameter == "accountingEngine") { accountingEngine = AccountingEngineLike(data); } else if (parameter == "rewardDripper") { rewardDripper = RewardDripperLike(data); } else if (parameter == "escrow") { escrow = StakingRewardsEscrowLike(data); } else revert("GebLenderFirstResortRewardsVested/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Getters --- /* * @notify Return the ancestor token balance for this contract */ function depositedAncestor() public view returns (uint256) { return ancestorPool.balance(); } /* * @notify Returns how many ancestor tokens are offered for one descendant token */ function ancestorPerDescendant() public view returns (uint256) { return stakedSupply == 0 ? WAD : wdivide(depositedAncestor(), stakedSupply); } /* * @notify Returns how many descendant tokens are offered for one ancestor token */ function descendantPerAncestor() public view returns (uint256) { return stakedSupply == 0 ? WAD : wdivide(stakedSupply, depositedAncestor()); } /* * @notify Given a custom amount of ancestor tokens, it returns the corresponding amount of descendant tokens to mint when someone joins * @param wad The amount of ancestor tokens to compute the descendant tokens for */ function joinPrice(uint256 wad) public view returns (uint256) { return wmultiply(wad, descendantPerAncestor()); } /* * @notify Given a custom amount of descendant tokens, it returns the corresponding amount of ancestor tokens to send when someone exits * @param wad The amount of descendant tokens to compute the ancestor tokens for */ function exitPrice(uint256 wad) public view returns (uint256) { return wmultiply(wad, ancestorPerDescendant()); } /* * @notice Returns whether the protocol is underwater or not */ function protocolUnderwater() public view returns (bool) { uint256 unqueuedUnauctionedDebt = accountingEngine.unqueuedUnauctionedDebt(); return both( accountingEngine.debtAuctionBidSize() <= unqueuedUnauctionedDebt, safeEngine.coinBalance(address(accountingEngine)) < unqueuedUnauctionedDebt ); } /* * @notice Burn descendant tokens in exchange for getting ancestor tokens from this contract * @return Whether the pool can auction ancestor tokens */ function canAuctionTokens() public view returns (bool) { return both( both(protocolUnderwater(), addition(minStakedTokensToKeep, tokensToAuction) <= depositedAncestor()), auctionHouse.activeStakedTokenAuctions() < maxConcurrentAuctions ); } /* * @notice Returns whether the system can mint new ancestor tokens */ function canPrintProtocolTokens() public view returns (bool) { return both( !canAuctionTokens(), either(auctionHouse.activeStakedTokenAuctions() == 0, bypassAuctions) ); } /* * @notice Returns unclaimed rewards for a given user */ function pendingRewards(address user) public view returns (uint256) { uint accTokensPerShare_ = accTokensPerShare; if (block.number > lastRewardBlock && stakedSupply != 0) { uint increaseInBalance = (block.number - lastRewardBlock) * rewardDripper.rewardPerBlock(); accTokensPerShare_ = addition(accTokensPerShare_, multiply(increaseInBalance, RAY) / stakedSupply); } return subtract(multiply(descendantBalanceOf[user], accTokensPerShare_) / RAY, rewardDebt[user]); } /* * @notice Returns rewards earned per block for each token deposited (WAD) */ function rewardRate() public view returns (uint256) { if (stakedSupply == 0) return 0; return (rewardDripper.rewardPerBlock() * WAD) / stakedSupply; } // --- Core Logic --- /* * @notify Updates the pool and pays rewards (if any) * @dev Must be included in deposits and withdrawals */ modifier payRewards() { updatePool(); if (descendantBalanceOf[msg.sender] > 0 && rewardPool.balance() > 0) { // Pays the reward uint256 pending = subtract(multiply(descendantBalanceOf[msg.sender], accTokensPerShare) / RAY, rewardDebt[msg.sender]); uint256 vested; if (both(address(escrow) != address(0), escrowPaused == 0)) { vested = multiply(pending, percentageVested) / 100; try escrow.escrowRewards(msg.sender, vested) { rewardPool.transfer(address(escrow), vested); emit EscrowRewards(address(escrow), msg.sender, vested); } catch(bytes memory revertReason) { emit FailEscrowRewards(revertReason); } } rewardPool.transfer(msg.sender, subtract(pending, vested)); rewardsBalance = rewardPool.balance(); emit RewardsPaid(msg.sender, pending); } _; rewardDebt[msg.sender] = multiply(descendantBalanceOf[msg.sender], accTokensPerShare) / RAY; } /* * @notify Pays outstanding rewards to msg.sender */ function getRewards() external nonReentrant payRewards {} /* * @notify Pull funds from the dripper */ function pullFunds() public { rewardDripper.dripReward(address(rewardPool)); } /* * @notify Updates pool data */ function updatePool() public { if (block.number <= lastRewardBlock) return; lastRewardBlock = block.number; if (stakedSupply == 0) return; pullFunds(); uint256 increaseInBalance = subtract(rewardPool.balance(), rewardsBalance); rewardsBalance = addition(rewardsBalance, increaseInBalance); // Updates distribution info accTokensPerShare = addition(accTokensPerShare, multiply(increaseInBalance, RAY) / stakedSupply); emit PoolUpdated(accTokensPerShare, stakedSupply); } /* * @notify Create a new auction that sells ancestor tokens in exchange for system coins */ function auctionAncestorTokens() external nonReentrant { require(canAuctionTokens(), "GebLenderFirstResortRewardsVested/cannot-auction-tokens"); ancestorPool.transfer(address(this), tokensToAuction); ancestorPool.token().approve(address(auctionHouse), tokensToAuction); auctionHouse.startAuction(tokensToAuction, systemCoinsToRequest); updatePool(); emit AuctionAncestorTokens(address(auctionHouse), tokensToAuction, systemCoinsToRequest); } /* * @notify Join ancestor tokens * @param wad The amount of ancestor tokens to join */ function join(uint256 wad) external nonReentrant payRewards { require(both(canJoin, !protocolUnderwater()), "GebLenderFirstResortRewardsVested/join-not-allowed"); require(wad > 0, "GebLenderFirstResortRewardsVested/null-ancestor-to-join"); uint256 price = joinPrice(wad); require(price > 0, "GebLenderFirstResortRewardsVested/null-join-price"); require(ancestorPool.token().transferFrom(msg.sender, address(ancestorPool), wad), "GebLenderFirstResortRewardsVested/could-not-transfer-ancestor"); descendant.mint(msg.sender, price); descendantBalanceOf[msg.sender] = addition(descendantBalanceOf[msg.sender], price); stakedSupply = addition(stakedSupply, price); emit Join(msg.sender, price, wad); } /* * @notice Request an exit for a specific amount of ancestor tokens * @param wad The amount of tokens to exit */ function requestExit(uint wad) external nonReentrant payRewards { require(wad > 0, "GebLenderFirstResortRewardsVested/null-amount-to-exit"); exitRequests[msg.sender].deadline = addition(now, exitDelay); exitRequests[msg.sender].lockedAmount = addition(exitRequests[msg.sender].lockedAmount, wad); descendantBalanceOf[msg.sender] = subtract(descendantBalanceOf[msg.sender], wad); descendant.burn(msg.sender, wad); emit RequestExit(msg.sender, exitRequests[msg.sender].deadline, wad); } /* * @notify Exit ancestor tokens */ function exit() external nonReentrant { require(both(now >= exitRequests[msg.sender].deadline, exitRequests[msg.sender].lockedAmount > 0), "GebLenderFirstResortRewardsVested/wait-more"); require(either(!protocolUnderwater(), forcedExit), "GebLenderFirstResortRewardsVested/exit-not-allowed"); uint256 price = exitPrice(exitRequests[msg.sender].lockedAmount); stakedSupply = subtract(stakedSupply, exitRequests[msg.sender].lockedAmount); ancestorPool.transfer(msg.sender, price); emit Exit(msg.sender, price, exitRequests[msg.sender].lockedAmount); delete exitRequests[msg.sender]; } }
@notify Create a new auction that sells ancestor tokens in exchange for system coins/
function auctionAncestorTokens() external nonReentrant { require(canAuctionTokens(), "GebLenderFirstResortRewardsVested/cannot-auction-tokens"); ancestorPool.transfer(address(this), tokensToAuction); ancestorPool.token().approve(address(auctionHouse), tokensToAuction); auctionHouse.startAuction(tokensToAuction, systemCoinsToRequest); updatePool(); emit AuctionAncestorTokens(address(auctionHouse), tokensToAuction, systemCoinsToRequest); }
1,791,076
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './SafeMath32.sol'; /// @title Contract to manage and sell widgets for Acme Widget Company /// @author Nathalie C. Chan King Choy contract AcmeWidgetCo { using SafeMath for uint256; using SafeMath32 for uint32; //=========================================== // Struct definitions //=========================================== // The information about a single widget struct WidgetData { uint32 serialNumber; uint8 factoryMadeAt; uint8 siteTestedAt; uint32 testResults; // bit == 1 => that test passed, 0 => test failed // e.g. testResults == 0xFFFFFFFF means all 32 tests passed // e.g. testResults == 0xFFFF0000 means only the first 16 tests passed } // Assumption: Customer will buy >1 widget in an order. // The information for an order of widgets from a particular bin. // Widgets are sold in array index order // e.g. Customer buys 5 widgets. If [1] was the last widget sold in that // bin, then firstIndex is [2], lastIndex is [6] for this order. struct WidgetOrderFill { uint8 bin; // Indices into corresponding bin of widgets uint32 firstIndex; uint32 lastIndex; } //=========================================== // Contract variables //=========================================== // Circuit breaker bool public stopContract; // Lists of users by role mapping (address => uint8) public addr2Role; // Enum may seem appropriate, but you have to document the decoding anyway // because the enum isn't accessible in JavaScript, so skip using enum. // This is how to decode: // Admin = 1 // Tester = 2 // Sales Distributor = 3 // Customer = 4 // Assumption: During the life of this contract Acme won't ever reach >256 sites // Stores names of factories and test sites string[] public factoryList; string[] public testSiteList; uint8 public factoryCount; uint8 public testSiteCount; // Used to ensure we don't add a duplicate factory or test site // Uses the keccak256 hash of the string for the lookup // Store the index into the string array for that name mapping (bytes32 => uint8) public factoryMapping; mapping (bytes32 => uint8) public testSiteMapping; // Track the widgets. Map the serial number to position in widgetList // Assumption: We won't have more than 4 billion widgets // Bin0 is unsellable widgets (i.e. did not have the correct sets of // passing test results. So, not all 0 indices are populated b/c N/A. // Bin1 has most functionality, Bin2 a bit less, Bin3 even less WidgetData[] public widgetList; mapping (uint32 => uint32) public widgetSerialMapping; uint32 public widgetCount; uint32[4] public binMask; // What tests must pass to be in each bin. uint256[4] public binUnitPrice; // in wei uint32[] public bin1Widgets; // Array of indices into widgetList uint32[] public bin2Widgets; uint32[] public bin3Widgets; uint32[4] public binWidgetCount; // HACK: Because using uint instead of int, widget[0] never really gets sold // TODO: Deal with that later if time allows uint32[4] public lastWidgetSoldInBin; // Index of last sold in that bin mapping (address => WidgetOrderFill[]) public customerWidgetMapping; // Who owns each widget in widgetList //=========================================== // Events //=========================================== event NewAdmin(address indexed _newAdminRegistered); event NewTester(address indexed _newTesterRegistered); event NewSalesDistributor(address indexed _newSalesDistributorRegistered); event NewCustomer(address indexed _newCustomerRegistered); event NewFactory(uint8 indexed _factoryCount, string _factory); event NewTestSite(uint8 indexed _testSiteCount, string _testSite); event NewTestedWidget(uint32 indexed _serial, uint8 indexed _factory, uint8 _testSite, uint32 _results, uint32 _widgetCount, uint8 indexed _bin, uint32 _binCount); event NewUnitPrice(uint8 indexed _bin, uint256 _newPrice, address indexed _salesDistributor); event NewBinMask(uint8 indexed _bin, uint32 _newBinMask, address indexed _salesDistributor); event WidgetSale(uint8 indexed _bin, uint32 _quantity, address indexed _customer, uint256 _totalAmtPaid); event FundsWithdrawn(address indexed _withdrawer, uint256 _amt); //=========================================== // Modifiers //=========================================== modifier onlyAdmin { require( (addr2Role[msg.sender] == 1), "Only Admins can run this function." ); _; } modifier onlyTester { require( (addr2Role[msg.sender] == 2), "Only Testers can run this function." ); _; } modifier onlySalesDistributor { require( (addr2Role[msg.sender] == 3), "Only Sales Distributors can run this function." ); _; } modifier onlyCustomer { require( (addr2Role[msg.sender] == 4), "Only Customers can run this function." ); _; } // Circuit breaker modifier stopInEmergency { require(!stopContract, "Emergency: Contract is stopped."); _; } modifier onlyInEmergency { require(stopContract, "Not an emergency. This function is only for emergencies."); _; } //=========================================== // constructor //=========================================== /// @notice Set up initial conditions for the contract, on deployment constructor() public { // Circuit breaker stopContract = false; // The first admin is the deployer of the contract addr2Role[msg.sender] = 1; // These values can only be changed by Sales Distributors binUnitPrice[1] = 0.1 ether; binUnitPrice[2] = 0.05 ether; binUnitPrice[3] = 0.01 ether; binMask[1] = 0xFFFFFFFF; binMask[2] = 0xFFFF0000; binMask[3] = 0xFF000000; } // fallback function (if exists) //=========================================== // public //=========================================== //------------------------- // Admin functions //------------------------- /// @notice Circuit breaker enable - start emergency mode function beginEmergency() public onlyAdmin { stopContract = true; } /// @notice Circuit breaker disable - end emergency mode function endEmergency() public onlyAdmin { stopContract = false; } /// @notice Report contract balance for withdrawal possibility function getContractBalance() constant public onlyAdmin returns (uint) { return address(this).balance; } /// @notice Allow admin to withdraw funds from contract /// @dev TODO Create Finance role for that, if time allows /// @dev Using transfer protects against re-entrancy /// @param _amtToWithdraw How much to withdraw function withdrawFunds(uint256 _amtToWithdraw) public onlyAdmin { require(_amtToWithdraw <= address(this).balance, "Trying to withdraw more than contract balance."); msg.sender.transfer(_amtToWithdraw); emit FundsWithdrawn(msg.sender, _amtToWithdraw); } // Functions to add to user lists /// @notice Admin can add another admin /// @dev Admin has privileges for adding users, sites, or stopping contract /// @param _newAdmin is Ethereum address of the new admin function registerAdmin(address _newAdmin) public onlyAdmin { require(addr2Role[_newAdmin] == 0); addr2Role[_newAdmin] = 1; emit NewAdmin(_newAdmin); } /// @notice Admin can add another tester /// @dev Tester has privileges to record test results for widgets /// @param _newTester is Ethereum address of the new tester function registerTester(address _newTester) public onlyAdmin { require(addr2Role[_newTester] == 0); addr2Role[_newTester] = 2; emit NewTester(_newTester); } /// @notice Admin can add another sales distributor /// @dev Sales dist. has privileges to update bin masks and unit prices /// @param _newSalesDistributor is Ethereum address of the new sales dist. function registerSalesDistributor(address _newSalesDistributor) public onlyAdmin { require(addr2Role[_newSalesDistributor] == 0); addr2Role[_newSalesDistributor] = 3; emit NewSalesDistributor(_newSalesDistributor); } /// @notice Admin can add another customer /// @dev Customer has privileges to buy widgets /// @param _newCustomer is Ethereum address of the new customer function registerCustomer(address _newCustomer) public onlyAdmin { require(addr2Role[_newCustomer] == 0); addr2Role[_newCustomer] = 4; emit NewCustomer(_newCustomer); } /// @notice Admin can add another factory for tester to choose from /// @dev Won't be added if _factory is already in the list /// @param _factory is the name of the new factory. function addFactory(string _factory) public onlyAdmin { require(factoryCount < 255); // Prevent overflow require(factoryMapping[keccak256(abi.encodePacked(_factory))] == 0); factoryList.push(_factory); factoryMapping[keccak256(abi.encodePacked(_factory))] = factoryCount; factoryCount++; emit NewFactory(factoryCount, _factory); } /// @notice Admin can add another test site for tester to choose from /// @dev Won't be added if _testSite is already in the list /// @param _testSite is the name of the new test site. function addTestSite(string _testSite) public onlyAdmin { require(testSiteCount < 255); // Prevent overflow require(testSiteMapping[keccak256(abi.encodePacked(_testSite))] == 0); testSiteList.push(_testSite); testSiteMapping[keccak256(abi.encodePacked(_testSite))] = testSiteCount; testSiteCount++; emit NewTestSite(testSiteCount, _testSite); } //------------------------- // Tester functions //------------------------- /// @notice Tester records the factory where the widget was made, the site /// where it was tested, and the test results for a given widget serial # /// @dev Won't be added if serial # is already in the list /// @dev TODO: Generalize to N bins if time allows /// @dev TODO: Figure out 2-D arrays if time allows /// @param _serial is the serial number for the widget under test /// @param _factory is the factory where the widget was made /// @param _testSite is the site where the widget was tested /// @param _results is the bit mapping of what tests passed or failed /// bit == 1 => that test passed, 0 => test failed /// e.g. testResults == 0xFFFFFFFF means all 32 tests passed /// e.g. testResults == 0xFFFF0000 means only the first 16 tests passed function recordWidgetTests(uint32 _serial, uint8 _factory, uint8 _testSite, uint32 _results) public onlyTester { require(_factory < factoryCount); // Valid factory require(_testSite < testSiteCount); // Valid test site require(widgetSerialMapping[_serial] == 0); // Widget not already recorded uint8 bin; WidgetData memory w; w.serialNumber = _serial; w.factoryMadeAt = _factory; w.siteTestedAt = _testSite; w.testResults = _results; widgetList.push(w); widgetSerialMapping[_serial] = widgetCount; // Save index for serial # if ((_results & binMask[1]) == binMask[1]) { bin1Widgets.push(widgetCount); bin = 1; } else if ((_results & binMask[2]) == binMask[2]) { bin2Widgets.push(widgetCount); bin = 2; } else if ((_results & binMask[3]) == binMask[3]) { bin3Widgets.push(widgetCount); bin = 3; } else { // Widgets that don't match a bin are too low quality to sell bin = 0; } binWidgetCount[bin]++; widgetCount++; emit NewTestedWidget(_serial, _factory, _testSite, _results, widgetCount, bin, binWidgetCount[bin]); } //------------------------- // Sales distributor functions //------------------------- /// @notice Sales distributor can update the unit price of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @param _bin is the bin whose price is getting updated /// @param _newPrice is the new price in wei function updateUnitPrice(uint8 _bin, uint256 _newPrice) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binUnitPrice[_bin] = _newPrice; emit NewUnitPrice(_bin, _newPrice, msg.sender); } /// @notice Sales distributor can update the mask of any of the bins /// @dev TODO: Later generalize to N bins, if time allows /// @dev Mask is how we know what bin a widget belongs in. Widget must have /// a 1 in its test result in all positions where mask is 1 to get into /// that particular bin /// @param _bin is the bin whose mask is getting updated /// @param _newMask is the new mask value (e.g. 0xFFFFFF00) function updateBinMask(uint8 _bin, uint32 _newMask) public onlySalesDistributor { require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); binMask[_bin] = _newMask; emit NewBinMask(_bin, _newMask, msg.sender); } //------------------------- // Customer functions //------------------------- /// @notice Function for customer to buy widgets from a specific bin /// @dev This function is stopped by the circuit breaker /// @dev TODO: Later generalize to N bins, if time allows /// @dev TODO: Currently doesn't refund any excess if customer overpaid /// @dev TODO: Currently only way to withdraw funds is when killing the contract. /// @param _bin is the bin from which the customer wants to buy widgets /// @param _quantity is the number of widgets to buy function buyWidgets(uint8 _bin, uint32 _quantity) payable public onlyCustomer stopInEmergency { require(_quantity > 0, "Must purchase >0 widgets."); require((_bin > 0) && (_bin <=3), "Bin must be between 1 to 3, inclusive"); uint32 wCount = binWidgetCount[_bin]; uint32 lastSold = lastWidgetSoldInBin[_bin]; uint256 uPrice = binUnitPrice[_bin]; uint32 stock = wCount.sub(lastSold).sub(1); require((_quantity <= stock), "Insufficient stock. NOTE: widget[0] in each bin is not for sale."); require((uint256(_quantity).mul(uPrice) <= msg.value), "Insufficient funds."); WidgetOrderFill memory w; w.bin = _bin; w.firstIndex = lastSold.add(1); w.lastIndex = lastSold.add(_quantity); customerWidgetMapping[msg.sender].push(w); lastWidgetSoldInBin[_bin] = w.lastIndex; emit WidgetSale(_bin, _quantity, msg.sender, msg.value); } }
Admin can add another factory for tester to choose from Won't be added if _factory is already in the list _factory is the name of the new factory.
function addFactory(string _factory) public onlyAdmin { require(factoryMapping[keccak256(abi.encodePacked(_factory))] == 0); factoryList.push(_factory); factoryMapping[keccak256(abi.encodePacked(_factory))] = factoryCount; factoryCount++; emit NewFactory(factoryCount, _factory); }
12,642,330
./partial_match/97/0xA9f312460D5d6c72dE4013187AF0F3DBcf01dfD0/sources/SOTAMarket.sol
buyer pay itemPrice + marketFee seller receive itemPrice - itemPrice firstSellFee / 100 referral of seller receive itemPrice firstSellFee / 100 (referralFee / 100) referral of buyer receive itemPrice marketFee / 100 (referralFee / 100)/ buyer pay itemPrice + marketFee seller receive itemPrice - itemPrice firstSellFee / 100 referral of seller receive itemPrice firstSellFee / 100 (referralFee / 100) referral of buyer receive itemPrice marketFee / 100 (referralFee / 100)/ buyer pay itemPrice + marketFee seller receive itemPrice - itemPrice marketFee / 100 - revenue lastSalePrice[tokenAddress][tokenId] item.loyalty referral of seller receive itemPrice marketFee / 100 (referralFee / 100) referral of buyer receive itemPrice marketFee / 100 (referralFee / 100) creator receive revenue lastSalePrice[tokenAddress][tokenId] loyalty/
function executeOrder(address _buyer, uint256 _itemId, uint256 _quantity, address _paymentToken, uint256 _paymentAmount) private returns(bool) { Item storage item = items[_itemId]; address payable creator = payable(IERC1155(item.tokenAddress).getCreator(item.tokenId)); uint256 loyalty = IERC1155(item.tokenAddress).getLoyaltyFee(item.tokenId); uint256 itemPrice = item.price; ref.buyerRef = getReferralAddress(_buyer); ref.sellerRef = getReferralAddress(item.owner); if (msg.value == 0) { if (item.tokenAddress == farmingContract) { fee.itemFee = itemPrice.mul(marketFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(creator, itemPrice.mul(artistLoyaltyFee).div(ZOOM_FEE)); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - artistLoyaltyFee).div(ZOOM_FEE)); IERC20(_paymentToken).transfer(ref.buyerRef, fee.itemFee.mul(referralFee).div(ZOOM_FEE)); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(firstSellFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - firstSellFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } if (item.tokenAddress == farmingContract) { fee.itemFee = itemPrice.mul(marketFee).div(ZOOM_FEE); creator.transfer(itemPrice.mul(artistLoyaltyFee).div(ZOOM_FEE)); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - artistLoyaltyFee).div(ZOOM_FEE)); ref.buyerRef.transfer(fee.itemFee.mul(referralFee).div(ZOOM_FEE)); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(firstSellFee).div(ZOOM_FEE); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - firstSellFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } } if (lastSalePrice[item.tokenAddress][item.tokenId] < itemPrice) { uint256 revenue = (itemPrice - lastSalePrice[item.tokenAddress][item.tokenId]).mul(ZOOM_FEE).div(itemPrice); if (msg.value > 0) { fee.loyaltyFee = revenue.mul(msg.value).mul(loyalty).div(ZOOM_FEE).div(ZOOM_FEE); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE).sub(fee.loyaltyFee)); creator.transfer(fee.loyaltyFee); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } fee.loyaltyFee = revenue.mul(_paymentAmount).mul(loyalty).div(ZOOM_FEE).div(ZOOM_FEE); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE).sub(fee.loyaltyFee)); IERC20(_paymentToken).transfer(creator, fee.loyaltyFee); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); if (msg.value == 0) { ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } } } IERC1155(item.tokenAddress).safeTransferFrom(address(this), _buyer, item.tokenId, _quantity, abi.encodePacked(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))); item.quantity = item.quantity.sub(_quantity);
11,435,681
/** *Submitted for verification at Etherscan.io on 2020-09-06 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.11; // /** * @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 Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (block.number != 0) { // Equivalent to contains(set, value) //injected CONTRACT AFFECTED BY MINERS // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // interface IERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // /** * XFI token extends the interface of ERC20 standard. */ interface IXFIToken is IERC20 { event VestingStartChanged(uint256 newVestingStart, uint256 newVestingEnd, uint256 newReserveFrozenUntil); event TransfersStarted(); event TransfersStopped(); event MigrationsAllowed(); event ReserveWithdrawal(address indexed to, uint256 amount); event VestingBalanceMigrated(address indexed from, bytes32 to, uint256 vestingDaysLeft, uint256 vestingBalance); function isTransferringStopped() external view returns (bool); function isMigratingAllowed() external view returns (bool); function VESTING_DURATION() external view returns (uint256); function VESTING_DURATION_DAYS() external view returns (uint256); function RESERVE_FREEZE_DURATION() external view returns (uint256); function RESERVE_FREEZE_DURATION_DAYS() external view returns (uint256); function MAX_VESTING_TOTAL_SUPPLY() external view returns (uint256); function vestingStart() external view returns (uint256); function vestingEnd() external view returns (uint256); function reserveFrozenUntil() external view returns (uint256); function reserveAmount() external view returns (uint256); function vestingDaysSinceStart() external view returns (uint256); function vestingDaysLeft() external view returns (uint256); function convertAmountUsingRatio(uint256 amount) external view returns (uint256); function convertAmountUsingReverseRatio(uint256 amount) external view returns (uint256); function totalVestedBalanceOf(address account) external view returns (uint256); function unspentVestedBalanceOf(address account) external view returns (uint256); function spentVestedBalanceOf(address account) external view returns (uint256); function mint(address account, uint256 amount) external returns (bool); function mintWithoutVesting(address account, uint256 amount) external returns (bool); function burn(uint256 amount) external returns (bool); function burnFrom(address account, uint256 amount) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function startTransfers() external returns (bool); function stopTransfers() external returns (bool); function allowMigrations() external returns (bool); function changeVestingStart(uint256 newVestingStart) external returns (bool); function withdrawReserve(address to) external returns (bool); function migrateVestingBalance(bytes32 to) external returns (bool); } // /** * Implementation of the {IXFIToken} interface. * * 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. */ contract XFIToken is AccessControl, ReentrancyGuard, IXFIToken { using SafeMath for uint256; using Address for address; string private constant _name = 'dfinance'; string private constant _symbol = 'XFI'; uint8 private constant _decimals = 18; bytes32 public constant MINTER_ROLE = keccak256('minter'); uint256 public constant override MAX_VESTING_TOTAL_SUPPLY = 1e26; // 100 million XFI. uint256 public constant override VESTING_DURATION_DAYS = 182; uint256 public constant override VESTING_DURATION = 182 days; /** * @dev Reserve is the final amount of tokens that weren't distributed * during the vesting. */ uint256 public constant override RESERVE_FREEZE_DURATION_DAYS = 730; // Around 2 years. uint256 public constant override RESERVE_FREEZE_DURATION = 730 days; mapping (address => uint256) private _vestingBalances; mapping (address => uint256) private _balances; mapping (address => uint256) private _spentVestedBalances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _vestingTotalSupply; uint256 private _totalSupply; uint256 private _spentVestedTotalSupply; uint256 private _vestingStart; uint256 private _vestingEnd; uint256 private _reserveFrozenUntil; bool private _stopped = false; bool private _migratingAllowed = false; uint256 private _reserveAmount; /** * Sets {DEFAULT_ADMIN_ROLE} (alias `owner`) role for caller. * Assigns vesting and freeze period dates. */ constructor (uint256 vestingStart_) public { require(vestingStart_ > block.timestamp, 'XFIToken: vesting start must be greater than current timestamp'); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _vestingStart = vestingStart_; _vestingEnd = vestingStart_.add(VESTING_DURATION); _reserveFrozenUntil = vestingStart_.add(RESERVE_FREEZE_DURATION); _reserveAmount = MAX_VESTING_TOTAL_SUPPLY; } /** * Transfers `amount` tokens to `recipient`. * * Emits a {Transfer} event. * * Requirements: * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * Approves `spender` to spend `amount` of caller's tokens. * * 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. * * Requirements: * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * Transfers `amount` tokens from `sender` to `recipient`. * * Emits a {Transfer} event. * Emits an {Approval} event indicating the updated allowance. * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, 'XFIToken: transfer amount exceeds allowance')); return true; } /** * 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 {approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * 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 {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 override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, 'XFIToken: decreased allowance below zero')); return true; } /** * Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * - Caller must have minter role. * - `account` cannot be the zero address. */ function mint(address account, uint256 amount) external override returns (bool) { require(hasRole(MINTER_ROLE, msg.sender), 'XFIToken: sender is not minter'); _mint(account, amount); return true; } /** * Creates `amount` tokens and assigns them to `account`, increasing * the total supply without vesting. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * - Caller must have minter role. * - `account` cannot be the zero address. */ function mintWithoutVesting(address account, uint256 amount) external override returns (bool) { require(hasRole(MINTER_ROLE, msg.sender), 'XFIToken: sender is not minter'); _mintWithoutVesting(account, amount); return true; } /** * Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * - Caller must have minter role. */ function burnFrom(address account, uint256 amount) external override returns (bool) { require(hasRole(MINTER_ROLE, msg.sender), 'XFIToken: sender is not minter'); _burn(account, amount); return true; } /** * Destroys `amount` tokens from sender, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. */ function burn(uint256 amount) external override returns (bool) { _burn(msg.sender, amount); return true; } /** * Change vesting start and end timestamps. * * Emits a {VestingStartChanged} event. * * Requirements: * - Caller must have owner role. * - Vesting must be pending. * - `vestingStart_` must be greater than the current timestamp. */ function changeVestingStart(uint256 vestingStart_) external override returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), 'XFIToken: sender is not owner'); require(_vestingStart > block.timestamp, 'XFIToken: vesting has started'); require(vestingStart_ > block.timestamp, 'XFIToken: vesting start must be greater than current timestamp'); _vestingStart = vestingStart_; _vestingEnd = vestingStart_.add(VESTING_DURATION); _reserveFrozenUntil = vestingStart_.add(RESERVE_FREEZE_DURATION); emit VestingStartChanged(vestingStart_, _vestingEnd, _reserveFrozenUntil); return true; } /** * Starts all transfers. * * Emits a {TransfersStarted} event. * * Requirements: * - Caller must have owner role. * - Transferring is stopped. */ function startTransfers() external override returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XFIToken: sender is not owner'); require(_stopped, 'XFIToken: transferring is not stopped'); _stopped = false; emit TransfersStarted(); return true; } /** * Stops all transfers. * * Emits a {TransfersStopped} event. * * Requirements: * - Caller must have owner role. * - Transferring isn't stopped. */ function stopTransfers() external override returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XFIToken: sender is not owner'); require(!_stopped, 'XFIToken: transferring is stopped'); _stopped = true; emit TransfersStopped(); return true; } /** * Start migrations. * * Emits a {MigrationsStarted} event. * * Requirements: * - Caller must have owner role. * - Migrating isn't allowed. */ function allowMigrations() external override returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XFIToken: sender is not owner'); require(!_migratingAllowed, 'XFIToken: migrating is allowed'); _migratingAllowed = true; emit MigrationsAllowed(); return true; } /** * Withdraws reserve amount to a destination specified as `to`. * * Emits a {ReserveWithdrawal} event. * * Requirements: * - `to` cannot be the zero address. * - Caller must have owner role. * - Reserve has unfrozen. */ function withdrawReserve(address to) external override nonReentrant returns (bool) { require(to != address(0), 'XFIToken: withdraw to the zero address'); require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'XFIToken: sender is not owner'); require(block.timestamp > _reserveFrozenUntil, 'XFIToken: reserve is frozen'); uint256 amount = reserveAmount(); _mintWithoutVesting(to, amount); _reserveAmount = 0; emit ReserveWithdrawal(to, amount); return true; } /** * Migrate vesting balance to the Dfinance blockchain. * * Emits a {VestingBalanceMigrated} event. * * Requirements: * - `to` is not the zero bytes. * - Vesting balance is greater than zero. * - Vesting hasn't ended. */ function migrateVestingBalance(bytes32 to) external override nonReentrant returns (bool) { require(to != bytes32(0), 'XFIToken: migrate to the zero bytes'); require(_migratingAllowed, 'XFIToken: migrating is disallowed'); require(block.timestamp < _vestingEnd, 'XFIToken: vesting has ended'); uint256 vestingBalance = _vestingBalances[msg.sender]; require(vestingBalance > 0, 'XFIToken: vesting balance is zero'); uint256 spentVestedBalance = spentVestedBalanceOf(msg.sender); uint256 unspentVestedBalance = unspentVestedBalanceOf(msg.sender); // Subtract the vesting balance from total supply. _vestingTotalSupply = _vestingTotalSupply.sub(vestingBalance); // Add the unspent vesting balance to total supply. _totalSupply = _totalSupply.add(unspentVestedBalance); // Subtract the spent vested balance from total supply. _spentVestedTotalSupply = _spentVestedTotalSupply.sub(spentVestedBalance); // Make unspent vested balance persistent. _balances[msg.sender] = _balances[msg.sender].add(unspentVestedBalance); // Reset the account's vesting. _vestingBalances[msg.sender] = 0; _spentVestedBalances[msg.sender] = 0; emit VestingBalanceMigrated(msg.sender, to, vestingDaysLeft(), vestingBalance); return true; } /** * Returns name of the token. */ function name() external view override returns (string memory) { return _name; } /** * Returns symbol of the token. */ function symbol() external view override returns (string memory) { return _symbol; } /** * Returns number of decimals of the token. */ function decimals() external view override returns (uint8) { return _decimals; } /** * Returnes amount of `owner`'s tokens that `spender` is allowed to transfer. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * Returns the vesting start. */ function vestingStart() external view override returns (uint256) { return _vestingStart; } /** * Returns the vesting end. */ function vestingEnd() external view override returns (uint256) { return _vestingEnd; } /** * Returns the date when freeze of the reserve XFI amount. */ function reserveFrozenUntil() external view override returns (uint256) { return _reserveFrozenUntil; } /** * Returns whether transfering is stopped. */ function isTransferringStopped() external view override returns (bool) { return _stopped; } /** * Returns whether migrating is allowed. */ function isMigratingAllowed() external view override returns (bool) { return _migratingAllowed; } /** * Convert input amount to the output amount using the vesting ratio * (days since vesting start / vesting duration). */ function convertAmountUsingRatio(uint256 amount) public view override returns (uint256) { uint256 convertedAmount = amount .mul(vestingDaysSinceStart()) .div(VESTING_DURATION_DAYS); return (convertedAmount < amount) ? convertedAmount : amount; } /** * Convert input amount to the output amount using the vesting reverse * ratio (days until vesting end / vesting duration). */ function convertAmountUsingReverseRatio(uint256 amount) public view override returns (uint256) { if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS return amount .mul(vestingDaysLeft().add(1)) .div(VESTING_DURATION_DAYS); } else { return amount; } } /** * Returns days since the vesting start. */ function vestingDaysSinceStart() public view override returns (uint256) { if (block.number > _vestingStart) { //injected CONTRACT AFFECTED BY MINERS return block.timestamp .sub(_vestingStart) .div(1 days) .add(1); } else { return 0; } } /** * Returns vesting days left. */ function vestingDaysLeft() public view override returns (uint256) { if (block.number < _vestingEnd) { //injected CONTRACT AFFECTED BY MINERS return VESTING_DURATION_DAYS .sub(vestingDaysSinceStart()); } else { return 0; } } /** * Returns total supply of the token. */ function totalSupply() public view override returns (uint256) { return convertAmountUsingRatio(_vestingTotalSupply) .add(_totalSupply) .sub(_spentVestedTotalSupply); } /** * Returns total vested balance of the `account`. */ function totalVestedBalanceOf(address account) public view override returns (uint256) { return convertAmountUsingRatio(_vestingBalances[account]); } /** * Returns unspent vested balance of the `account`. */ function unspentVestedBalanceOf(address account) public view override returns (uint256) { return totalVestedBalanceOf(account) .sub(_spentVestedBalances[account]); } /** * Returns spent vested balance of the `account`. */ function spentVestedBalanceOf(address account) public view override returns (uint256) { return _spentVestedBalances[account]; } /** * Returns token balance of the `account`. */ function balanceOf(address account) public view override returns (uint256) { return unspentVestedBalanceOf(account) .add(_balances[account]); } /** * Returns reserve amount. */ function reserveAmount() public view override returns (uint256) { return _reserveAmount; } /** * Moves tokens `amount` from `sender` to `recipient`. * * 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`. * - Transferring is not stopped. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'XFIToken: transfer from the zero address'); require(recipient != address(0), 'XFIToken: transfer to the zero address'); require(!_stopped, 'XFIToken: transferring is stopped'); _decreaseAccountBalance(sender, amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * 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. * - Transferring is not stopped. * - `amount` doesn't exceed reserve amount. */ function _mint(address account, uint256 amount) internal { require(account != address(0), 'XFIToken: mint to the zero address'); require(!_stopped, 'XFIToken: transferring is stopped'); require(_reserveAmount >= amount, 'XFIToken: mint amount exceeds reserve amount'); _vestingTotalSupply = _vestingTotalSupply.add(amount); _vestingBalances[account] = _vestingBalances[account].add(amount); _reserveAmount = _reserveAmount.sub(amount); emit Transfer(address(0), account, amount); } /** * Creates `amount` tokens and assigns them to `account`, increasing * the total supply without vesting. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * - `account` cannot be the zero address. * - Transferring is not stopped. */ function _mintWithoutVesting(address account, uint256 amount) internal { require(account != address(0), 'XFIToken: mint to the zero address'); require(!_stopped, 'XFIToken: transferring is stopped'); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * 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. * - Transferring is not stopped. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), 'XFIToken: burn from the zero address'); require(!_stopped, 'XFIToken: transferring is stopped'); require(balanceOf(account) >= amount, 'XFIToken: burn amount exceeds balance'); _decreaseAccountBalance(account, amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * 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), 'XFIToken: approve from the zero address'); require(spender != address(0), 'XFIToken: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * Decrease balance of the `account`. * * The use of vested balance is in priority. Otherwise, the normal balance * will be used. */ function _decreaseAccountBalance(address account, uint256 amount) internal { uint256 accountBalance = balanceOf(account); require(accountBalance >= amount, 'XFIToken: transfer amount exceeds balance'); uint256 accountVestedBalance = unspentVestedBalanceOf(account); uint256 usedVestedBalance = 0; uint256 usedBalance = 0; if (block.timestamp >= amount) { //injected CONTRACT AFFECTED BY MINERS usedVestedBalance = amount; } else { usedVestedBalance = accountVestedBalance; usedBalance = amount.sub(usedVestedBalance); } _balances[account] = _balances[account].sub(usedBalance); _spentVestedBalances[account] = _spentVestedBalances[account].add(usedVestedBalance); _totalSupply = _totalSupply.add(usedVestedBalance); _spentVestedTotalSupply = _spentVestedTotalSupply.add(usedVestedBalance); } }
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 {approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function increaseAllowance(address spender, uint256 addedValue) external override returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
1,019,377
pragma solidity ^0.4.20; // File: attrstore/AttributeStore.sol pragma solidity^0.4.11; library AttributeStore { struct Data { mapping(bytes32 => uint) store; } function getAttribute(Data storage self, bytes32 _UUID, string _attrName) public view returns (uint) { bytes32 key = keccak256(_UUID, _attrName); return self.store[key]; } function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal) public { bytes32 key = keccak256(_UUID, _attrName); self.store[key] = _attrVal; } } // File: dll/DLL.sol pragma solidity^0.4.11; library DLL { uint constant NULL_NODE_ID = 0; struct Node { uint next; uint prev; } struct Data { mapping(uint => Node) dll; } function isEmpty(Data storage self) public view returns (bool) { return getStart(self) == NULL_NODE_ID; } function contains(Data storage self, uint _curr) public view returns (bool) { if (isEmpty(self) || _curr == NULL_NODE_ID) { return false; } bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr); bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID); return isSingleNode || !isNullNode; } function getNext(Data storage self, uint _curr) public view returns (uint) { return self.dll[_curr].next; } function getPrev(Data storage self, uint _curr) public view returns (uint) { return self.dll[_curr].prev; } function getStart(Data storage self) public view returns (uint) { return getNext(self, NULL_NODE_ID); } function getEnd(Data storage self) public view returns (uint) { return getPrev(self, NULL_NODE_ID); } /** @dev Inserts a new node between _prev and _next. When inserting a node already existing in the list it will be automatically removed from the old position. @param _prev the node which _new will be inserted after @param _curr the id of the new node being inserted @param _next the node which _new will be inserted before */ function insert(Data storage self, uint _prev, uint _curr, uint _next) public { require(_curr != NULL_NODE_ID); remove(self, _curr); require(_prev == NULL_NODE_ID || contains(self, _prev)); require(_next == NULL_NODE_ID || contains(self, _next)); require(getNext(self, _prev) == _next); require(getPrev(self, _next) == _prev); self.dll[_curr].prev = _prev; self.dll[_curr].next = _next; self.dll[_prev].next = _curr; self.dll[_next].prev = _curr; } function remove(Data storage self, uint _curr) public { if (!contains(self, _curr)) { return; } uint next = getNext(self, _curr); uint prev = getPrev(self, _curr); self.dll[next].prev = prev; self.dll[prev].next = next; delete self.dll[_curr]; } } // File: tokens/eip20/EIP20Interface.sol // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.8; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // File: zeppelin/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: plcr-revival/PLCRVoting.sol /** @title Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens @author Team: Aspyn Palatnick, Cem Ozer, Yorke Rhodes */ contract PLCRVoting { // ============ // EVENTS: // ============ event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter); event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter); event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator); event _VotingRightsGranted(uint numTokens, address indexed voter); event _VotingRightsWithdrawn(uint numTokens, address indexed voter); event _TokensRescued(uint indexed pollID, address indexed voter); // ============ // DATA STRUCTURES: // ============ using AttributeStore for AttributeStore.Data; using DLL for DLL.Data; using SafeMath for uint; struct Poll { uint commitEndDate; /// expiration date of commit period for poll uint revealEndDate; /// expiration date of reveal period for poll uint voteQuorum; /// number of votes required for a proposal to pass uint votesFor; /// tally of votes supporting proposal uint votesAgainst; /// tally of votes countering proposal mapping(address => bool) didCommit; /// indicates whether an address committed a vote for this poll mapping(address => bool) didReveal; /// indicates whether an address revealed a vote for this poll } // ============ // STATE VARIABLES: // ============ uint constant public INITIAL_POLL_NONCE = 0; uint public pollNonce; mapping(uint => Poll) public pollMap; // maps pollID to Poll struct mapping(address => uint) public voteTokenBalance; // maps user's address to voteToken balance mapping(address => DLL.Data) dllMap; AttributeStore.Data store; EIP20Interface public token; /** @dev Initializer. Can only be called once. @param _token The address where the ERC20 token contract is deployed */ function init(address _token) public { require(_token != 0 && address(token) == 0); token = EIP20Interface(_token); pollNonce = INITIAL_POLL_NONCE; } // ================ // TOKEN INTERFACE: // ================ /** @notice Loads _numTokens ERC20 tokens into the voting contract for one-to-one voting rights @dev Assumes that msg.sender has approved voting contract to spend on their behalf @param _numTokens The number of votingTokens desired in exchange for ERC20 tokens */ function requestVotingRights(uint _numTokens) public { require(token.balanceOf(msg.sender) >= _numTokens); voteTokenBalance[msg.sender] += _numTokens; require(token.transferFrom(msg.sender, this, _numTokens)); emit _VotingRightsGranted(_numTokens, msg.sender); } /** @notice Withdraw _numTokens ERC20 tokens from the voting contract, revoking these voting rights @param _numTokens The number of ERC20 tokens desired in exchange for voting rights */ function withdrawVotingRights(uint _numTokens) external { uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender)); require(availableTokens >= _numTokens); voteTokenBalance[msg.sender] -= _numTokens; require(token.transfer(msg.sender, _numTokens)); emit _VotingRightsWithdrawn(_numTokens, msg.sender); } /** @dev Unlocks tokens locked in unrevealed vote where poll has ended @param _pollID Integer identifier associated with the target poll */ function rescueTokens(uint _pollID) public { require(isExpired(pollMap[_pollID].revealEndDate)); require(dllMap[msg.sender].contains(_pollID)); dllMap[msg.sender].remove(_pollID); emit _TokensRescued(_pollID, msg.sender); } /** @dev Unlocks tokens locked in unrevealed votes where polls have ended @param _pollIDs Array of integer identifiers associated with the target polls */ function rescueTokensInMultiplePolls(uint[] _pollIDs) public { // loop through arrays, rescuing tokens from all for (uint i = 0; i < _pollIDs.length; i++) { rescueTokens(_pollIDs[i]); } } // ================= // VOTING INTERFACE: // ================= /** @notice Commits vote using hash of choice and secret salt to conceal vote until reveal @param _pollID Integer identifier associated with target poll @param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order) @param _numTokens The number of tokens to be committed towards the target poll @param _prevPollID The ID of the poll that the user has voted the maximum number of tokens in which is still less than or equal to numTokens */ function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public { require(commitPeriodActive(_pollID)); // if msg.sender doesn't have enough voting rights, // request for enough voting rights if (voteTokenBalance[msg.sender] < _numTokens) { uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]); requestVotingRights(remainder); } // make sure msg.sender has enough voting rights require(voteTokenBalance[msg.sender] >= _numTokens); // prevent user from committing to zero node placeholder require(_pollID != 0); // prevent user from committing a secretHash of 0 require(_secretHash != 0); // Check if _prevPollID exists in the user's DLL or if _prevPollID is 0 require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID)); uint nextPollID = dllMap[msg.sender].getNext(_prevPollID); // edge case: in-place update if (nextPollID == _pollID) { nextPollID = dllMap[msg.sender].getNext(_pollID); } require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens)); dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID); bytes32 UUID = attrUUID(msg.sender, _pollID); store.setAttribute(UUID, "numTokens", _numTokens); store.setAttribute(UUID, "commitHash", uint(_secretHash)); pollMap[_pollID].didCommit[msg.sender] = true; emit _VoteCommitted(_pollID, _numTokens, msg.sender); } /** @notice Commits votes using hashes of choices and secret salts to conceal votes until reveal @param _pollIDs Array of integer identifiers associated with target polls @param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order) @param _numsTokens Array of numbers of tokens to be committed towards the target polls @param _prevPollIDs Array of IDs of the polls that the user has voted the maximum number of tokens in which is still less than or equal to numTokens */ function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external { // make sure the array lengths are all the same require(_pollIDs.length == _secretHashes.length); require(_pollIDs.length == _numsTokens.length); require(_pollIDs.length == _prevPollIDs.length); // loop through arrays, committing each individual vote values for (uint i = 0; i < _pollIDs.length; i++) { commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]); } } /** @dev Compares previous and next poll's committed tokens for sorting purposes @param _prevID Integer identifier associated with previous poll in sorted order @param _nextID Integer identifier associated with next poll in sorted order @param _voter Address of user to check DLL position for @param _numTokens The number of tokens to be committed towards the poll (used for sorting) @return valid Boolean indication of if the specified position maintains the sort */ function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) { bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID)); // if next is zero node, _numTokens does not need to be greater bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0); return prevValid && nextValid; } /** @notice Reveals vote with choice and secret salt used in generating commitHash to attribute committed tokens @param _pollID Integer identifier associated with target poll @param _voteOption Vote choice used to generate commitHash for associated poll @param _salt Secret number used to generate commitHash for associated poll */ function revealVote(uint _pollID, uint _voteOption, uint _salt) public { // Make sure the reveal period is active require(revealPeriodActive(_pollID)); require(pollMap[_pollID].didCommit[msg.sender]); // make sure user has committed a vote for this poll require(!pollMap[_pollID].didReveal[msg.sender]); // prevent user from revealing multiple times require(keccak256(_voteOption, _salt) == getCommitHash(msg.sender, _pollID)); // compare resultant hash from inputs to original commitHash uint numTokens = getNumTokens(msg.sender, _pollID); if (_voteOption == 1) {// apply numTokens to appropriate poll choice pollMap[_pollID].votesFor += numTokens; } else { pollMap[_pollID].votesAgainst += numTokens; } dllMap[msg.sender].remove(_pollID); // remove the node referring to this vote upon reveal pollMap[_pollID].didReveal[msg.sender] = true; emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender); } /** @notice Reveals multiple votes with choices and secret salts used in generating commitHashes to attribute committed tokens @param _pollIDs Array of integer identifiers associated with target polls @param _voteOptions Array of vote choices used to generate commitHashes for associated polls @param _salts Array of secret numbers used to generate commitHashes for associated polls */ function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external { // make sure the array lengths are all the same require(_pollIDs.length == _voteOptions.length); require(_pollIDs.length == _salts.length); // loop through arrays, revealing each individual vote values for (uint i = 0; i < _pollIDs.length; i++) { revealVote(_pollIDs[i], _voteOptions[i], _salts[i]); } } /** @param _pollID Integer identifier associated with target poll @param _salt Arbitrarily chosen integer used to generate secretHash @return correctVotes Number of tokens voted for winning option */ function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) { require(pollEnded(_pollID)); require(pollMap[_pollID].didReveal[_voter]); uint winningChoice = isPassed(_pollID) ? 1 : 0; bytes32 winnerHash = keccak256(winningChoice, _salt); bytes32 commitHash = getCommitHash(_voter, _pollID); require(winnerHash == commitHash); return getNumTokens(_voter, _pollID); } // ================== // POLLING INTERFACE: // ================== /** @dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event @param _voteQuorum Type of majority (out of 100) that is necessary for poll to be successful @param _commitDuration Length of desired commit period in seconds @param _revealDuration Length of desired reveal period in seconds */ function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) { pollNonce = pollNonce + 1; uint commitEndDate = block.timestamp.add(_commitDuration); uint revealEndDate = commitEndDate.add(_revealDuration); pollMap[pollNonce] = Poll({ voteQuorum: _voteQuorum, commitEndDate: commitEndDate, revealEndDate: revealEndDate, votesFor: 0, votesAgainst: 0 }); emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender); return pollNonce; } /** @notice Determines if proposal has passed @dev Check if votesFor out of totalVotes exceeds votesQuorum (requires pollEnded) @param _pollID Integer identifier associated with target poll */ function isPassed(uint _pollID) constant public returns (bool passed) { require(pollEnded(_pollID)); Poll memory poll = pollMap[_pollID]; return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst)); } // ---------------- // POLLING HELPERS: // ---------------- /** @dev Gets the total winning votes for reward distribution purposes @param _pollID Integer identifier associated with target poll @return Total number of votes committed to the winning option for specified poll */ function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) { require(pollEnded(_pollID)); if (isPassed(_pollID)) return pollMap[_pollID].votesFor; else return pollMap[_pollID].votesAgainst; } /** @notice Determines if poll is over @dev Checks isExpired for specified poll's revealEndDate @return Boolean indication of whether polling period is over */ function pollEnded(uint _pollID) constant public returns (bool ended) { require(pollExists(_pollID)); return isExpired(pollMap[_pollID].revealEndDate); } /** @notice Checks if the commit period is still active for the specified poll @dev Checks isExpired for the specified poll's commitEndDate @param _pollID Integer identifier associated with target poll @return Boolean indication of isCommitPeriodActive for target poll */ function commitPeriodActive(uint _pollID) constant public returns (bool active) { require(pollExists(_pollID)); return !isExpired(pollMap[_pollID].commitEndDate); } /** @notice Checks if the reveal period is still active for the specified poll @dev Checks isExpired for the specified poll's revealEndDate @param _pollID Integer identifier associated with target poll */ function revealPeriodActive(uint _pollID) constant public returns (bool active) { require(pollExists(_pollID)); return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID); } /** @dev Checks if user has committed for specified poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Boolean indication of whether user has committed */ function didCommit(address _voter, uint _pollID) constant public returns (bool committed) { require(pollExists(_pollID)); return pollMap[_pollID].didCommit[_voter]; } /** @dev Checks if user has revealed for specified poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Boolean indication of whether user has revealed */ function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) { require(pollExists(_pollID)); return pollMap[_pollID].didReveal[_voter]; } /** @dev Checks if a poll exists @param _pollID The pollID whose existance is to be evaluated. @return Boolean Indicates whether a poll exists for the provided pollID */ function pollExists(uint _pollID) constant public returns (bool exists) { return (_pollID != 0 && _pollID <= pollNonce); } // --------------------------- // DOUBLE-LINKED-LIST HELPERS: // --------------------------- /** @dev Gets the bytes32 commitHash property of target poll @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Bytes32 hash property attached to target poll */ function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) { return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash")); } /** @dev Wrapper for getAttribute with attrName="numTokens" @param _voter Address of user to check against @param _pollID Integer identifier associated with target poll @return Number of tokens committed to poll in sorted poll-linked-list */ function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) { return store.getAttribute(attrUUID(_voter, _pollID), "numTokens"); } /** @dev Gets top element of sorted poll-linked-list @param _voter Address of user to check against @return Integer identifier to poll with maximum number of tokens committed to it */ function getLastNode(address _voter) constant public returns (uint pollID) { return dllMap[_voter].getPrev(0); } /** @dev Gets the numTokens property of getLastNode @param _voter Address of user to check against @return Maximum number of tokens committed in poll specified */ function getLockedTokens(address _voter) constant public returns (uint numTokens) { return getNumTokens(_voter, getLastNode(_voter)); } /* @dev Takes the last node in the user's DLL and iterates backwards through the list searching for a node with a value less than or equal to the provided _numTokens value. When such a node is found, if the provided _pollID matches the found nodeID, this operation is an in-place update. In that case, return the previous node of the node being updated. Otherwise return the first node that was found with a value less than or equal to the provided _numTokens. @param _voter The voter whose DLL will be searched @param _numTokens The value for the numTokens attribute in the node to be inserted @return the node which the propoded node should be inserted after */ function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID) constant public returns (uint prevNode) { // Get the last node in the list and the number of tokens in that node uint nodeID = getLastNode(_voter); uint tokensInNode = getNumTokens(_voter, nodeID); // Iterate backwards through the list until reaching the root node while(nodeID != 0) { // Get the number of tokens in the current node tokensInNode = getNumTokens(_voter, nodeID); if(tokensInNode <= _numTokens) { // We found the insert point! if(nodeID == _pollID) { // This is an in-place update. Return the prev node of the node being updated nodeID = dllMap[_voter].getPrev(nodeID); } // Return the insert point return nodeID; } // We did not find the insert point. Continue iterating backwards through the list nodeID = dllMap[_voter].getPrev(nodeID); } // The list is empty, or a smaller value than anything else in the list is being inserted return nodeID; } // ---------------- // GENERAL HELPERS: // ---------------- /** @dev Checks if an expiration date has been reached @param _terminationDate Integer timestamp of date to compare current timestamp with @return expired Boolean indication of whether the terminationDate has passed */ function isExpired(uint _terminationDate) constant public returns (bool expired) { return (block.timestamp > _terminationDate); } /** @dev Generates an identifier which associates a user and a poll together @param _pollID Integer identifier associated with target poll @return UUID Hash which is deterministic from _user and _pollID */ function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) { return keccak256(_user, _pollID); } } // File: contracts/Parameterizer.sol pragma solidity^0.4.11; contract Parameterizer { // ------ // EVENTS // ------ event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate, address indexed proposer); event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate, address indexed challenger); event _ProposalAccepted(bytes32 indexed propID, string name, uint value); event _ProposalExpired(bytes32 indexed propID); event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens); event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens); event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter); // ------ // DATA STRUCTURES // ------ using SafeMath for uint; struct ParamProposal { uint appExpiry; uint challengeID; uint deposit; string name; address owner; uint processBy; uint value; } struct Challenge { uint rewardPool; // (remaining) pool of tokens distributed amongst winning voters address challenger; // owner of Challenge bool resolved; // indication of if challenge is resolved uint stake; // number of tokens at risk for either party during challenge uint winningTokens; // (remaining) amount of tokens used for voting by the winning side mapping(address => bool) tokenClaims; } // ------ // STATE // ------ mapping(bytes32 => uint) public params; // maps challengeIDs to associated challenge data mapping(uint => Challenge) public challenges; // maps pollIDs to intended data change if poll passes mapping(bytes32 => ParamProposal) public proposals; // Global Variables EIP20Interface public token; PLCRVoting public voting; uint public PROCESSBY = 604800; // 7 days /** @dev Initializer Can only be called once @param _token The address where the ERC20 token contract is deployed @param _plcr address of a PLCR voting contract for the provided token @notice _parameters array of canonical parameters */ function init( address _token, address _plcr, uint[] _parameters ) public { require(_token != 0 && address(token) == 0); require(_plcr != 0 && address(voting) == 0); token = EIP20Interface(_token); voting = PLCRVoting(_plcr); // minimum deposit for listing to be whitelisted set("minDeposit", _parameters[0]); // minimum deposit to propose a reparameterization set("pMinDeposit", _parameters[1]); // period over which applicants wait to be whitelisted set("applyStageLen", _parameters[2]); // period over which reparmeterization proposals wait to be processed set("pApplyStageLen", _parameters[3]); // length of commit period for voting set("commitStageLen", _parameters[4]); // length of commit period for voting in parameterizer set("pCommitStageLen", _parameters[5]); // length of reveal period for voting set("revealStageLen", _parameters[6]); // length of reveal period for voting in parameterizer set("pRevealStageLen", _parameters[7]); // percentage of losing party's deposit distributed to winning party set("dispensationPct", _parameters[8]); // percentage of losing party's deposit distributed to winning party in parameterizer set("pDispensationPct", _parameters[9]); // type of majority out of 100 necessary for candidate success set("voteQuorum", _parameters[10]); // type of majority out of 100 necessary for proposal success in parameterizer set("pVoteQuorum", _parameters[11]); } // ----------------------- // TOKEN HOLDER INTERFACE // ----------------------- /** @notice propose a reparamaterization of the key _name's value to _value. @param _name the name of the proposed param to be set @param _value the proposed value to set the param to be set */ function proposeReparameterization(string _name, uint _value) public returns (bytes32) { uint deposit = get("pMinDeposit"); bytes32 propID = keccak256(_name, _value); if (keccak256(_name) == keccak256("dispensationPct") || keccak256(_name) == keccak256("pDispensationPct")) { require(_value <= 100); } require(!propExists(propID)); // Forbid duplicate proposals require(get(_name) != _value); // Forbid NOOP reparameterizations // attach name and value to pollID proposals[propID] = ParamProposal({ appExpiry: now.add(get("pApplyStageLen")), challengeID: 0, deposit: deposit, name: _name, owner: msg.sender, processBy: now.add(get("pApplyStageLen")) .add(get("pCommitStageLen")) .add(get("pRevealStageLen")) .add(PROCESSBY), value: _value }); require(token.transferFrom(msg.sender, this, deposit)); // escrow tokens (deposit amt) emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender); return propID; } /** @notice challenge the provided proposal ID, and put tokens at stake to do so. @param _propID the proposal ID to challenge */ function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) { ParamProposal memory prop = proposals[_propID]; uint deposit = prop.deposit; require(propExists(_propID) && prop.challengeID == 0); //start poll uint pollID = voting.startPoll( get("pVoteQuorum"), get("pCommitStageLen"), get("pRevealStageLen") ); challenges[pollID] = Challenge({ challenger: msg.sender, rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100), stake: deposit, resolved: false, winningTokens: 0 }); proposals[_propID].challengeID = pollID; // update listing to store most recent challenge //take tokens from challenger require(token.transferFrom(msg.sender, this, deposit)); var (commitEndDate, revealEndDate,) = voting.pollMap(pollID); emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender); return pollID; } /** @notice for the provided proposal ID, set it, resolve its challenge, or delete it depending on whether it can be set, has a challenge which can be resolved, or if its "process by" date has passed @param _propID the proposal ID to make a determination and state transition for */ function processProposal(bytes32 _propID) public { ParamProposal storage prop = proposals[_propID]; address propOwner = prop.owner; uint propDeposit = prop.deposit; // Before any token transfers, deleting the proposal will ensure that if reentrancy occurs the // prop.owner and prop.deposit will be 0, thereby preventing theft if (canBeSet(_propID)) { // There is no challenge against the proposal. The processBy date for the proposal has not // passed, but the proposal's appExpirty date has passed. set(prop.name, prop.value); emit _ProposalAccepted(_propID, prop.name, prop.value); delete proposals[_propID]; require(token.transfer(propOwner, propDeposit)); } else if (challengeCanBeResolved(_propID)) { // There is a challenge against the proposal. resolveChallenge(_propID); } else if (now > prop.processBy) { // There is no challenge against the proposal, but the processBy date has passed. emit _ProposalExpired(_propID); delete proposals[_propID]; require(token.transfer(propOwner, propDeposit)); } else { // There is no challenge against the proposal, and neither the appExpiry date nor the // processBy date has passed. revert(); } assert(get("dispensationPct") <= 100); assert(get("pDispensationPct") <= 100); // verify that future proposal appExpiry and processBy times will not overflow now.add(get("pApplyStageLen")) .add(get("pCommitStageLen")) .add(get("pRevealStageLen")) .add(PROCESSBY); delete proposals[_propID]; } /** @notice Claim the tokens owed for the msg.sender in the provided challenge @param _challengeID the challenge ID to claim tokens for @param _salt the salt used to vote in the challenge being withdrawn for */ function claimReward(uint _challengeID, uint _salt) public { // ensure voter has not already claimed tokens and challenge results have been processed require(challenges[_challengeID].tokenClaims[msg.sender] == false); require(challenges[_challengeID].resolved == true); uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt); uint reward = voterReward(msg.sender, _challengeID, _salt); // subtract voter's information to preserve the participation ratios of other voters // compared to the remaining pool of rewards challenges[_challengeID].winningTokens -= voterTokens; challenges[_challengeID].rewardPool -= reward; // ensures a voter cannot claim tokens again challenges[_challengeID].tokenClaims[msg.sender] = true; emit _RewardClaimed(_challengeID, reward, msg.sender); require(token.transfer(msg.sender, reward)); } /** @dev Called by a voter to claim their rewards for each completed vote. Someone must call updateStatus() before this can be called. @param _challengeIDs The PLCR pollIDs of the challenges rewards are being claimed for @param _salts The salts of a voter's commit hashes in the given polls */ function claimRewards(uint[] _challengeIDs, uint[] _salts) public { // make sure the array lengths are the same require(_challengeIDs.length == _salts.length); // loop through arrays, claiming each individual vote reward for (uint i = 0; i < _challengeIDs.length; i++) { claimReward(_challengeIDs[i], _salts[i]); } } // -------- // GETTERS // -------- /** @dev Calculates the provided voter's token reward for the given poll. @param _voter The address of the voter whose reward balance is to be returned @param _challengeID The ID of the challenge the voter's reward is being calculated for @param _salt The salt of the voter's commit hash in the given poll @return The uint indicating the voter's reward */ function voterReward(address _voter, uint _challengeID, uint _salt) public view returns (uint) { uint winningTokens = challenges[_challengeID].winningTokens; uint rewardPool = challenges[_challengeID].rewardPool; uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt); return (voterTokens * rewardPool) / winningTokens; } /** @notice Determines whether a proposal passed its application stage without a challenge @param _propID The proposal ID for which to determine whether its application stage passed without a challenge */ function canBeSet(bytes32 _propID) view public returns (bool) { ParamProposal memory prop = proposals[_propID]; return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0); } /** @notice Determines whether a proposal exists for the provided proposal ID @param _propID The proposal ID whose existance is to be determined */ function propExists(bytes32 _propID) view public returns (bool) { return proposals[_propID].processBy > 0; } /** @notice Determines whether the provided proposal ID has a challenge which can be resolved @param _propID The proposal ID whose challenge to inspect */ function challengeCanBeResolved(bytes32 _propID) view public returns (bool) { ParamProposal memory prop = proposals[_propID]; Challenge memory challenge = challenges[prop.challengeID]; return (prop.challengeID > 0 && challenge.resolved == false && voting.pollEnded(prop.challengeID)); } /** @notice Determines the number of tokens to awarded to the winning party in a challenge @param _challengeID The challengeID to determine a reward for */ function challengeWinnerReward(uint _challengeID) public view returns (uint) { if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) { // Edge case, nobody voted, give all tokens to the challenger. return 2 * challenges[_challengeID].stake; } return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool; } /** @notice gets the parameter keyed by the provided name value from the params mapping @param _name the key whose value is to be determined */ function get(string _name) public view returns (uint value) { return params[keccak256(_name)]; } /** @dev Getter for Challenge tokenClaims mappings @param _challengeID The challengeID to query @param _voter The voter whose claim status to query for the provided challengeID */ function tokenClaims(uint _challengeID, address _voter) public view returns (bool) { return challenges[_challengeID].tokenClaims[_voter]; } // ---------------- // PRIVATE FUNCTIONS // ---------------- /** @dev resolves a challenge for the provided _propID. It must be checked in advance whether the _propID has a challenge on it @param _propID the proposal ID whose challenge is to be resolved. */ function resolveChallenge(bytes32 _propID) private { ParamProposal memory prop = proposals[_propID]; Challenge storage challenge = challenges[prop.challengeID]; // winner gets back their full staked deposit, and dispensationPct*loser's stake uint reward = challengeWinnerReward(prop.challengeID); challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID); challenge.resolved = true; if (voting.isPassed(prop.challengeID)) { // The challenge failed if(prop.processBy > now) { set(prop.name, prop.value); } emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens); require(token.transfer(prop.owner, reward)); } else { // The challenge succeeded or nobody voted emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens); require(token.transfer(challenges[prop.challengeID].challenger, reward)); } } /** @dev sets the param keted by the provided name to the provided value @param _name the name of the param to be set @param _value the value to set the param to be set */ function set(string _name, uint _value) private { params[keccak256(_name)] = _value; } } // File: plcr-revival/ProxyFactory.sol /*** * Shoutouts: * * Bytecode origin https://www.reddit.com/r/ethereum/comments/6ic49q/any_assembly_programmers_willing_to_write_a/dj5ceuw/ * Modified version of Vitalik's https://www.reddit.com/r/ethereum/comments/6c1jui/delegatecall_forwarders_how_to_save_5098_on/ * Credits to Jorge Izquierdo (@izqui) for coming up with this design here: https://gist.github.com/izqui/7f904443e6d19c1ab52ec7f5ad46b3a8 * Credits to Stefan George (@Georgi87) for inspiration for many of the improvements from Gnosis Safe: https://github.com/gnosis/gnosis-safe-contracts * * This version has many improvements over the original @izqui's library like using REVERT instead of THROWing on failed calls. * It also implements the awesome design pattern for initializing code as seen in Gnosis Safe Factory: https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/ProxyFactory.sol * but unlike this last one it doesn't require that you waste storage on both the proxy and the proxied contracts (v. https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/Proxy.sol#L8 & https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol#L14) * * * v0.0.2 * The proxy is now only 60 bytes long in total. Constructor included. * No functionalities were added. The change was just to make the proxy leaner. * * v0.0.3 * Thanks @dacarley for noticing the incorrect check for the subsequent call to the proxy. 🙌 * Note: I'm creating a new version of this that doesn't need that one call. * Will add tests and put this in its own repository soon™. * * v0.0.4 * All the merit in this fix + update of the factory is @dacarley 's. 🙌 * Thank you! 😄 * * Potential updates can be found at https://gist.github.com/GNSPS/ba7b88565c947cfd781d44cf469c2ddb * ***/ pragma solidity ^0.4.19; /* solhint-disable no-inline-assembly, indent, state-visibility, avoid-low-level-calls */ contract ProxyFactory { event ProxyDeployed(address proxyAddress, address targetAddress); event ProxiesDeployed(address[] proxyAddresses, address targetAddress); function createManyProxies(uint256 _count, address _target, bytes _data) public { address[] memory proxyAddresses = new address[](_count); for (uint256 i = 0; i < _count; ++i) { proxyAddresses[i] = createProxyImpl(_target, _data); } ProxiesDeployed(proxyAddresses, _target); } function createProxy(address _target, bytes _data) public returns (address proxyContract) { proxyContract = createProxyImpl(_target, _data); ProxyDeployed(proxyContract, _target); } function createProxyImpl(address _target, bytes _data) internal returns (address proxyContract) { assembly { let contractCode := mload(0x40) // Find empty storage location using "free memory pointer" mstore(add(contractCode, 0x0b), _target) // Add target address, with a 11 bytes [i.e. 23 - (32 - 20)] offset to later accomodate first part of the bytecode mstore(sub(contractCode, 0x09), 0x000000000000000000603160008181600b9039f3600080808080368092803773) // First part of the bytecode, shifted left by 9 bytes, overwrites left padding of target address mstore(add(contractCode, 0x2b), 0x5af43d828181803e808314602f57f35bfd000000000000000000000000000000) // Final part of bytecode, offset by 43 bytes proxyContract := create(0, contractCode, 60) // total length 60 bytes if iszero(extcodesize(proxyContract)) { revert(0, 0) } // check if the _data.length > 0 and if it is forward it to the newly created contract let dataLength := mload(_data) if iszero(iszero(dataLength)) { if iszero(call(gas, proxyContract, 0, add(_data, 0x20), dataLength, 0, 0)) { revert(0, 0) } } } } } // File: tokens/eip20/EIP20.sol /* Implements EIP20 token standard: https://github.com/ethereum/EIPs/issues/20 .*/ pragma solidity ^0.4.8; contract EIP20 is EIP20Interface { uint256 constant MAX_UINT256 = 2**256 - 1; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EIP20( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } // File: plcr-revival/PLCRFactory.sol contract PLCRFactory { event newPLCR(address creator, EIP20 token, PLCRVoting plcr); ProxyFactory public proxyFactory; PLCRVoting public canonizedPLCR; /// @dev constructor deploys a new canonical PLCRVoting contract and a proxyFactory. constructor() { canonizedPLCR = new PLCRVoting(); proxyFactory = new ProxyFactory(); } /* @dev deploys and initializes a new PLCRVoting contract that consumes a token at an address supplied by the user. @param _token an EIP20 token to be consumed by the new PLCR contract */ function newPLCRBYOToken(EIP20 _token) public returns (PLCRVoting) { PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, "")); plcr.init(_token); emit newPLCR(msg.sender, _token, plcr); return plcr; } /* @dev deploys and initializes a new PLCRVoting contract and an EIP20 to be consumed by the PLCR's initializer. @param _supply the total number of tokens to mint in the EIP20 contract @param _name the name of the new EIP20 token @param _decimals the decimal precision to be used in rendering balances in the EIP20 token @param _symbol the symbol of the new EIP20 token */ function newPLCRWithToken( uint _supply, string _name, uint8 _decimals, string _symbol ) public returns (PLCRVoting) { // Create a new token and give all the tokens to the PLCR creator EIP20 token = new EIP20(_supply, _name, _decimals, _symbol); token.transfer(msg.sender, _supply); // Create and initialize a new PLCR contract PLCRVoting plcr = PLCRVoting(proxyFactory.createProxy(canonizedPLCR, "")); plcr.init(token); emit newPLCR(msg.sender, token, plcr); return plcr; } } // File: contracts/ParameterizerFactory.sol contract ParameterizerFactory { event NewParameterizer(address creator, address token, address plcr, Parameterizer parameterizer); PLCRFactory public plcrFactory; ProxyFactory public proxyFactory; Parameterizer public canonizedParameterizer; /// @dev constructor deploys a new canonical Parameterizer contract and a proxyFactory. constructor(PLCRFactory _plcrFactory) public { plcrFactory = _plcrFactory; proxyFactory = plcrFactory.proxyFactory(); canonizedParameterizer = new Parameterizer(); } /* @dev deploys and initializes a new Parameterizer contract that consumes a token at an address supplied by the user. @param _token an EIP20 token to be consumed by the new Parameterizer contract @param _plcr a PLCR voting contract to be consumed by the new Parameterizer contract @param _parameters array of canonical parameters */ function newParameterizerBYOToken( EIP20 _token, uint[] _parameters ) public returns (Parameterizer) { PLCRVoting plcr = plcrFactory.newPLCRBYOToken(_token); Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, "")); parameterizer.init( _token, plcr, _parameters ); emit NewParameterizer(msg.sender, _token, plcr, parameterizer); return parameterizer; } /* @dev deploys and initializes new EIP20, PLCRVoting, and Parameterizer contracts @param _supply the total number of tokens to mint in the EIP20 contract @param _name the name of the new EIP20 token @param _decimals the decimal precision to be used in rendering balances in the EIP20 token @param _symbol the symbol of the new EIP20 token @param _parameters array of canonical parameters */ function newParameterizerWithToken( uint _supply, string _name, uint8 _decimals, string _symbol, uint[] _parameters ) public returns (Parameterizer) { // Creates a new EIP20 token & transfers the supply to creator (msg.sender) // Deploys & initializes a new PLCRVoting contract PLCRVoting plcr = plcrFactory.newPLCRWithToken(_supply, _name, _decimals, _symbol); EIP20 token = EIP20(plcr.token()); token.transfer(msg.sender, _supply); // Create & initialize a new Parameterizer contract Parameterizer parameterizer = Parameterizer(proxyFactory.createProxy(canonizedParameterizer, "")); parameterizer.init( token, plcr, _parameters ); emit NewParameterizer(msg.sender, token, plcr, parameterizer); return parameterizer; } }
/ minimum deposit for listing to be whitelisted minimum deposit to propose a reparameterization period over which applicants wait to be whitelisted period over which reparmeterization proposals wait to be processed length of commit period for voting length of commit period for voting in parameterizer length of reveal period for voting length of reveal period for voting in parameterizer percentage of losing party's deposit distributed to winning party percentage of losing party's deposit distributed to winning party in parameterizer type of majority out of 100 necessary for candidate success type of majority out of 100 necessary for proposal success in parameterizer
function init( address _token, address _plcr, uint[] _parameters ) public { require(_token != 0 && address(token) == 0); require(_plcr != 0 && address(voting) == 0); token = EIP20Interface(_token); voting = PLCRVoting(_plcr); set("minDeposit", _parameters[0]); set("pMinDeposit", _parameters[1]); set("applyStageLen", _parameters[2]); set("pApplyStageLen", _parameters[3]); set("commitStageLen", _parameters[4]); set("pCommitStageLen", _parameters[5]); set("revealStageLen", _parameters[6]); set("pRevealStageLen", _parameters[7]); set("dispensationPct", _parameters[8]); set("pDispensationPct", _parameters[9]); set("voteQuorum", _parameters[10]); set("pVoteQuorum", _parameters[11]); } @param _name the name of the proposed param to be set @param _value the proposed value to set the param to be set
502,152
./partial_match/1/0xAC3DfD73f11e19143efe7C7631e4C8abFD80BCcE/sources/ThePool.sol
File: @openzeppelin/contracts/token/ERC20/IERC20.sol Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function whenSent(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); }
2,666,958
pragma solidity ^0.8.11; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import {Unauthorized, IllegalState, IllegalArgument} from "./base/Errors.sol"; import "./base/Multicall.sol"; import "./base/Mutex.sol"; import "./interfaces/IAlchemistV2.sol"; import "./interfaces/IERC20Minimal.sol"; import "./interfaces/IERC20TokenReceiver.sol"; import "./interfaces/ITokenAdapter.sol"; import "./interfaces/IAlchemicToken.sol"; import "./interfaces/IWhitelist.sol"; import "./libraries/SafeCast.sol"; import "./libraries/Sets.sol"; import "./libraries/TokenUtils.sol"; import "./libraries/Limiters.sol"; /// @title AlchemistV2 /// @author Alchemix Finance contract AlchemistV2 is IAlchemistV2, Initializable, Multicall, Mutex { using Limiters for Limiters.LinearGrowthLimiter; using Sets for Sets.AddressSet; /// @notice A user account. struct Account { // A signed value which represents the current amount of debt or credit that the account has accrued. // Positive values indicate debt, negative values indicate credit. int256 debt; // The share balances for each yield token. mapping(address => uint256) balances; // The last values recorded for accrued weights for each yield token. mapping(address => uint256) lastAccruedWeights; // The set of yield tokens that the account has deposited into the system. Sets.AddressSet depositedTokens; // The allowances for mints. mapping(address => uint256) mintAllowances; // The allowances for withdrawals. mapping(address => mapping(address => uint256)) withdrawAllowances; } /// @notice The number of basis points there are to represent exactly 100%. uint256 public constant BPS = 10000; /// @notice The scalar used for conversion of integral numbers to fixed point numbers. Fixed point numbers in this /// implementation have 18 decimals of resolution, meaning that 1 is represented as 1e18, 0.5 is /// represented as 5e17, and 2 is represented as 2e18. uint256 public constant FIXED_POINT_SCALAR = 1e18; /// @inheritdoc IAlchemistV2Immutables string public constant override version = "2.2.6"; /// @inheritdoc IAlchemistV2Immutables address public override debtToken; /// @inheritdoc IAlchemistV2State address public override admin; /// @inheritdoc IAlchemistV2State address public override pendingAdmin; /// @inheritdoc IAlchemistV2State mapping(address => bool) public override sentinels; /// @inheritdoc IAlchemistV2State mapping(address => bool) public override keepers; /// @inheritdoc IAlchemistV2State address public override transmuter; /// @inheritdoc IAlchemistV2State uint256 public override minimumCollateralization; /// @inheritdoc IAlchemistV2State uint256 public override protocolFee; /// @inheritdoc IAlchemistV2State address public override protocolFeeReceiver; /// @inheritdoc IAlchemistV2State address public override whitelist; /// @dev A linear growth function that limits the amount of debt-token minted. Limiters.LinearGrowthLimiter private _mintingLimiter; // @dev The repay limiters for each underlying token. mapping(address => Limiters.LinearGrowthLimiter) private _repayLimiters; // @dev The liquidation limiters for each underlying token. mapping(address => Limiters.LinearGrowthLimiter) private _liquidationLimiters; /// @dev Accounts mapped by the address that owns them. mapping(address => Account) private _accounts; /// @dev Underlying token parameters mapped by token address. mapping(address => UnderlyingTokenParams) private _underlyingTokens; /// @dev Yield token parameters mapped by token address. mapping(address => YieldTokenParams) private _yieldTokens; /// @dev An iterable set of the underlying tokens that are supported by the system. Sets.AddressSet private _supportedUnderlyingTokens; /// @dev An iterable set of the yield tokens that are supported by the system. Sets.AddressSet private _supportedYieldTokens; constructor() initializer {} /// @inheritdoc IAlchemistV2State function getYieldTokensPerShare(address yieldToken) external view override returns (uint256) { return _convertSharesToYieldTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals); } /// @inheritdoc IAlchemistV2State function getUnderlyingTokensPerShare(address yieldToken) external view override returns (uint256) { return _convertSharesToUnderlyingTokens(yieldToken, 10**_yieldTokens[yieldToken].decimals); } /// @inheritdoc IAlchemistV2State function getSupportedUnderlyingTokens() external view override returns (address[] memory) { return _supportedUnderlyingTokens.values; } /// @inheritdoc IAlchemistV2State function getSupportedYieldTokens() external view override returns (address[] memory) { return _supportedYieldTokens.values; } /// @inheritdoc IAlchemistV2State function isSupportedUnderlyingToken(address underlyingToken) external view override returns (bool) { return _supportedUnderlyingTokens.contains(underlyingToken); } /// @inheritdoc IAlchemistV2State function isSupportedYieldToken(address yieldToken) external view override returns (bool) { return _supportedYieldTokens.contains(yieldToken); } /// @inheritdoc IAlchemistV2State function accounts(address owner) external view override returns ( int256 debt, address[] memory depositedTokens ) { Account storage account = _accounts[owner]; return ( _calculateUnrealizedDebt(owner), account.depositedTokens.values ); } /// @inheritdoc IAlchemistV2State function positions(address owner, address yieldToken) external view override returns ( uint256 shares, uint256 lastAccruedWeight ) { Account storage account = _accounts[owner]; return (account.balances[yieldToken], account.lastAccruedWeights[yieldToken]); } /// @inheritdoc IAlchemistV2State function mintAllowance(address owner, address spender) external view override returns (uint256) { Account storage account = _accounts[owner]; return account.mintAllowances[spender]; } /// @inheritdoc IAlchemistV2State function withdrawAllowance(address owner, address spender, address yieldToken) external view override returns (uint256) { Account storage account = _accounts[owner]; return account.withdrawAllowances[spender][yieldToken]; } /// @inheritdoc IAlchemistV2State function getUnderlyingTokenParameters(address underlyingToken) external view override returns (UnderlyingTokenParams memory) { return _underlyingTokens[underlyingToken]; } /// @inheritdoc IAlchemistV2State function getYieldTokenParameters(address yieldToken) external view override returns (YieldTokenParams memory) { return _yieldTokens[yieldToken]; } /// @inheritdoc IAlchemistV2State function getMintLimitInfo() external view override returns ( uint256 currentLimit, uint256 rate, uint256 maximum ) { return ( _mintingLimiter.get(), _mintingLimiter.rate, _mintingLimiter.maximum ); } /// @inheritdoc IAlchemistV2State function getRepayLimitInfo(address underlyingToken) external view override returns ( uint256 currentLimit, uint256 rate, uint256 maximum ) { Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken]; return ( limiter.get(), limiter.rate, limiter.maximum ); } /// @inheritdoc IAlchemistV2State function getLiquidationLimitInfo(address underlyingToken) external view override returns ( uint256 currentLimit, uint256 rate, uint256 maximum ) { Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken]; return ( limiter.get(), limiter.rate, limiter.maximum ); } /// @inheritdoc IAlchemistV2AdminActions function initialize(InitializationParams memory params) external initializer { _checkArgument(params.protocolFee <= BPS); debtToken = params.debtToken; admin = params.admin; transmuter = params.transmuter; minimumCollateralization = params.minimumCollateralization; protocolFee = params.protocolFee; protocolFeeReceiver = params.protocolFeeReceiver; whitelist = params.whitelist; _mintingLimiter = Limiters.createLinearGrowthLimiter( params.mintingLimitMaximum, params.mintingLimitBlocks, params.mintingLimitMinimum ); emit AdminUpdated(admin); emit TransmuterUpdated(transmuter); emit MinimumCollateralizationUpdated(minimumCollateralization); emit ProtocolFeeUpdated(protocolFee); emit ProtocolFeeReceiverUpdated(protocolFeeReceiver); emit MintingLimitUpdated(params.mintingLimitMaximum, params.mintingLimitBlocks); } /// @inheritdoc IAlchemistV2AdminActions function setPendingAdmin(address value) external override { _onlyAdmin(); pendingAdmin = value; emit PendingAdminUpdated(value); } /// @inheritdoc IAlchemistV2AdminActions function acceptAdmin() external override { _checkState(pendingAdmin != address(0)); if (msg.sender != pendingAdmin) { revert Unauthorized(); } admin = pendingAdmin; pendingAdmin = address(0); emit AdminUpdated(admin); emit PendingAdminUpdated(address(0)); } /// @inheritdoc IAlchemistV2AdminActions function setSentinel(address sentinel, bool flag) external override { _onlyAdmin(); sentinels[sentinel] = flag; emit SentinelSet(sentinel, flag); } /// @inheritdoc IAlchemistV2AdminActions function setKeeper(address keeper, bool flag) external override { _onlyAdmin(); keepers[keeper] = flag; emit KeeperSet(keeper, flag); } /// @inheritdoc IAlchemistV2AdminActions function addUnderlyingToken(address underlyingToken, UnderlyingTokenConfig calldata config) external override lock { _onlyAdmin(); _checkState(!_supportedUnderlyingTokens.contains(underlyingToken)); uint8 tokenDecimals = TokenUtils.expectDecimals(underlyingToken); uint8 debtTokenDecimals = TokenUtils.expectDecimals(debtToken); _checkArgument(tokenDecimals <= debtTokenDecimals); _underlyingTokens[underlyingToken] = UnderlyingTokenParams({ decimals: tokenDecimals, conversionFactor: 10**(debtTokenDecimals - tokenDecimals), enabled: false }); _repayLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter( config.repayLimitMaximum, config.repayLimitBlocks, config.repayLimitMinimum ); _liquidationLimiters[underlyingToken] = Limiters.createLinearGrowthLimiter( config.liquidationLimitMaximum, config.liquidationLimitBlocks, config.liquidationLimitMinimum ); _supportedUnderlyingTokens.add(underlyingToken); emit AddUnderlyingToken(underlyingToken); } /// @inheritdoc IAlchemistV2AdminActions function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external override lock { _onlyAdmin(); _checkArgument(config.maximumLoss <= BPS); _checkArgument(config.creditUnlockBlocks > 0); _checkState(!_supportedYieldTokens.contains(yieldToken)); ITokenAdapter adapter = ITokenAdapter(config.adapter); _checkState(yieldToken == adapter.token()); _checkSupportedUnderlyingToken(adapter.underlyingToken()); _yieldTokens[yieldToken] = YieldTokenParams({ decimals: TokenUtils.expectDecimals(yieldToken), underlyingToken: adapter.underlyingToken(), adapter: config.adapter, maximumLoss: config.maximumLoss, maximumExpectedValue: config.maximumExpectedValue, creditUnlockRate: FIXED_POINT_SCALAR / config.creditUnlockBlocks, activeBalance: 0, harvestableBalance: 0, totalShares: 0, expectedValue: 0, accruedWeight: 0, pendingCredit: 0, distributedCredit: 0, lastDistributionBlock: 0, enabled: false }); _supportedYieldTokens.add(yieldToken); TokenUtils.safeApprove(yieldToken, config.adapter, type(uint256).max); TokenUtils.safeApprove(adapter.underlyingToken(), config.adapter, type(uint256).max); emit AddYieldToken(yieldToken); emit TokenAdapterUpdated(yieldToken, config.adapter); emit MaximumLossUpdated(yieldToken, config.maximumLoss); } /// @inheritdoc IAlchemistV2AdminActions function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external override { _onlySentinelOrAdmin(); _checkSupportedUnderlyingToken(underlyingToken); _underlyingTokens[underlyingToken].enabled = enabled; emit UnderlyingTokenEnabled(underlyingToken, enabled); } /// @inheritdoc IAlchemistV2AdminActions function setYieldTokenEnabled(address yieldToken, bool enabled) external override { _onlySentinelOrAdmin(); _checkSupportedYieldToken(yieldToken); _yieldTokens[yieldToken].enabled = enabled; emit YieldTokenEnabled(yieldToken, enabled); } /// @inheritdoc IAlchemistV2AdminActions function configureRepayLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override { _onlyAdmin(); _checkSupportedUnderlyingToken(underlyingToken); _repayLimiters[underlyingToken].update(); _repayLimiters[underlyingToken].configure(maximum, blocks); emit RepayLimitUpdated(underlyingToken, maximum, blocks); } /// @inheritdoc IAlchemistV2AdminActions function configureLiquidationLimit(address underlyingToken, uint256 maximum, uint256 blocks) external override { _onlyAdmin(); _checkSupportedUnderlyingToken(underlyingToken); _liquidationLimiters[underlyingToken].update(); _liquidationLimiters[underlyingToken].configure(maximum, blocks); emit LiquidationLimitUpdated(underlyingToken, maximum, blocks); } /// @inheritdoc IAlchemistV2AdminActions function setTransmuter(address value) external override { _onlyAdmin(); _checkArgument(value != address(0)); transmuter = value; emit TransmuterUpdated(value); } /// @inheritdoc IAlchemistV2AdminActions function setMinimumCollateralization(uint256 value) external override { _onlyAdmin(); minimumCollateralization = value; emit MinimumCollateralizationUpdated(value); } /// @inheritdoc IAlchemistV2AdminActions function setProtocolFee(uint256 value) external override { _onlyAdmin(); _checkArgument(value <= BPS); protocolFee = value; emit ProtocolFeeUpdated(value); } /// @inheritdoc IAlchemistV2AdminActions function setProtocolFeeReceiver(address value) external override { _onlyAdmin(); _checkArgument(value != address(0)); protocolFeeReceiver = value; emit ProtocolFeeReceiverUpdated(value); } /// @inheritdoc IAlchemistV2AdminActions function configureMintingLimit(uint256 maximum, uint256 rate) external override { _onlyAdmin(); _mintingLimiter.update(); _mintingLimiter.configure(maximum, rate); emit MintingLimitUpdated(maximum, rate); } /// @inheritdoc IAlchemistV2AdminActions function configureCreditUnlockRate(address yieldToken, uint256 blocks) external override { _onlyAdmin(); _checkArgument(blocks > 0); _checkSupportedYieldToken(yieldToken); _yieldTokens[yieldToken].creditUnlockRate = FIXED_POINT_SCALAR / blocks; emit CreditUnlockRateUpdated(yieldToken, blocks); } /// @inheritdoc IAlchemistV2AdminActions function setTokenAdapter(address yieldToken, address adapter) external override { _onlyAdmin(); _checkState(yieldToken == ITokenAdapter(adapter).token()); _checkSupportedYieldToken(yieldToken); _yieldTokens[yieldToken].adapter = adapter; TokenUtils.safeApprove(yieldToken, adapter, type(uint256).max); TokenUtils.safeApprove(ITokenAdapter(adapter).underlyingToken(), adapter, type(uint256).max); emit TokenAdapterUpdated(yieldToken, adapter); } /// @inheritdoc IAlchemistV2AdminActions function setMaximumExpectedValue(address yieldToken, uint256 value) external override { _onlyAdmin(); _checkSupportedYieldToken(yieldToken); _yieldTokens[yieldToken].maximumExpectedValue = value; emit MaximumExpectedValueUpdated(yieldToken, value); } /// @inheritdoc IAlchemistV2AdminActions function setMaximumLoss(address yieldToken, uint256 value) external override { _onlyAdmin(); _checkArgument(value <= BPS); _checkSupportedYieldToken(yieldToken); _yieldTokens[yieldToken].maximumLoss = value; emit MaximumLossUpdated(yieldToken, value); } /// @inheritdoc IAlchemistV2AdminActions function snap(address yieldToken) external override lock { _onlyAdmin(); _checkSupportedYieldToken(yieldToken); uint256 expectedValue = _convertYieldTokensToUnderlying(yieldToken, _yieldTokens[yieldToken].activeBalance); _yieldTokens[yieldToken].expectedValue = expectedValue; emit Snap(yieldToken, expectedValue); } /// @inheritdoc IAlchemistV2Actions function approveMint(address spender, uint256 amount) external override { _onlyWhitelisted(); _approveMint(msg.sender, spender, amount); } /// @inheritdoc IAlchemistV2Actions function approveWithdraw(address spender, address yieldToken, uint256 shares) external override { _onlyWhitelisted(); _checkSupportedYieldToken(yieldToken); _approveWithdraw(msg.sender, spender, yieldToken, shares); } /// @inheritdoc IAlchemistV2Actions function poke(address owner) external override lock { _onlyWhitelisted(); _preemptivelyHarvestDeposited(owner); _distributeUnlockedCreditDeposited(owner); _poke(owner); } /// @inheritdoc IAlchemistV2Actions function deposit( address yieldToken, uint256 amount, address recipient ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); // Deposit the yield tokens to the recipient. uint256 shares = _deposit(yieldToken, amount, recipient); // Transfer tokens from the message sender now that the internal storage updates have been committed. TokenUtils.safeTransferFrom(yieldToken, msg.sender, address(this), amount); return shares; } /// @inheritdoc IAlchemistV2Actions function depositUnderlying( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); // Before depositing, the underlying tokens must be wrapped into yield tokens. uint256 amountYieldTokens = _wrap(yieldToken, amount, minimumAmountOut); // Deposit the yield-tokens to the recipient. return _deposit(yieldToken, amountYieldTokens, recipient); } /// @inheritdoc IAlchemistV2Actions function withdraw( address yieldToken, uint256 shares, address recipient ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); // Withdraw the shares from the system. uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient); // Transfer the yield tokens to the recipient. TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens); return amountYieldTokens; } /// @inheritdoc IAlchemistV2Actions function withdrawFrom( address owner, address yieldToken, uint256 shares, address recipient ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); // Preemptively try and decrease the withdrawal allowance. This will save gas when the allowance is not // sufficient for the withdrawal. _decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares); // Withdraw the shares from the system. uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient); // Transfer the yield tokens to the recipient. TokenUtils.safeTransfer(yieldToken, recipient, amountYieldTokens); return amountYieldTokens; } /// @inheritdoc IAlchemistV2Actions function withdrawUnderlying( address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); _checkLoss(yieldToken); uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient); return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut); } /// @inheritdoc IAlchemistV2Actions function withdrawUnderlyingFrom( address owner, address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(recipient != address(0)); _checkSupportedYieldToken(yieldToken); _checkLoss(yieldToken); _decreaseWithdrawAllowance(owner, msg.sender, yieldToken, shares); uint256 amountYieldTokens = _withdraw(yieldToken, owner, shares, recipient); return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut); } /// @inheritdoc IAlchemistV2Actions function mint(uint256 amount, address recipient) external override lock { _onlyWhitelisted(); _checkArgument(amount > 0); _checkArgument(recipient != address(0)); // Mint tokens from the message sender's account to the recipient. _mint(msg.sender, amount, recipient); } /// @inheritdoc IAlchemistV2Actions function mintFrom( address owner, uint256 amount, address recipient ) external override lock { _onlyWhitelisted(); _checkArgument(amount > 0); _checkArgument(recipient != address(0)); // Preemptively try and decrease the minting allowance. This will save gas when the allowance is not sufficient // for the mint. _decreaseMintAllowance(owner, msg.sender, amount); // Mint tokens from the owner's account to the recipient. _mint(owner, amount, recipient); } /// @inheritdoc IAlchemistV2Actions function burn(uint256 amount, address recipient) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(amount > 0); _checkArgument(recipient != address(0)); // Distribute unlocked credit to depositors. _distributeUnlockedCreditDeposited(recipient); // Update the recipient's account, decrease the debt of the recipient by the number of tokens burned. _poke(recipient); // Check that the debt is greater than zero. // // It is possible that the number of debt which is repayable is equal to or less than zero after realizing the // credit that was earned since the last update. We do not want to perform a noop so we need to check that the // amount of debt to repay is greater than zero. int256 debt; _checkState((debt = _accounts[recipient].debt) > 0); // Limit how much debt can be repaid up to the current amount of debt that the account has. This prevents // situations where the user may be trying to repay their entire debt, but it decreases since they send the // transaction and causes a revert because burning can never decrease the debt below zero. // // Casts here are safe because it is asserted that debt is greater than zero. uint256 credit = amount > uint256(debt) ? uint256(debt) : amount; // Update the recipient's debt. _updateDebt(recipient, -SafeCast.toInt256(credit)); // Burn the tokens from the message sender. TokenUtils.safeBurnFrom(debtToken, msg.sender, credit); emit Burn(msg.sender, credit, recipient); return credit; } /// @inheritdoc IAlchemistV2Actions function repay(address underlyingToken, uint256 amount, address recipient) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(amount > 0); _checkArgument(recipient != address(0)); _checkSupportedUnderlyingToken(underlyingToken); _checkUnderlyingTokenEnabled(underlyingToken); // Distribute unlocked credit to depositors. _distributeUnlockedCreditDeposited(recipient); // Update the recipient's account and decrease the amount of debt incurred. _poke(recipient); // Check that the debt is greater than zero. // // It is possible that the amount of debt which is repayable is equal to or less than zero after realizing the // credit that was earned since the last update. We do not want to perform a noop so we need to check that the // amount of debt to repay is greater than zero. int256 debt; _checkState((debt = _accounts[recipient].debt) > 0); // Determine the maximum amount of underlying tokens that can be repaid. // // It is implied that this value is greater than zero because `debt` is greater than zero so a noop is not possible // beyond this point. Casting the debt to an unsigned integer is also safe because `debt` is greater than zero. uint256 maximumAmount = _normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt)); // Limit the number of underlying tokens to repay up to the maximum allowed. uint256 actualAmount = amount > maximumAmount ? maximumAmount : amount; Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken]; // Check to make sure that the underlying token repay limit has not been breached. uint256 currentRepayLimit = limiter.get(); if (actualAmount > currentRepayLimit) { revert RepayLimitExceeded(underlyingToken, actualAmount, currentRepayLimit); } uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, actualAmount); // Update the recipient's debt. _updateDebt(recipient, -SafeCast.toInt256(credit)); // Decrease the amount of the underlying token which is globally available to be repaid. limiter.decrease(actualAmount); // Transfer the repaid tokens to the transmuter. TokenUtils.safeTransferFrom(underlyingToken, msg.sender, transmuter, actualAmount); // Inform the transmuter that it has received tokens. IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, actualAmount); emit Repay(msg.sender, underlyingToken, actualAmount, recipient); return actualAmount; } /// @inheritdoc IAlchemistV2Actions function liquidate( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external override lock returns (uint256) { _onlyWhitelisted(); _checkArgument(shares > 0); YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; address underlyingToken = yieldTokenParams.underlyingToken; _checkSupportedYieldToken(yieldToken); _checkYieldTokenEnabled(yieldToken); _checkUnderlyingTokenEnabled(underlyingToken); _checkLoss(yieldToken); // Calculate the unrealized debt. // // It is possible that the number of debt which is repayable is equal to or less than zero after realizing the // credit that was earned since the last update. We do not want to perform a noop so we need to check that the // amount of debt to repay is greater than zero. int256 unrealizedDebt; _checkState((unrealizedDebt = _calculateUnrealizedDebt(msg.sender)) > 0); // Determine the maximum amount of shares that can be liquidated from the unrealized debt. // // It is implied that this value is greater than zero because `debt` is greater than zero. Casting the debt to an // unsigned integer is also safe for this reason. uint256 maximumShares = _convertUnderlyingTokensToShares( yieldToken, _normalizeDebtTokensToUnderlying(underlyingToken, uint256(unrealizedDebt)) ); // Limit the number of shares to liquidate up to the maximum allowed. uint256 actualShares = shares > maximumShares ? maximumShares : shares; // Unwrap the yield tokens that the shares are worth. uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, actualShares); uint256 amountUnderlyingTokens = _unwrap(yieldToken, amountYieldTokens, address(this), minimumAmountOut); // Again, perform another noop check. It is possible that the amount of underlying tokens that were received by // unwrapping the yield tokens was zero because the amount of yield tokens to unwrap was too small. _checkState(amountUnderlyingTokens > 0); Limiters.LinearGrowthLimiter storage limiter = _liquidationLimiters[underlyingToken]; // Check to make sure that the underlying token liquidation limit has not been breached. uint256 liquidationLimit = limiter.get(); if (amountUnderlyingTokens > liquidationLimit) { revert LiquidationLimitExceeded(underlyingToken, amountUnderlyingTokens, liquidationLimit); } // Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users // and the balance which is held by the system. This is required for `_sync` to function correctly. _preemptivelyHarvest(yieldToken); // Distribute unlocked credit to depositors. _distributeUnlockedCreditDeposited(msg.sender); uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens); // Update the message sender's account, proactively burn shares, decrease the amount of debt incurred, and then // decrease the value of the token that the system is expected to hold. _poke(msg.sender, yieldToken); _burnShares(msg.sender, yieldToken, actualShares); _updateDebt(msg.sender, -SafeCast.toInt256(credit)); _sync(yieldToken, amountYieldTokens, _usub); // Decrease the amount of the underlying token which is globally available to be liquidated. limiter.decrease(amountUnderlyingTokens); // Transfer the liquidated tokens to the transmuter. TokenUtils.safeTransfer(underlyingToken, transmuter, amountUnderlyingTokens); // Inform the transmuter that it has received tokens. IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, amountUnderlyingTokens); emit Liquidate(msg.sender, yieldToken, underlyingToken, actualShares); return actualShares; } /// @inheritdoc IAlchemistV2Actions function donate(address yieldToken, uint256 amount) external override lock { _onlyWhitelisted(); _checkArgument(amount != 0); // Distribute any unlocked credit so that the accrued weight is up to date. _distributeUnlockedCredit(yieldToken); // Update the message sender's account. This will assure that any credit that was earned is not overridden. _poke(msg.sender); uint256 shares = _yieldTokens[yieldToken].totalShares - _accounts[msg.sender].balances[yieldToken]; _yieldTokens[yieldToken].accruedWeight += amount * FIXED_POINT_SCALAR / shares; _accounts[msg.sender].lastAccruedWeights[yieldToken] = _yieldTokens[yieldToken].accruedWeight; TokenUtils.safeBurnFrom(debtToken, msg.sender, amount); emit Donate(msg.sender, yieldToken, amount); } /// @inheritdoc IAlchemistV2Actions function harvest(address yieldToken, uint256 minimumAmountOut) external override lock { _onlyKeeper(); _checkSupportedYieldToken(yieldToken); YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; // Buffer any harvestable yield tokens. This will properly synchronize the balance which is held by users // and the balance which is held by the system to be harvested during this call. _preemptivelyHarvest(yieldToken); // Load and proactively clear the amount of harvestable tokens so that future calls do not rely on stale data. // Because we cannot call an external unwrap until the amount of harvestable tokens has been calculated, // clearing this data immediately prevents any potential reentrancy attacks which would use stale harvest // buffer values. uint256 harvestableAmount = yieldTokenParams.harvestableBalance; yieldTokenParams.harvestableBalance = 0; // Check that the harvest will not be a no-op. _checkState(harvestableAmount != 0); address underlyingToken = yieldTokenParams.underlyingToken; uint256 amountUnderlyingTokens = _unwrap(yieldToken, harvestableAmount, address(this), minimumAmountOut); // Calculate how much of the unwrapped underlying tokens will be allocated for fees and distributed to users. uint256 feeAmount = amountUnderlyingTokens * protocolFee / BPS; uint256 distributeAmount = amountUnderlyingTokens - feeAmount; uint256 credit = _normalizeUnderlyingTokensToDebt(underlyingToken, distributeAmount); // Distribute credit to all of the users who hold shares of the yield token. _distributeCredit(yieldToken, credit); // Transfer the tokens to the fee receiver and transmuter. TokenUtils.safeTransfer(underlyingToken, protocolFeeReceiver, feeAmount); TokenUtils.safeTransfer(underlyingToken, transmuter, distributeAmount); // Inform the transmuter that it has received tokens. IERC20TokenReceiver(transmuter).onERC20Received(underlyingToken, distributeAmount); emit Harvest(yieldToken, minimumAmountOut, amountUnderlyingTokens); } /// @dev Checks that the `msg.sender` is the administrator. /// /// @dev `msg.sender` must be the administrator or this call will revert with an {Unauthorized} error. function _onlyAdmin() internal view { if (msg.sender != admin) { revert Unauthorized(); } } /// @dev Checks that the `msg.sender` is the administrator or a sentinel. /// /// @dev `msg.sender` must be either the administrator or a sentinel or this call will revert with an /// {Unauthorized} error. function _onlySentinelOrAdmin() internal view { // Check if the message sender is the administrator. if (msg.sender == admin) { return; } // Check if the message sender is a sentinel. After this check we can revert since we know that it is neither // the administrator or a sentinel. if (!sentinels[msg.sender]) { revert Unauthorized(); } } /// @dev Checks that the `msg.sender` is a keeper. /// /// @dev `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error. function _onlyKeeper() internal view { if (!keepers[msg.sender]) { revert Unauthorized(); } } /// @dev Preemptively harvests all of the yield tokens that have been deposited into an account. /// /// @param owner The address which owns the account. function _preemptivelyHarvestDeposited(address owner) internal { Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens; for (uint256 i = 0; i < depositedTokens.values.length; i++) { _preemptivelyHarvest(depositedTokens.values[i]); } } /// @dev Preemptively harvests `yieldToken`. /// /// @dev This will earmark yield tokens to be harvested at a future time when the current value of the token is /// greater than the expected value. The purpose of this function is to synchronize the balance of the yield /// token which is held by users versus tokens which will be seized by the protocol. /// /// @param yieldToken The address of the yield token to preemptively harvest. function _preemptivelyHarvest(address yieldToken) internal { uint256 activeBalance = _yieldTokens[yieldToken].activeBalance; if (activeBalance == 0) { return; } uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance); uint256 expectedValue = _yieldTokens[yieldToken].expectedValue; if (currentValue <= expectedValue) { return; } uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue); if (harvestable == 0) { return; } _yieldTokens[yieldToken].activeBalance -= harvestable; _yieldTokens[yieldToken].harvestableBalance += harvestable; } /// @dev Checks if a yield token is enabled. /// /// @param yieldToken The address of the yield token. function _checkYieldTokenEnabled(address yieldToken) internal view { if (!_yieldTokens[yieldToken].enabled) { revert TokenDisabled(yieldToken); } } /// @dev Checks if an underlying token is enabled. /// /// @param underlyingToken The address of the underlying token. function _checkUnderlyingTokenEnabled(address underlyingToken) internal view { if (!_underlyingTokens[underlyingToken].enabled) { revert TokenDisabled(underlyingToken); } } /// @dev Checks if an address is a supported yield token. /// /// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error. /// /// @param yieldToken The address to check. function _checkSupportedYieldToken(address yieldToken) internal view { if (!_supportedYieldTokens.contains(yieldToken)) { revert UnsupportedToken(yieldToken); } } /// @dev Checks if an address is a supported underlying token. /// /// If the address is not a supported yield token, this function will revert using a {UnsupportedToken} error. /// /// @param underlyingToken The address to check. function _checkSupportedUnderlyingToken(address underlyingToken) internal view { if (!_supportedUnderlyingTokens.contains(underlyingToken)) { revert UnsupportedToken(underlyingToken); } } /// @dev Checks if `amount` of debt tokens can be minted. /// /// @dev `amount` must be less than the current minting limit or this call will revert with a /// {MintingLimitExceeded} error. /// /// @param amount The amount to check. function _checkMintingLimit(uint256 amount) internal view { uint256 limit = _mintingLimiter.get(); if (amount > limit) { revert MintingLimitExceeded(amount, limit); } } /// @dev Checks if the current loss of `yieldToken` has exceeded its maximum acceptable loss. /// /// @dev The loss that `yieldToken` has incurred must be less than its maximum accepted value or this call will /// revert with a {LossExceeded} error. /// /// @param yieldToken The address of the yield token. function _checkLoss(address yieldToken) internal view { uint256 loss = _loss(yieldToken); uint256 maximumLoss = _yieldTokens[yieldToken].maximumLoss; if (loss > maximumLoss) { revert LossExceeded(yieldToken, loss, maximumLoss); } } /// @dev Deposits `amount` yield tokens into the account of `recipient`. /// /// @dev Emits a {Deposit} event. /// /// @param yieldToken The address of the yield token to deposit. /// @param amount The amount of yield tokens to deposit. /// @param recipient The recipient of the yield tokens. /// /// @return The number of shares minted to `recipient`. function _deposit( address yieldToken, uint256 amount, address recipient ) internal returns (uint256) { _checkArgument(amount > 0); YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; address underlyingToken = yieldTokenParams.underlyingToken; // Check that the yield token and it's underlying token are enabled. Disabling the yield token and or the // underlying token prevents the system from holding more of the disabled yield token or underlying token. _checkYieldTokenEnabled(yieldToken); _checkUnderlyingTokenEnabled(underlyingToken); // Check to assure that the token has not experienced a sudden unexpected loss. This prevents users from being // able to deposit funds and then have them siphoned if the price recovers. _checkLoss(yieldToken); // Buffers any harvestable yield tokens. This will properly synchronize the balance which is held by users // and the balance which is held by the system to eventually be harvested. _preemptivelyHarvest(yieldToken); // Distribute unlocked credit to depositors. _distributeUnlockedCreditDeposited(recipient); // Update the recipient's account, proactively issue shares for the deposited tokens to the recipient, and then // increase the value of the token that the system is expected to hold. _poke(recipient, yieldToken); uint256 shares = _issueSharesForAmount(recipient, yieldToken, amount); _sync(yieldToken, amount, _uadd); // Check that the maximum expected value has not been breached. uint256 maximumExpectedValue = yieldTokenParams.maximumExpectedValue; if (yieldTokenParams.expectedValue > maximumExpectedValue) { revert ExpectedValueExceeded(yieldToken, amount, maximumExpectedValue); } emit Deposit(msg.sender, yieldToken, amount, recipient); return shares; } /// @dev Withdraw `yieldToken` from the account owned by `owner` by burning shares and receiving yield tokens of /// equivalent value. /// /// @dev Emits a {Withdraw} event. /// /// @param yieldToken The address of the yield token to withdraw. /// @param owner The address of the account owner to withdraw from. /// @param shares The number of shares to burn. /// @param recipient The recipient of the withdrawn shares. This parameter is only used for logging. /// /// @return The amount of yield tokens that the burned shares were exchanged for. function _withdraw( address yieldToken, address owner, uint256 shares, address recipient ) internal returns (uint256) { // Buffers any harvestable yield tokens that the owner of the account has deposited. This will properly // synchronize the balance of all the tokens held by the owner so that the validation check properly // computes the total value of the tokens held by the owner. _preemptivelyHarvestDeposited(owner); // Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates // the accrued weights so that the debt is properly calculated before the account is validated. _distributeUnlockedCreditDeposited(owner); uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares); // Update the owner's account, burn shares from the owner's account, and then decrease the value of the token // that the system is expected to hold. _poke(owner); _burnShares(owner, yieldToken, shares); _sync(yieldToken, amountYieldTokens, _usub); // Valid the owner's account to assure that the collateralization invariant is still held. _validate(owner); emit Withdraw(owner, yieldToken, shares, recipient); return amountYieldTokens; } /// @dev Mints debt tokens to `recipient` using the account owned by `owner`. /// /// @dev Emits a {Mint} event. /// /// @param owner The owner of the account to mint from. /// @param amount The amount to mint. /// @param recipient The recipient of the minted debt tokens. function _mint(address owner, uint256 amount, address recipient) internal { // Check that the system will allow for the specified amount to be minted. _checkMintingLimit(amount); // Preemptively harvest all tokens that the user has deposited into the system. This allows the debt to be // properly calculated before the account is validated. _preemptivelyHarvestDeposited(owner); // Distribute unlocked credit for all of the tokens that the user has deposited into the system. This updates // the accrued weights so that the debt is properly calculated before the account is validated. _distributeUnlockedCreditDeposited(owner); // Update the owner's account, increase their debt by the amount of tokens to mint, and then finally validate // their account to assure that the collateralization invariant is still held. _poke(owner); _updateDebt(owner, SafeCast.toInt256(amount)); _validate(owner); // Decrease the global amount of mintable debt tokens. _mintingLimiter.decrease(amount); // Mint the debt tokens to the recipient. TokenUtils.safeMint(debtToken, recipient, amount); emit Mint(owner, amount, recipient); } /// @dev Synchronizes the active balance and expected value of `yieldToken`. /// /// @param yieldToken The address of the yield token. /// @param amount The amount to add or subtract from the debt. /// @param operation The mathematical operation to perform for the update. Either one of {_uadd} or {_usub}. function _sync( address yieldToken, uint256 amount, function(uint256, uint256) internal pure returns (uint256) operation ) internal { YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken]; uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, amount); uint256 updatedActiveBalance = operation(yieldTokenParams.activeBalance, amount); uint256 updatedExpectedValue = operation(yieldTokenParams.expectedValue, amountUnderlyingTokens); _yieldTokens[yieldToken].activeBalance = updatedActiveBalance; _yieldTokens[yieldToken].expectedValue = updatedExpectedValue; } /// @dev Gets the amount of loss that `yieldToken` has incurred measured in basis points. When the expected /// underlying value is less than the actual value, this will return zero. /// /// @param yieldToken The address of the yield token. /// /// @return The loss in basis points. function _loss(address yieldToken) internal view returns (uint256) { YieldTokenParams memory yieldTokenParams = _yieldTokens[yieldToken]; uint256 amountUnderlyingTokens = _convertYieldTokensToUnderlying(yieldToken, yieldTokenParams.activeBalance); uint256 expectedUnderlyingValue = yieldTokenParams.expectedValue; return expectedUnderlyingValue > amountUnderlyingTokens ? ((expectedUnderlyingValue - amountUnderlyingTokens) * BPS) / expectedUnderlyingValue : 0; } /// @dev Distributes `amount` credit to all depositors of `yieldToken`. /// /// @param yieldToken The address of the yield token to distribute credit for. /// @param amount The amount of credit to distribute in debt tokens. function _distributeCredit(address yieldToken, uint256 amount) internal { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 pendingCredit = yieldTokenParams.pendingCredit; uint256 distributedCredit = yieldTokenParams.distributedCredit; uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken); uint256 lockedCredit = pendingCredit - (distributedCredit + unlockedCredit); // Distribute any unlocked credit before overriding it. if (unlockedCredit > 0) { yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares; } yieldTokenParams.pendingCredit = amount + lockedCredit; yieldTokenParams.distributedCredit = 0; yieldTokenParams.lastDistributionBlock = block.number; } /// @dev Distributes unlocked credit for all of the yield tokens that have been deposited into the account owned /// by `owner`. /// /// @param owner The address of the account owner. function _distributeUnlockedCreditDeposited(address owner) internal { Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens; for (uint256 i = 0; i < depositedTokens.values.length; i++) { _distributeUnlockedCredit(depositedTokens.values[i]); } } /// @dev Distributes unlocked credit of `yieldToken` to all depositors. /// /// @param yieldToken The address of the yield token to distribute unlocked credit for. function _distributeUnlockedCredit(address yieldToken) internal { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken); if (unlockedCredit == 0) { return; } yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares; yieldTokenParams.distributedCredit += unlockedCredit; } /// @dev Wraps `amount` of an underlying token into its `yieldToken`. /// /// @param yieldToken The address of the yield token to wrap the underlying tokens into. /// @param amount The amount of the underlying token to wrap. /// @param minimumAmountOut The minimum amount of yield tokens that are expected to be received from the operation. /// /// @return The amount of yield tokens that resulted from the operation. function _wrap( address yieldToken, uint256 amount, uint256 minimumAmountOut ) internal returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter); address underlyingToken = yieldTokenParams.underlyingToken; TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount); uint256 wrappedShares = adapter.wrap(amount, address(this)); if (wrappedShares < minimumAmountOut) { revert SlippageExceeded(wrappedShares, minimumAmountOut); } return wrappedShares; } /// @dev Unwraps `amount` of `yieldToken` into its underlying token. /// /// @param yieldToken The address of the yield token to unwrap. /// @param amount The amount of the underlying token to wrap. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be received from the /// operation. /// /// @return The amount of underlying tokens that resulted from the operation. function _unwrap( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) internal returns (uint256) { ITokenAdapter adapter = ITokenAdapter(_yieldTokens[yieldToken].adapter); uint256 amountUnwrapped = adapter.unwrap(amount, recipient); if (amountUnwrapped < minimumAmountOut) { revert SlippageExceeded(amountUnwrapped, minimumAmountOut); } return amountUnwrapped; } /// @dev Synchronizes the state for all of the tokens deposited in the account owned by `owner`. /// /// @param owner The address of the account owner. function _poke(address owner) internal { Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens; for (uint256 i = 0; i < depositedTokens.values.length; i++) { _poke(owner, depositedTokens.values[i]); } } /// @dev Synchronizes the state of `yieldToken` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param yieldToken The address of the yield token to synchronize the state for. function _poke(address owner, address yieldToken) internal { Account storage account = _accounts[owner]; uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight; uint256 lastAccruedWeight = account.lastAccruedWeights[yieldToken]; if (currentAccruedWeight == lastAccruedWeight) { return; } uint256 balance = account.balances[yieldToken]; uint256 unrealizedCredit = (currentAccruedWeight - lastAccruedWeight) * balance / FIXED_POINT_SCALAR; account.debt -= SafeCast.toInt256(unrealizedCredit); account.lastAccruedWeights[yieldToken] = currentAccruedWeight; } /// @dev Increases the debt by `amount` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param amount The amount to increase the debt by. function _updateDebt(address owner, int256 amount) internal { Account storage account = _accounts[owner]; account.debt += amount; } /// @dev Set the mint allowance for `spender` to `amount` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param spender The address of the spender. /// @param amount The amount of debt tokens to set the mint allowance to. function _approveMint(address owner, address spender, uint256 amount) internal { Account storage account = _accounts[owner]; account.mintAllowances[spender] = amount; emit ApproveMint(owner, spender, amount); } /// @dev Decrease the mint allowance for `spender` by `amount` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param spender The address of the spender. /// @param amount The amount of debt tokens to decrease the mint allowance by. function _decreaseMintAllowance(address owner, address spender, uint256 amount) internal { Account storage account = _accounts[owner]; account.mintAllowances[spender] -= amount; } /// @dev Set the withdraw allowance of `yieldToken` for `spender` to `shares` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param spender The address of the spender. /// @param yieldToken The address of the yield token to set the withdraw allowance for. /// @param shares The amount of shares to set the withdraw allowance to. function _approveWithdraw(address owner, address spender, address yieldToken, uint256 shares) internal { Account storage account = _accounts[owner]; account.withdrawAllowances[spender][yieldToken] = shares; emit ApproveWithdraw(owner, spender, yieldToken, shares); } /// @dev Decrease the withdraw allowance of `yieldToken` for `spender` by `amount` for the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param spender The address of the spender. /// @param yieldToken The address of the yield token to decrease the withdraw allowance for. /// @param amount The amount of shares to decrease the withdraw allowance by. function _decreaseWithdrawAllowance(address owner, address spender, address yieldToken, uint256 amount) internal { Account storage account = _accounts[owner]; account.withdrawAllowances[spender][yieldToken] -= amount; } /// @dev Checks that the account owned by `owner` is properly collateralized. /// /// @dev If the account is undercollateralized then this will revert with an {Undercollateralized} error. /// /// @param owner The address of the account owner. function _validate(address owner) internal view { int256 debt = _accounts[owner].debt; if (debt <= 0) { return; } uint256 collateralization = _totalValue(owner) * FIXED_POINT_SCALAR / uint256(debt); if (collateralization < minimumCollateralization) { revert Undercollateralized(); } } /// @dev Gets the total value of the deposit collateral measured in debt tokens of the account owned by `owner`. /// /// @param owner The address of the account owner. /// /// @return The total value. function _totalValue(address owner) internal view returns (uint256) { uint256 totalValue = 0; Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens; for (uint256 i = 0; i < depositedTokens.values.length; i++) { address yieldToken = depositedTokens.values[i]; address underlyingToken = _yieldTokens[yieldToken].underlyingToken; uint256 shares = _accounts[owner].balances[yieldToken]; uint256 amountUnderlyingTokens = _convertSharesToUnderlyingTokens(yieldToken, shares); totalValue += _normalizeUnderlyingTokensToDebt(underlyingToken, amountUnderlyingTokens); } return totalValue; } /// @dev Issues shares of `yieldToken` for `amount` of its underlying token to `recipient`. /// /// IMPORTANT: `amount` must never be 0. /// /// @param recipient The address of the recipient. /// @param yieldToken The address of the yield token. /// @param amount The amount of the underlying token. /// /// @return The amount of shares issued to `recipient`. function _issueSharesForAmount( address recipient, address yieldToken, uint256 amount ) internal returns (uint256) { uint256 shares = _convertYieldTokensToShares(yieldToken, amount); if (_accounts[recipient].balances[yieldToken] == 0) { _accounts[recipient].depositedTokens.add(yieldToken); } _accounts[recipient].balances[yieldToken] += shares; _yieldTokens[yieldToken].totalShares += shares; return shares; } /// @dev Burns `share` shares of `yieldToken` from the account owned by `owner`. /// /// @param owner The address of the owner. /// @param yieldToken The address of the yield token. /// @param shares The amount of shares to burn. function _burnShares(address owner, address yieldToken, uint256 shares) internal { Account storage account = _accounts[owner]; account.balances[yieldToken] -= shares; _yieldTokens[yieldToken].totalShares -= shares; if (account.balances[yieldToken] == 0) { account.depositedTokens.remove(yieldToken); } } /// @dev Gets the amount of debt that the account owned by `owner` will have after an update occurs. /// /// @param owner The address of the account owner. /// /// @return The amount of debt that the account owned by `owner` will have after an update. function _calculateUnrealizedDebt(address owner) internal view returns (int256) { int256 debt = _accounts[owner].debt; Sets.AddressSet storage depositedTokens = _accounts[owner].depositedTokens; for (uint256 i = 0; i < depositedTokens.values.length; i++) { address yieldToken = depositedTokens.values[i]; uint256 currentAccruedWeight = _yieldTokens[yieldToken].accruedWeight; uint256 lastAccruedWeight = _accounts[owner].lastAccruedWeights[yieldToken]; uint256 unlockedCredit = _calculateUnlockedCredit(yieldToken); currentAccruedWeight += unlockedCredit > 0 ? unlockedCredit * FIXED_POINT_SCALAR / _yieldTokens[yieldToken].totalShares : 0; if (currentAccruedWeight == lastAccruedWeight) { continue; } uint256 balance = _accounts[owner].balances[yieldToken]; uint256 unrealizedCredit = ((currentAccruedWeight - lastAccruedWeight) * balance) / FIXED_POINT_SCALAR; debt -= SafeCast.toInt256(unrealizedCredit); } return debt; } /// @dev Gets the virtual active balance of `yieldToken`. /// /// @dev The virtual active balance is the active balance minus any harvestable tokens which have yet to be realized. /// /// @param yieldToken The address of the yield token to get the virtual active balance of. /// /// @return The virtual active balance. function _calculateUnrealizedActiveBalance(address yieldToken) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 activeBalance = yieldTokenParams.activeBalance; if (activeBalance == 0) { return activeBalance; } uint256 currentValue = _convertYieldTokensToUnderlying(yieldToken, activeBalance); uint256 expectedValue = yieldTokenParams.expectedValue; if (currentValue <= expectedValue) { return activeBalance; } uint256 harvestable = _convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue); if (harvestable == 0) { return activeBalance; } return activeBalance - harvestable; } /// @dev Calculates the amount of unlocked credit for `yieldToken` that is available for distribution. /// /// @param yieldToken The address of the yield token. /// /// @return The amount of unlocked credit available. function _calculateUnlockedCredit(address yieldToken) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; uint256 pendingCredit = yieldTokenParams.pendingCredit; if (pendingCredit == 0) { return 0; } uint256 creditUnlockRate = yieldTokenParams.creditUnlockRate; uint256 distributedCredit = yieldTokenParams.distributedCredit; uint256 lastDistributionBlock = yieldTokenParams.lastDistributionBlock; uint256 percentUnlocked = (block.number - lastDistributionBlock) * creditUnlockRate; return percentUnlocked < FIXED_POINT_SCALAR ? (pendingCredit * percentUnlocked / FIXED_POINT_SCALAR) - distributedCredit : pendingCredit - distributedCredit; } /// @dev Gets the amount of shares that `amount` of `yieldToken` is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param amount The amount of yield tokens. /// /// @return The number of shares. function _convertYieldTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) { if (_yieldTokens[yieldToken].totalShares == 0) { return amount; } return amount * _yieldTokens[yieldToken].totalShares / _calculateUnrealizedActiveBalance(yieldToken); } /// @dev Gets the amount of yield tokens that `shares` shares of `yieldToken` is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param shares The amount of shares. /// /// @return The amount of yield tokens. function _convertSharesToYieldTokens(address yieldToken, uint256 shares) internal view returns (uint256) { uint256 totalShares = _yieldTokens[yieldToken].totalShares; if (totalShares == 0) { return shares; } return (shares * _calculateUnrealizedActiveBalance(yieldToken)) / totalShares; } /// @dev Gets the amount of underlying tokens that `shares` shares of `yieldToken` is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param shares The amount of shares. /// /// @return The amount of underlying tokens. function _convertSharesToUnderlyingTokens(address yieldToken, uint256 shares) internal view returns (uint256) { uint256 amountYieldTokens = _convertSharesToYieldTokens(yieldToken, shares); return _convertYieldTokensToUnderlying(yieldToken, amountYieldTokens); } /// @dev Gets the amount of an underlying token that `amount` of `yieldToken` is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param amount The amount of yield tokens. /// /// @return The amount of underlying tokens. function _convertYieldTokensToUnderlying(address yieldToken, uint256 amount) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter); return amount * adapter.price() / 10**yieldTokenParams.decimals; } /// @dev Gets the amount of `yieldToken` that `amount` of its underlying token is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param amount The amount of underlying tokens. /// /// @return The amount of yield tokens. function _convertUnderlyingTokensToYield(address yieldToken, uint256 amount) internal view returns (uint256) { YieldTokenParams storage yieldTokenParams = _yieldTokens[yieldToken]; ITokenAdapter adapter = ITokenAdapter(yieldTokenParams.adapter); return amount * 10**yieldTokenParams.decimals / adapter.price(); } /// @dev Gets the amount of shares of `yieldToken` that `amount` of its underlying token is exchangeable for. /// /// @param yieldToken The address of the yield token. /// @param amount The amount of underlying tokens. /// /// @return The amount of shares. function _convertUnderlyingTokensToShares(address yieldToken, uint256 amount) internal view returns (uint256) { uint256 amountYieldTokens = _convertUnderlyingTokensToYield(yieldToken, amount); return _convertYieldTokensToShares(yieldToken, amountYieldTokens); } /// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeUnderlyingTokensToDebt(address underlyingToken, uint256 amount) internal view returns (uint256) { return amount * _underlyingTokens[underlyingToken].conversionFactor; } /// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`. /// /// @dev This operation will result in truncation of some of the least significant digits of `amount`. This /// truncation amount will be the least significant N digits where N is the difference in decimals between /// the debt token and the underlying token. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of the debt token. /// /// @return The normalized amount. function _normalizeDebtTokensToUnderlying(address underlyingToken, uint256 amount) internal view returns (uint256) { return amount / _underlyingTokens[underlyingToken].conversionFactor; } /// @dev Checks the whitelist for msg.sender. /// /// Reverts if msg.sender is not in the whitelist. function _onlyWhitelisted() internal view { // Check if the message sender is an EOA. In the future, this potentially may break. It is important that functions // which rely on the whitelist not be explicitly vulnerable in the situation where this no longer holds true. if (tx.origin == msg.sender) { return; } // Only check the whitelist for calls from contracts. if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) { revert Unauthorized(); } } /// @dev Checks an expression and reverts with an {IllegalArgument} error if the expression is {false}. /// /// @param expression The expression to check. function _checkArgument(bool expression) internal pure { if (!expression) { revert IllegalArgument(); } } /// @dev Checks an expression and reverts with an {IllegalState} error if the expression is {false}. /// /// @param expression The expression to check. function _checkState(bool expression) internal pure { if (!expression) { revert IllegalState(); } } /// @dev Adds two unsigned 256 bit integers together and returns the result. /// /// @dev This operation is checked and will fail if the result overflows. /// /// @param x The first operand. /// @param y The second operand. /// /// @return z The result. function _uadd(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; } /// @dev Subtracts two unsigned 256 bit integers together and returns the result. /// /// @dev This operation is checked and will fail if the result overflows. /// /// @param x The first operand. /// @param y The second operand. /// /// @return z the result. function _usub(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x - y; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } pragma solidity ^0.8.11; /// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or /// `msg.origin` is not authorized. error Unauthorized(); /// @notice An error used to indicate that an action could not be completed because the contract either already existed /// or entered an illegal condition which is not recoverable from. error IllegalState(); /// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed /// to the function. error IllegalArgument(); // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.11; import "../interfaces/IMulticall.sol"; /// @title Multicall /// @author Uniswap Labs /// /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { revert MulticallFailed(data[i], result); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.11; /// @title Mutex /// @author Alchemix Finance /// /// @notice Provides a mutual exclusion lock for implementing contracts. abstract contract Mutex { /// @notice An error which is thrown when a lock is attempted to be claimed before it has been freed. error LockAlreadyClaimed(); /// @notice The lock state. Non-zero values indicate the lock has been claimed. uint256 private _lockState; /// @dev A modifier which acquires the mutex. modifier lock() { _claimLock(); _; _freeLock(); } /// @dev Gets if the mutex is locked. /// /// @return if the mutex is locked. function _isLocked() internal returns (bool) { return _lockState == 1; } /// @dev Claims the lock. If the lock is already claimed, then this will revert. function _claimLock() internal { // Check that the lock has not been claimed yet. if (_lockState != 0) { revert LockAlreadyClaimed(); } // Claim the lock. _lockState = 1; } /// @dev Frees the lock. function _freeLock() internal { _lockState = 0; } } pragma solidity >=0.5.0; import "./alchemist/IAlchemistV2Actions.sol"; import "./alchemist/IAlchemistV2AdminActions.sol"; import "./alchemist/IAlchemistV2Errors.sol"; import "./alchemist/IAlchemistV2Immutables.sol"; import "./alchemist/IAlchemistV2Events.sol"; import "./alchemist/IAlchemistV2State.sol"; /// @title IAlchemistV2 /// @author Alchemix Finance interface IAlchemistV2 is IAlchemistV2Actions, IAlchemistV2AdminActions, IAlchemistV2Errors, IAlchemistV2Immutables, IAlchemistV2Events, IAlchemistV2State { } pragma solidity >=0.5.0; /// @title IERC20Minimal /// @author Alchemix Finance interface IERC20Minimal { /// @notice An event which is emitted when tokens are transferred between two parties. /// /// @param owner The owner of the tokens from which the tokens were transferred. /// @param recipient The recipient of the tokens to which the tokens were transferred. /// @param amount The amount of tokens which were transferred. event Transfer(address indexed owner, address indexed recipient, uint256 amount); /// @notice An event which is emitted when an approval is made. /// /// @param owner The address which made the approval. /// @param spender The address which is allowed to transfer tokens on behalf of `owner`. /// @param amount The amount of tokens that `spender` is allowed to transfer. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice Gets the current total supply of tokens. /// /// @return The total supply. function totalSupply() external view returns (uint256); /// @notice Gets the balance of tokens that an account holds. /// /// @param account The account address. /// /// @return The balance of the account. function balanceOf(address account) external view returns (uint256); /// @notice Gets the allowance that an owner has allotted for a spender. /// /// @param owner The owner address. /// @param spender The spender address. /// /// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256); /// @notice Transfers `amount` tokens from `msg.sender` to `recipient`. /// /// @notice Emits a {Transfer} event. /// /// @param recipient The address which will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`. /// /// @notice Emits a {Approval} event. /// /// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`. /// @param amount The amount of tokens that `spender` is allowed to transfer. /// /// @return If the approval was successful. function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`. /// /// @notice Emits a {Approval} event. /// @notice Emits a {Transfer} event. /// /// @param owner The address to transfer tokens from. /// @param recipient The address that will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transferFrom(address owner, address recipient, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; /// @title IERC20TokenReceiver /// @author Alchemix Finance interface IERC20TokenReceiver { /// @notice Informs implementors of this interface that an ERC20 token has been transferred. /// /// @param token The token that was transferred. /// @param value The amount of the token that was transferred. function onERC20Received(address token, uint256 value) external; } pragma solidity >=0.5.0; /// @title ITokenAdapter /// @author Alchemix Finance interface ITokenAdapter { /// @notice Gets the current version. /// /// @return The version. function version() external view returns (string memory); /// @notice Gets the address of the yield token that this adapter supports. /// /// @return The address of the yield token. function token() external view returns (address); /// @notice Gets the address of the underlying token that the yield token wraps. /// /// @return The address of the underlying token. function underlyingToken() external view returns (address); /// @notice Gets the number of underlying tokens that a single whole yield token is redeemable for. /// /// @return The price. function price() external view returns (uint256); /// @notice Wraps `amount` underlying tokens into the yield token. /// /// @param amount The amount of the underlying token to wrap. /// @param recipient The address which will receive the yield tokens. /// /// @return amountYieldTokens The amount of yield tokens minted to `recipient`. function wrap(uint256 amount, address recipient) external returns (uint256 amountYieldTokens); /// @notice Unwraps `amount` yield tokens into the underlying token. /// /// @param amount The amount of yield-tokens to redeem. /// @param recipient The recipient of the resulting underlying-tokens. /// /// @return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`. function unwrap(uint256 amount, address recipient) external returns (uint256 amountUnderlyingTokens); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.5.0; import "./IERC20Burnable.sol"; import "./IERC20Minimal.sol"; import "./IERC20Mintable.sol"; /// @title IAlchemicToken /// @author Alchemix Finance interface IAlchemicToken is IERC20Minimal, IERC20Burnable, IERC20Mintable { /// @notice Gets the total amount of minted tokens for an account. /// /// @param account The address of the account. /// /// @return The total minted. function hasMinted(address account) external view returns (uint256); /// @notice Lowers the number of tokens which the `msg.sender` has minted. /// /// This reverts if the `msg.sender` is not whitelisted. /// /// @param amount The amount to lower the minted amount by. function lowerHasMinted(uint256 amount) external; } pragma solidity ^0.8.11; import "../base/Errors.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../libraries/Sets.sol"; /// @title Whitelist /// @author Alchemix Finance interface IWhitelist { /// @dev Emitted when a contract is added to the whitelist. /// /// @param account The account that was added to the whitelist. event AccountAdded(address account); /// @dev Emitted when a contract is removed from the whitelist. /// /// @param account The account that was removed from the whitelist. event AccountRemoved(address account); /// @dev Emitted when the whitelist is deactivated. event WhitelistDisabled(); /// @dev Returns the list of addresses that are whitelisted for the given contract address. /// /// @return addresses The addresses that are whitelisted to interact with the given contract. function getAddresses() external view returns (address[] memory addresses); /// @dev Returns the disabled status of a given whitelist. /// /// @return disabled A flag denoting if the given whitelist is disabled. function disabled() external view returns (bool); /// @dev Adds an contract to the whitelist. /// /// @param caller The address to add to the whitelist. function add(address caller) external; /// @dev Adds a contract to the whitelist. /// /// @param caller The address to remove from the whitelist. function remove(address caller) external; /// @dev Disables the whitelist of the target whitelisted contract. /// /// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled. function disable() external; /// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA. /// /// @param account The account to check. /// /// @return whitelisted A flag denoting if the given account is whitelisted. function isWhitelisted(address account) external view returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import {IllegalArgument} from "../base/Errors.sol"; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { if (y >= 2**255) { revert IllegalArgument(); } z = int256(y); } /// @notice Cast a int256 to a uint256, revert on underflow /// @param y The int256 to be casted /// @return z The casted integer, now type uint256 function toUint256(int256 y) internal pure returns (uint256 z) { if (y < 0) { revert IllegalArgument(); } z = uint256(y); } } pragma solidity ^0.8.11; /// @title Sets /// @author Alchemix Finance library Sets { using Sets for AddressSet; /// @notice A data structure holding an array of values with an index mapping for O(1) lookup. struct AddressSet { address[] values; mapping(address => uint256) indexes; } /// @dev Add a value to a Set /// /// @param self The Set. /// @param value The value to add. /// /// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set) function add(AddressSet storage self, address value) internal returns (bool) { if (self.contains(value)) { return false; } self.values.push(value); self.indexes[value] = self.values.length; return true; } /// @dev Remove a value from a Set /// /// @param self The Set. /// @param value The value to remove. /// /// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set) function remove(AddressSet storage self, address value) internal returns (bool) { uint256 index = self.indexes[value]; if (index == 0) { return false; } // Normalize the index since we know that the element is in the set. index--; uint256 lastIndex = self.values.length - 1; if (index != lastIndex) { address lastValue = self.values[lastIndex]; self.values[index] = lastValue; self.indexes[lastValue] = index + 1; } self.values.pop(); delete self.indexes[value]; return true; } /// @dev Returns true if the value exists in the Set /// /// @param self The Set. /// @param value The value to check. /// /// @return True if the value is contained in the Set, False if it is not. function contains(AddressSet storage self, address value) internal view returns (bool) { return self.indexes[value] != 0; } } pragma solidity ^0.8.11; import "../interfaces/IERC20Burnable.sol"; import "../interfaces/IERC20Metadata.sol"; import "../interfaces/IERC20Minimal.sol"; import "../interfaces/IERC20Mintable.sol"; /// @title TokenUtils /// @author Alchemix Finance library TokenUtils { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise, /// this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Gets the balance of tokens held by an account. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The token to check the balance of. /// @param account The address of the token holder. /// /// @return The balance of the tokens held by an account. function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint256)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Mints tokens to an address. /// /// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value. /// /// @param token The token to mint. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to mint. function safeMint(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens. /// /// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param amount The amount of tokens to burn. function safeBurn(address token, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burn.selector, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens from its total supply. /// /// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param owner The owner of the tokens. /// @param amount The amount of tokens to burn. function safeBurnFrom(address token, address owner, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } pragma solidity ^0.8.11; import {IllegalArgument} from "../base/Errors.sol"; /// @title Functions /// @author Alchemix Finance library Limiters { using Limiters for LinearGrowthLimiter; /// @dev A maximum cooldown to avoid malicious governance bricking the contract. /// @dev 1 day @ 12 sec / block uint256 constant public MAX_COOLDOWN_BLOCKS = 7200; /// @dev The scalar used to convert integral types to fixed point numbers. uint256 constant public FIXED_POINT_SCALAR = 1e18; /// @dev The configuration and state of a linear growth function (LGF). struct LinearGrowthLimiter { uint256 maximum; /// The maximum limit of the function. uint256 rate; /// The rate at which the function increases back to its maximum. uint256 lastValue; /// The most recently saved value of the function. uint256 lastBlock; /// The block that `lastValue` was recorded. uint256 minLimit; /// A minimum limit to avoid malicious governance bricking the contract } /// @dev Instantiates a new linear growth function. /// /// @param maximum The maximum value for the LGF. /// @param blocks The number of blocks that determins the rate of the LGF. /// /// @return The LGF struct. function createLinearGrowthLimiter(uint256 maximum, uint256 blocks, uint256 _minLimit) internal view returns (LinearGrowthLimiter memory) { if (blocks > MAX_COOLDOWN_BLOCKS) { revert IllegalArgument(); } if (maximum < _minLimit) { revert IllegalArgument(); } return LinearGrowthLimiter({ maximum: maximum, rate: maximum * FIXED_POINT_SCALAR / blocks, lastValue: maximum, lastBlock: block.number, minLimit: _minLimit }); } /// @dev Configure an LGF. /// /// @param self The LGF to configure. /// @param maximum The maximum value of the LFG. /// @param blocks The number of recovery blocks of the LGF. function configure(LinearGrowthLimiter storage self, uint256 maximum, uint256 blocks) internal { if (blocks > MAX_COOLDOWN_BLOCKS) { revert IllegalArgument(); } if (maximum < self.minLimit) { revert IllegalArgument(); } if (self.lastValue > maximum) { self.lastValue = maximum; } self.maximum = maximum; self.rate = maximum * FIXED_POINT_SCALAR / blocks; } /// @dev Updates the state of an LGF by updating `lastValue` and `lastBlock`. /// /// @param self the LGF to update. function update(LinearGrowthLimiter storage self) internal { self.lastValue = self.get(); self.lastBlock = block.number; } /// @dev Decrease the value of the linear growth limiter. /// /// @param self The linear growth limiter. /// @param amount The amount to decrease `lastValue`. function decrease(LinearGrowthLimiter storage self, uint256 amount) internal { uint256 value = self.get(); self.lastValue = value - amount; self.lastBlock = block.number; } /// @dev Get the current value of the linear growth limiter. /// /// @return The current value. function get(LinearGrowthLimiter storage self) internal view returns (uint256) { uint256 elapsed = block.number - self.lastBlock; if (elapsed == 0) { return self.lastValue; } uint256 delta = elapsed * self.rate / FIXED_POINT_SCALAR; uint256 value = self.lastValue + delta; return value > self.maximum ? self.maximum : value; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Multicall interface /// @author Uniswap Labs /// /// @notice Enables calling multiple methods in a single call to the contract. /// @dev The use of `msg.value` should be heavily scrutinized for implementors of this interfaces. interface IMulticall { /// @notice An error used to indicate that an individual call in a multicall failed. /// /// @param data The call data. /// @param result The result of the call. error MulticallFailed(bytes data, bytes result); /// @notice Call multiple functions in the implementing contract. /// /// @param data The encoded function data for each of the calls to make to this contract. /// /// @return results The results from each of the calls passed in via data. function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } pragma solidity >=0.5.0; /// @title IAlchemistV2Actions /// @author Alchemix Finance /// /// @notice Specifies user actions. interface IAlchemistV2Actions { /// @notice Approve `spender` to mint `amount` debt tokens. /// /// **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to mint. /// @param amount The amount of tokens that `spender` will be allowed to mint. function approveMint(address spender, uint256 amount) external; /// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @param spender The address that will be approved to withdraw. /// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw. /// @param shares The amount of shares that `spender` will be allowed to withdraw. function approveWithdraw( address spender, address yieldToken, uint256 shares ) external; /// @notice Synchronizes the state of the account owned by `owner`. /// /// @param owner The owner of the account to synchronize. function poke(address owner) external; /// @notice Deposit a yield token into a user's account. /// /// @notice An approval must be set for `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice IERC20(ydai).approve(alchemistAddress, amount); /// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender); /// @notice ``` /// /// @param yieldToken The yield-token to deposit. /// @param amount The amount of yield tokens to deposit. /// @param recipient The owner of the account that will receive the resulting shares. /// /// @return sharesIssued The number of shares issued to `recipient`. function deposit( address yieldToken, uint256 amount, address recipient ) external returns (uint256 sharesIssued); /// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`. /// /// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Deposit} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amount = 50000; /// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to wrap the underlying tokens into. /// @param amount The amount of the underlying token to deposit. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`. /// /// @return sharesIssued The number of shares issued to `recipient`. function depositUnderlying( address yieldToken, uint256 amount, address recipient, uint256 minimumAmountOut ) external returns (uint256 sharesIssued); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdraw( address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner` /// /// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai); /// @notice uint256 amtYieldTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`. function withdrawFrom( address owner, address yieldToken, uint256 shares, address recipient ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amountUnderlyingTokens = 5000; /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlying( address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for. /// /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// /// @notice Emits a {Withdraw} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai); /// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1); /// @notice ``` /// /// @param owner The address of the account owner to withdraw from. /// @param yieldToken The address of the yield token to withdraw. /// @param shares The number of shares to burn. /// @param recipient The address of the recipient. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. /// /// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`. function withdrawUnderlyingFrom( address owner, address yieldToken, uint256 shares, address recipient, uint256 minimumAmountOut ) external returns (uint256 amountWithdrawn); /// @notice Mint `amount` debt tokens. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mint(uint256 amount, address recipient) external; /// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// /// @notice Emits a {Mint} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtDebt = 5000; /// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender); /// @notice ``` /// /// @param owner The address of the owner of the account to mint from. /// @param amount The amount of tokens to mint. /// @param recipient The address of the recipient. function mintFrom( address owner, uint256 amount, address recipient ) external; /// @notice Burn `amount` debt tokens to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error. /// /// @notice Emits a {Burn} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice uint256 amtBurn = 5000; /// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender); /// @notice ``` /// /// @param amount The amount of tokens to burn. /// @param recipient The address of the recipient. /// /// @return amountBurned The amount of tokens that were burned. function burn(uint256 amount, address recipient) external returns (uint256 amountBurned); /// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`. /// /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error. /// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error. /// /// @notice Emits a {Repay} event. /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f; /// @notice uint256 amtRepay = 5000; /// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender); /// @notice ``` /// /// @param underlyingToken The address of the underlying token to repay. /// @param amount The amount of the underlying token to repay. /// @param recipient The address of the recipient which will receive credit. /// /// @return amountRepaid The amount of tokens that were repaid. function repay( address underlyingToken, uint256 amount, address recipient ) external returns (uint256 amountRepaid); /// @notice /// /// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds. /// /// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error. /// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error. /// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error. /// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error. /// /// @notice Emits a {Liquidate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals(); /// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to liquidate. /// @param shares The number of shares to burn for credit. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated. /// /// @return sharesLiquidated The amount of shares that were liquidated. function liquidate( address yieldToken, uint256 shares, uint256 minimumAmountOut ) external returns (uint256 sharesLiquidated); /// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`. /// /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {Donate} event. /// /// @notice **_NOTE:_** This function is WHITELISTED. /// /// @notice **Example:** /// @notice ``` /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95; /// @notice uint256 amtSharesLiquidate = 5000; /// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1); /// @notice ``` /// /// @param yieldToken The address of the yield token to credit accounts for. /// @param amount The amount of debt tokens to burn. function donate(address yieldToken, uint256 amount) external; /// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders. /// /// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error. /// /// @notice Emits a {Harvest} event. /// /// @param yieldToken The address of the yield token to harvest. /// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`. function harvest(address yieldToken, uint256 minimumAmountOut) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2AdminActions /// @author Alchemix Finance /// /// @notice Specifies admin and or sentinel actions. interface IAlchemistV2AdminActions { /// @notice Contract initialization parameters. struct InitializationParams { // The initial admin account. address admin; // The ERC20 token used to represent debt. address debtToken; // The initial transmuter or transmuter buffer. address transmuter; // The minimum collateralization ratio that an account must maintain. uint256 minimumCollateralization; // The percentage fee taken from each harvest measured in units of basis points. uint256 protocolFee; // The address that receives protocol fees. address protocolFeeReceiver; // A limit used to prevent administrators from making minting functionality inoperable. uint256 mintingLimitMinimum; // The maximum number of tokens that can be minted per period of time. uint256 mintingLimitMaximum; // The number of blocks that it takes for the minting limit to be refreshed. uint256 mintingLimitBlocks; // The address of the whitelist. address whitelist; } /// @notice Configuration parameters for an underlying token. struct UnderlyingTokenConfig { // A limit used to prevent administrators from making repayment functionality inoperable. uint256 repayLimitMinimum; // The maximum number of underlying tokens that can be repaid per period of time. uint256 repayLimitMaximum; // The number of blocks that it takes for the repayment limit to be refreshed. uint256 repayLimitBlocks; // A limit used to prevent administrators from making liquidation functionality inoperable. uint256 liquidationLimitMinimum; // The maximum number of underlying tokens that can be liquidated per period of time. uint256 liquidationLimitMaximum; // The number of blocks that it takes for the liquidation limit to be refreshed. uint256 liquidationLimitBlocks; } /// @notice Configuration parameters of a yield token. struct YieldTokenConfig { // The adapter used by the system to interop with the token. address adapter; // The maximum percent loss in expected value that can occur before certain actions are disabled measured in // units of basis points. uint256 maximumLoss; // The maximum value that can be held by the system before certain actions are disabled measured in the // underlying token. uint256 maximumExpectedValue; // The number of blocks that credit will be distributed over to depositors. uint256 creditUnlockBlocks; } /// @notice Initialize the contract. /// /// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error. /// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library. /// /// @notice Emits an {AdminUpdated} event. /// @notice Emits a {TransmuterUpdated} event. /// @notice Emits a {MinimumCollateralizationUpdated} event. /// @notice Emits a {ProtocolFeeUpdated} event. /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// @notice Emits a {MintingLimitUpdated} event. /// /// @param params The contract initialization parameters. function initialize(InitializationParams memory params) external; /// @notice Sets the pending administrator. /// /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error. /// /// @notice Emits a {PendingAdminUpdated} event. /// /// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process. /// /// @param value the address to set the pending admin to. function setPendingAdmin(address value) external; /// @notice Allows for `msg.sender` to accepts the role of administrator. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error. /// /// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set. /// /// @notice Emits a {AdminUpdated} event. /// @notice Emits a {PendingAdminUpdated} event. function acceptAdmin() external; /// @notice Sets an address as a sentinel. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param sentinel The address to set or unset as a sentinel. /// @param flag A flag indicating of the address should be set or unset as a sentinel. function setSentinel(address sentinel, bool flag) external; /// @notice Sets an address as a keeper. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param keeper The address to set or unset as a keeper. /// @param flag A flag indicating of the address should be set or unset as a keeper. function setKeeper(address keeper, bool flag) external; /// @notice Adds an underlying token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @param underlyingToken The address of the underlying token to add. /// @param config The initial underlying token configuration. function addUnderlyingToken( address underlyingToken, UnderlyingTokenConfig calldata config ) external; /// @notice Adds a yield token to the system. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {AddYieldToken} event. /// @notice Emits a {TokenAdapterUpdated} event. /// @notice Emits a {MaximumLossUpdated} event. /// /// @param yieldToken The address of the yield token to add. /// @param config The initial yield token configuration. function addYieldToken(address yieldToken, YieldTokenConfig calldata config) external; /// @notice Sets an underlying token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits an {UnderlyingTokenEnabled} event. /// /// @param underlyingToken The address of the underlying token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setUnderlyingTokenEnabled(address underlyingToken, bool enabled) external; /// @notice Sets a yield token as either enabled or disabled. /// /// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {YieldTokenEnabled} event. /// /// @param yieldToken The address of the yield token to enable or disable. /// @param enabled If the underlying token should be enabled or disabled. function setYieldTokenEnabled(address yieldToken, bool enabled) external; /// @notice Configures the the repay limit of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {ReplayLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the repay limit of. /// @param maximum The maximum repay limit. /// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. function configureRepayLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Configure the liquidation limiter of `underlyingToken`. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @notice Emits a {LiquidationLimitUpdated} event. /// /// @param underlyingToken The address of the underlying token to configure the liquidation limit of. /// @param maximum The maximum liquidation limit. /// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. function configureLiquidationLimit( address underlyingToken, uint256 maximum, uint256 blocks ) external; /// @notice Set the address of the transmuter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {TransmuterUpdated} event. /// /// @param value The address of the transmuter. function setTransmuter(address value) external; /// @notice Set the minimum collateralization ratio. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MinimumCollateralizationUpdated} event. /// /// @param value The new minimum collateralization ratio. function setMinimumCollateralization(uint256 value) external; /// @notice Sets the fee that the protocol will take from harvests. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be in range or this call will with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeUpdated} event. /// /// @param value The value to set the protocol fee to measured in basis points. function setProtocolFee(uint256 value) external; /// @notice Sets the address which will receive protocol fees. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error. /// /// @notice Emits a {ProtocolFeeReceiverUpdated} event. /// /// @param value The address to set the protocol fee receiver to. function setProtocolFeeReceiver(address value) external; /// @notice Configures the minting limiter. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// /// @notice Emits a {MintingLimitUpdated} event. /// /// @param maximum The maximum minting limit. /// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. function configureMintingLimit(uint256 maximum, uint256 blocks) external; /// @notice Sets the rate at which credit will be completely available to depositors after it is harvested. /// /// @notice Emits a {CreditUnlockRateUpdated} event. /// /// @param yieldToken The address of the yield token to set the credit unlock rate for. /// @param blocks The number of blocks that it will take before the credit will be unlocked. function configureCreditUnlockRate(address yieldToken, uint256 blocks) external; /// @notice Sets the token adapter of a yield token. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error. /// /// @notice Emits a {TokenAdapterUpdated} event. /// /// @param yieldToken The address of the yield token to set the adapter for. /// @param adapter The address to set the token adapter to. function setTokenAdapter(address yieldToken, address adapter) external; /// @notice Sets the maximum expected value of a yield token that the system can hold. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @param yieldToken The address of the yield token to set the maximum expected value for. /// @param value The maximum expected value of the yield token denoted measured in its underlying token. function setMaximumExpectedValue(address yieldToken, uint256 value) external; /// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit. /// /// @param yieldToken The address of the yield bearing token to set the maximum loss for. /// @param value The value to set the maximum loss to. This is in units of basis points. function setMaximumLoss(address yieldToken, uint256 value) external; /// @notice Snap the expected value `yieldToken` to the current value. /// /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error. /// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error. /// /// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal. /// /// @param yieldToken The address of the yield token to snap. function snap(address yieldToken) external; } pragma solidity >=0.5.0; /// @title IAlchemistV2Errors /// @author Alchemix Finance /// /// @notice Specifies errors. interface IAlchemistV2Errors { /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize. /// /// @param token The address of the token. error UnsupportedToken(address token); /// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled. /// /// @param token The address of the token. error TokenDisabled(address token); /// @notice An error which is used to indicate that an operation failed because an account became undercollateralized. error Undercollateralized(); /// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The expected value measured in units of the underlying token. /// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token. error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue); /// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted. /// /// @param yieldToken The address of the yield token. /// @param loss The amount of loss measured in basis points. /// @param maximumLoss The maximum amount of loss permitted measured in basis points. error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss); /// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded. /// /// @param amount The amount of debt tokens that were requested to be minted. /// @param available The amount of debt tokens which are available to mint. error MintingLimitExceeded(uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be repaid. /// @param available The amount of underlying tokens that are available to be repaid. error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded. /// /// @param underlyingToken The address of the underlying token. /// @param amount The amount of underlying tokens that were requested to be liquidated. /// @param available The amount of underlying tokens that are available to be liquidated. error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available); /// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded. /// /// @param amount The amount of underlying or yield tokens returned by the operation. /// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing /// the operation. error SlippageExceeded(uint256 amount, uint256 minimumAmountOut); } pragma solidity >=0.5.0; /// @title IAlchemistV2Immutables /// @author Alchemix Finance interface IAlchemistV2Immutables { /// @notice Returns the version of the alchemist. /// /// @return The version. function version() external view returns (string memory); /// @notice Returns the address of the debt token used by the system. /// /// @return The address of the debt token. function debtToken() external view returns (address); } pragma solidity >=0.5.0; /// @title IAlchemistV2Events /// @author Alchemix Finance interface IAlchemistV2Events { /// @notice Emitted when the pending admin is updated. /// /// @param pendingAdmin The address of the pending admin. event PendingAdminUpdated(address pendingAdmin); /// @notice Emitted when the administrator is updated. /// /// @param admin The address of the administrator. event AdminUpdated(address admin); /// @notice Emitted when an address is set or unset as a sentinel. /// /// @param sentinel The address of the sentinel. /// @param flag A flag indicating if `sentinel` was set or unset as a sentinel. event SentinelSet(address sentinel, bool flag); /// @notice Emitted when an address is set or unset as a keeper. /// /// @param sentinel The address of the keeper. /// @param flag A flag indicating if `keeper` was set or unset as a sentinel. event KeeperSet(address sentinel, bool flag); /// @notice Emitted when an underlying token is added. /// /// @param underlyingToken The address of the underlying token that was added. event AddUnderlyingToken(address indexed underlyingToken); /// @notice Emitted when a yield token is added. /// /// @param yieldToken The address of the yield token that was added. event AddYieldToken(address indexed yieldToken); /// @notice Emitted when an underlying token is enabled or disabled. /// /// @param underlyingToken The address of the underlying token that was enabled or disabled. /// @param enabled A flag indicating if the underlying token was enabled or disabled. event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled); /// @notice Emitted when an yield token is enabled or disabled. /// /// @param yieldToken The address of the yield token that was enabled or disabled. /// @param enabled A flag indicating if the yield token was enabled or disabled. event YieldTokenEnabled(address indexed yieldToken, bool enabled); /// @notice Emitted when the repay limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum repay limit. /// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted. event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the liquidation limit of an underlying token is updated. /// /// @param underlyingToken The address of the underlying token. /// @param maximum The updated maximum liquidation limit. /// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted. event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks); /// @notice Emitted when the transmuter is updated. /// /// @param transmuter The updated address of the transmuter. event TransmuterUpdated(address transmuter); /// @notice Emitted when the minimum collateralization is updated. /// /// @param minimumCollateralization The updated minimum collateralization. event MinimumCollateralizationUpdated(uint256 minimumCollateralization); /// @notice Emitted when the protocol fee is updated. /// /// @param protocolFee The updated protocol fee. event ProtocolFeeUpdated(uint256 protocolFee); /// @notice Emitted when the protocol fee receiver is updated. /// /// @param protocolFeeReceiver The updated address of the protocol fee receiver. event ProtocolFeeReceiverUpdated(address protocolFeeReceiver); /// @notice Emitted when the minting limit is updated. /// /// @param maximum The updated maximum minting limit. /// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted. event MintingLimitUpdated(uint256 maximum, uint256 blocks); /// @notice Emitted when the credit unlock rate is updated. /// /// @param yieldToken The address of the yield token. /// @param blocks The number of blocks that distributed credit will unlock over. event CreditUnlockRateUpdated(address yieldToken, uint256 blocks); /// @notice Emitted when the adapter of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param tokenAdapter The updated address of the token adapter. event TokenAdapterUpdated(address yieldToken, address tokenAdapter); /// @notice Emitted when the maximum expected value of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumExpectedValue The updated maximum expected value. event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue); /// @notice Emitted when the maximum loss of a yield token is updated. /// /// @param yieldToken The address of the yield token. /// @param maximumLoss The updated maximum loss. event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss); /// @notice Emitted when the expected value of a yield token is snapped to its current value. /// /// @param yieldToken The address of the yield token. /// @param expectedValue The updated expected value measured in the yield token's underlying token. event Snap(address indexed yieldToken, uint256 expectedValue); /// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param amount The amount of debt tokens that `spender` is allowed to mint. event ApproveMint(address indexed owner, address indexed spender, uint256 amount); /// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account. /// /// @param owner The address of the account owner. /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`. /// @param yieldToken The address of the yield token that `spender` is allowed to withdraw. /// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw. event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount); /// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`. /// /// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the /// underlying tokens were wrapped. /// /// @param sender The address of the user which deposited funds. /// @param yieldToken The address of the yield token that was deposited. /// @param amount The amount of yield tokens that were deposited. /// @param recipient The address that received the deposited funds. event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient); /// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned /// by `owner` to `recipient`. /// /// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens /// were unwrapped. /// /// @param owner The address of the account owner. /// @param yieldToken The address of the yield token that was withdrawn. /// @param shares The amount of shares that were burned. /// @param recipient The address that received the withdrawn funds. event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient); /// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`. /// /// @param owner The address of the account owner. /// @param amount The amount of tokens that were minted. /// @param recipient The recipient of the minted tokens. event Mint(address indexed owner, uint256 amount, address recipient); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`. /// /// @param sender The address which is burning tokens. /// @param amount The amount of tokens that were burned. /// @param recipient The address that received credit for the burned tokens. event Burn(address indexed sender, uint256 amount, address recipient); /// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`. /// /// @param sender The address which is repaying tokens. /// @param underlyingToken The address of the underlying token that was used to repay debt. /// @param amount The amount of the underlying token that was used to repay debt. /// @param recipient The address that received credit for the repaid tokens. event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient); /// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`. /// /// @param owner The address of the account owner liquidating shares. /// @param yieldToken The address of the yield token. /// @param underlyingToken The address of the underlying token. /// @param shares The amount of the shares of `yieldToken` that were liquidated. event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares); /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`. /// /// @param sender The address which burned debt tokens. /// @param yieldToken The address of the yield token. /// @param amount The amount of debt tokens which were burned. event Donate(address indexed sender, address indexed yieldToken, uint256 amount); /// @notice Emitted when `yieldToken` is harvested. /// /// @param yieldToken The address of the yield token that was harvested. /// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points. /// @param totalHarvested The total amount of underlying tokens harvested. event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested); } pragma solidity >=0.5.0; /// @title IAlchemistV2State /// @author Alchemix Finance interface IAlchemistV2State { /// @notice Defines underlying token parameters. struct UnderlyingTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // A coefficient used to normalize the token to a value comparable to the debt token. For example, if the // underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be // 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token. uint256 conversionFactor; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Defines yield token parameters. struct YieldTokenParams { // The number of decimals the token has. This value is cached once upon registering the token so it is important // that the decimals of the token are immutable or the system will begin to have computation errors. uint8 decimals; // The associated underlying token that can be redeemed for the yield-token. address underlyingToken; // The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its // underlying token. address adapter; // The maximum percentage loss that is acceptable before disabling certain actions. uint256 maximumLoss; // The maximum value of yield tokens that the system can hold, measured in units of the underlying token. uint256 maximumExpectedValue; // The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal // fixed point integer. uint256 creditUnlockRate; // The current balance of yield tokens which are held by users. uint256 activeBalance; // The current balance of yield tokens which are earmarked to be harvested by the system at a later time. uint256 harvestableBalance; // The total number of shares that have been minted for this token. uint256 totalShares; // The expected value of the tokens measured in underlying tokens. This value controls how much of the token // can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens // are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected // value by how much the tokens are exchangeable for in the underlying token. uint256 expectedValue; // The current amount of credit which is will be distributed over time to depositors. uint256 pendingCredit; // The amount of the pending credit that has been distributed. uint256 distributedCredit; // The block number which the last credit distribution occurred. uint256 lastDistributionBlock; // The total accrued weight. This is used to calculate how much credit a user has been granted over time. The // representation of this value is a 18 decimal fixed point integer. uint256 accruedWeight; // A flag to indicate if the token is enabled. bool enabled; } /// @notice Gets the address of the admin. /// /// @return admin The admin address. function admin() external view returns (address admin); /// @notice Gets the address of the pending administrator. /// /// @return pendingAdmin The pending administrator address. function pendingAdmin() external view returns (address pendingAdmin); /// @notice Gets if an address is a sentinel. /// /// @param sentinel The address to check. /// /// @return isSentinel If the address is a sentinel. function sentinels(address sentinel) external view returns (bool isSentinel); /// @notice Gets if an address is a keeper. /// /// @param keeper The address to check. /// /// @return isKeeper If the address is a keeper function keepers(address keeper) external view returns (bool isKeeper); /// @notice Gets the address of the transmuter. /// /// @return transmuter The transmuter address. function transmuter() external view returns (address transmuter); /// @notice Gets the minimum collateralization. /// /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt. /// /// @dev The value returned is a 18 decimal fixed point integer. /// /// @return minimumCollateralization The minimum collateralization. function minimumCollateralization() external view returns (uint256 minimumCollateralization); /// @notice Gets the protocol fee. /// /// @return protocolFee The protocol fee. function protocolFee() external view returns (uint256 protocolFee); /// @notice Gets the protocol fee receiver. /// /// @return protocolFeeReceiver The protocol fee receiver. function protocolFeeReceiver() external view returns (address protocolFeeReceiver); /// @notice Gets the address of the whitelist contract. /// /// @return whitelist The address of the whitelist contract. function whitelist() external view returns (address whitelist); /// @notice Gets the conversion rate of underlying tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of underlying tokens per share. function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the conversion rate of yield tokens per share. /// /// @param yieldToken The address of the yield token to get the conversion rate for. /// /// @return rate The rate of yield tokens per share. function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate); /// @notice Gets the supported underlying tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported underlying tokens. function getSupportedUnderlyingTokens() external view returns (address[] memory tokens); /// @notice Gets the supported yield tokens. /// /// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls. /// /// @return tokens The supported yield tokens. function getSupportedYieldTokens() external view returns (address[] memory tokens); /// @notice Gets if an underlying token is supported. /// /// @param underlyingToken The address of the underlying token to check. /// /// @return isSupported If the underlying token is supported. function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported); /// @notice Gets if a yield token is supported. /// /// @param yieldToken The address of the yield token to check. /// /// @return isSupported If the yield token is supported. function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported); /// @notice Gets information about the account owned by `owner`. /// /// @param owner The address that owns the account. /// /// @return debt The unrealized amount of debt that the account had incurred. /// @return depositedTokens The yield tokens that the owner has deposited. function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens); /// @notice Gets information about a yield token position for the account owned by `owner`. /// /// @param owner The address that owns the account. /// @param yieldToken The address of the yield token to get the position of. /// /// @return shares The amount of shares of that `owner` owns of the yield token. /// @return lastAccruedWeight The last recorded accrued weight of the yield token. function positions(address owner, address yieldToken) external view returns ( uint256 shares, uint256 lastAccruedWeight ); /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to mint on behalf of `owner`. /// /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`. function mintAllowance(address owner, address spender) external view returns (uint256 allowance); /// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`. /// /// @param owner The owner of the account. /// @param spender The address which is allowed to withdraw on behalf of `owner`. /// @param yieldToken The address of the yield token. /// /// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`. function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance); /// @notice Gets the parameters of an underlying token. /// /// @param underlyingToken The address of the underlying token. /// /// @return params The underlying token parameters. function getUnderlyingTokenParameters(address underlyingToken) external view returns (UnderlyingTokenParams memory params); /// @notice Get the parameters and state of a yield-token. /// /// @param yieldToken The address of the yield token. /// /// @return params The yield token parameters. function getYieldTokenParameters(address yieldToken) external view returns (YieldTokenParams memory params); /// @notice Gets current limit, maximum, and rate of the minting limiter. /// /// @return currentLimit The current amount of debt tokens that can be minted. /// @return rate The maximum possible amount of tokens that can be liquidated at a time. /// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time. function getMintLimitInfo() external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be repaid. /// @return rate The rate at which the the current limit increases back to its maximum in tokens per block. /// @return maximum The maximum possible amount of tokens that can be repaid at a time. function getRepayLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); /// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`. /// /// @param underlyingToken The address of the underlying token. /// /// @return currentLimit The current amount of underlying tokens that can be liquidated. /// @return rate The rate at which the function increases back to its maximum limit (tokens / block). /// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time. function getLiquidationLimitInfo(address underlyingToken) external view returns ( uint256 currentLimit, uint256 rate, uint256 maximum ); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Burnable /// @author Alchemix Finance interface IERC20Burnable is IERC20Minimal { /// @notice Burns `amount` tokens from the balance of `msg.sender`. /// /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burn(uint256 amount) external returns (bool); /// @notice Burns `amount` tokens from `owner`'s balance. /// /// @param owner The address to burn tokens from. /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burnFrom(address owner, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Mintable /// @author Alchemix Finance interface IERC20Mintable is IERC20Minimal { /// @notice Mints `amount` tokens to `recipient`. /// /// @param recipient The address which will receive the minted tokens. /// @param amount The amount of tokens to mint. /// /// @return If minting the tokens was successful. function mint(address recipient, uint256 amount) external 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/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; } } pragma solidity >=0.5.0; /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); }
@inheritdoc IAlchemistV2State
function getUnderlyingTokenParameters(address underlyingToken) external view override returns (UnderlyingTokenParams memory) { return _underlyingTokens[underlyingToken]; }
504,733
./partial_match/1/0xf3C1eb45094dEc54A9e5A3eF0afc128dd0dEC6E5/sources/PleaseDebunk.sol
Solidity only automatically asserts when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn't hold
function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; }
3,701,340
pragma solidity ^0.4.13; 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 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 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 DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(s)); } } contract WETH9_ { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } 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); } 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; } } 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); } 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); } } 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 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/QmSCdmLL8BV4f9RSFjpsqZ3JTAdqgdwoQkfTYxNtG1uTNt // IPFS hash can be encoded and decoded using http://lenschulwitz.com/base58 string public constant ORIGINAL_IPFS_HASH = "QmSCdmLL8BV4f9RSFjpsqZ3JTAdqgdwoQkfTYxNtG1uTNt"; bytes public constant TERMS_AND_CONDITIONS = hex"1220396108900B284DDF2F10C83838E87BB7808A96996072521254D24EAABE7F6F5D"; 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) { bool isRegistered = registrantToRegistrantIds[x].exists; require(isRegistered); 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 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; } } 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) { 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) { uint tailNodeId = stakeNodes[0].prev; 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() 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 l = counter; l > k; l--) { out[l] = out[l - 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 = 0xD35EBA0B0FF284A240D50F43381D8A1E00F19FBFDBF5162224335251A7D6D154; // 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]; } }
Proofs that terms and conditions have been read and understood byManager Address of the fund manager, as used in the ipfs-frontend v ellipitc curve parameter v r ellipitc curve parameter r s ellipitc curve parameter s return Whether or not terms and conditions have been read and understood 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-APIweb3ethsign
function termsAndConditionsAreSigned(address byManager, uint8 v, bytes32 r, bytes32 s) view returns (bool) { return ecrecover( keccak256("\x19Ethereum Signed Message:\n34", TERMS_AND_CONDITIONS), v, r, s }
438,929
pragma solidity ^0.4.18; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; return true; } } contract BatCave is Pausable { // total eggs one bat can produce per day uint256 public EGGS_TO_HATCH_1BAT = 86400; // how much bat for newbie user uint256 public STARTING_BAT = 300; uint256 PSN = 10000; uint256 PSNH = 5000; address public batman; address public superman; address public aquaman; mapping(address => uint256) public hatcheryBat; mapping(address => uint256) public claimedEggs; mapping(address => uint256) public lastHatch; mapping(address => address) public referrals; mapping (address => uint256) realRef; // total eggs in market uint256 public marketEggs; function BatCave() public{ paused = false; } modifier onlyDCFamily() { require(batman!=address(0) && superman!=address(0) && aquaman!=address(0)); require(msg.sender == owner || msg.sender == batman || msg.sender == superman || msg.sender == aquaman); _; } function setBatman(address _bat) public onlyOwner{ require(_bat!=address(0)); batman = _bat; } function setSuperman(address _bat) public onlyOwner{ require(_bat!=address(0)); superman = _bat; } function setAquaman(address _bat) public onlyOwner{ require(_bat!=address(0)); aquaman = _bat; } function setRealRef(address _ref,uint256 _isReal) public onlyOwner{ require(_ref!=address(0)); require(_isReal==0 || _isReal==1); realRef[_ref] = _isReal; } function withdraw(uint256 _percent) public onlyDCFamily { require(_percent>0&&_percent<=100); uint256 val = SafeMath.div(SafeMath.mul(address(this).balance,_percent), 300); if (val>0){ batman.transfer(val); superman.transfer(val); aquaman.transfer(val); } } // hatch eggs into bats function hatchEggs(address ref) public whenNotPaused { // set user&#39;s referral only if which is empty if (referrals[msg.sender] == address(0) && referrals[msg.sender] != msg.sender) { //referrals[msg.sender] = ref; if (realRef[ref] == 1){ referrals[msg.sender] = ref; }else{ referrals[msg.sender] = owner; } } uint256 eggsUsed = getMyEggs(); uint256 newBat = SafeMath.div(eggsUsed, EGGS_TO_HATCH_1BAT); hatcheryBat[msg.sender] = SafeMath.add(hatcheryBat[msg.sender], newBat); claimedEggs[msg.sender] = 0; lastHatch[msg.sender] = now; //send referral eggs 20% of user //claimedEggs[referrals[msg.sender]] = SafeMath.add(claimedEggs[referrals[msg.sender]], SafeMath.div(eggsUsed, 5)); claimedEggs[referrals[msg.sender]] = SafeMath.add(claimedEggs[referrals[msg.sender]], SafeMath.div(eggsUsed, 3)); //boost market to nerf bat hoarding // add 10% of user into market marketEggs = SafeMath.add(marketEggs, SafeMath.div(eggsUsed, 10)); } // sell eggs for eth function sellEggs() public whenNotPaused { uint256 hasEggs = getMyEggs(); uint256 eggValue = calculateEggSell(hasEggs); uint256 fee = devFee(eggValue); // kill one third of the owner&#39;s snails on egg sale hatcheryBat[msg.sender] = SafeMath.mul(SafeMath.div(hatcheryBat[msg.sender], 3), 2); claimedEggs[msg.sender] = 0; lastHatch[msg.sender] = now; marketEggs = SafeMath.add(marketEggs, hasEggs); owner.transfer(fee); msg.sender.transfer(SafeMath.sub(eggValue, fee)); } function buyEggs() public payable whenNotPaused { uint256 eggsBought = calculateEggBuy(msg.value, SafeMath.sub(address(this).balance, msg.value)); eggsBought = SafeMath.sub(eggsBought, devFee(eggsBought)); owner.transfer(devFee(msg.value)); claimedEggs[msg.sender] = SafeMath.add(claimedEggs[msg.sender], eggsBought); } //magic trade balancing algorithm function calculateTrade(uint256 rt, uint256 rs, uint256 bs) public view returns(uint256) { //(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt)); return SafeMath.div(SafeMath.mul(PSN, bs), SafeMath.add(PSNH, SafeMath.div(SafeMath.add(SafeMath.mul(PSN, rs), SafeMath.mul(PSNH, rt)), rt))); } // eggs to eth function calculateEggSell(uint256 eggs) public view returns(uint256) { return calculateTrade(eggs, marketEggs, address(this).balance); } function calculateEggBuy(uint256 eth, uint256 contractBalance) public view returns(uint256) { return calculateTrade(eth, contractBalance, marketEggs); } function calculateEggBuySimple(uint256 eth) public view returns(uint256) { return calculateEggBuy(eth, address(this).balance); } // eggs amount to eth for developers: eggs*4/100 function devFee(uint256 amount) public pure returns(uint256) { return SafeMath.div(SafeMath.mul(amount, 4), 100); } // add eggs when there&#39;s no more eggs // 864000000 with 0.02 Ether function seedMarket(uint256 eggs) public payable { require(marketEggs == 0); marketEggs = eggs; } function getFreeBat() public payable whenNotPaused { require(msg.value == 0.001 ether); require(hatcheryBat[msg.sender] == 0); lastHatch[msg.sender] = now; hatcheryBat[msg.sender] = STARTING_BAT; owner.transfer(msg.value); } function getBalance() public view returns(uint256) { return address(this).balance; } function getMyBat() public view returns(uint256) { return hatcheryBat[msg.sender]; } function getMyEggs() public view returns(uint256) { return SafeMath.add(claimedEggs[msg.sender], getEggsSinceLastHatch(msg.sender)); } function getEggsSinceLastHatch(address adr) public view returns(uint256) { uint256 secondsPassed = min(EGGS_TO_HATCH_1BAT, SafeMath.sub(now, lastHatch[adr])); return SafeMath.mul(secondsPassed, hatcheryBat[adr]); } function min(uint256 a, uint256 b) private pure returns(uint256) { return a < b ? a : b; } }
eggs amount to eth for developers: eggs4/100
function devFee(uint256 amount) public pure returns(uint256) { return SafeMath.div(SafeMath.mul(amount, 4), 100); }
8,061,131
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.11; interface IKenshi { function approveAndCall( address spender, uint256 value, bytes memory data ) external returns (bool); } interface IVRFUtils { function fastVerify( uint256[4] memory proof, bytes memory message, uint256[2] memory uPoint, uint256[4] memory vComponents ) external view returns (bool); function gammaToHash(uint256 _gammaX, uint256 _gammaY) external pure returns (bytes32); } interface ICoordinator { function getKenshiAddr() external view returns (address); function getVrfUtilsAddr() external view returns (address); } abstract contract VRFConsumer { /* Request tracking */ mapping(uint256 => bool) _requests; uint256 private _requestId; /* Kenshi related */ uint256 private _approve; IKenshi private _kenshi; IVRFUtils private _utils; ICoordinator private _coordinator; /* VRF options */ bool private _shouldVerify; bool private _silent; constructor() { _approve = (1e13 * 1e18) / 1e2; } /** * @dev Setup various VRF related settings: * - Coordinator Address: Kenshi VRF coordinator address * - Should Verify: Set if the received randomness should be verified * - Silent: Set if an event should be emitted on randomness delivery */ function setupVRF( address coordinatorAddr, bool shouldVerify, bool silent ) internal { _coordinator = ICoordinator(coordinatorAddr); address _vrfUtilsAddr = _coordinator.getVrfUtilsAddr(); address _kenshiAddr = _coordinator.getKenshiAddr(); _utils = IVRFUtils(_vrfUtilsAddr); _kenshi = IKenshi(_kenshiAddr); _shouldVerify = shouldVerify; _silent = silent; } /** * @dev Setup VRF, short version. */ function setupVRF(address coordinatorAddr) internal { setupVRF(coordinatorAddr, false, false); } /** * @dev Sets the Kenshi VRF coordinator address. */ function setVRFCoordinatorAddr(address coordinatorAddr) internal { _coordinator = ICoordinator(coordinatorAddr); } /** * @dev Sets the Kenshi VRF verifier address. */ function setVRFUtilsAddr(address vrfUtilsAddr) internal { _utils = IVRFUtils(vrfUtilsAddr); } /** * @dev Sets the Kenshi token address. */ function setVRFKenshiAddr(address kenshiAddr) internal { _kenshi = IKenshi(kenshiAddr); } /** * @dev Sets if the received random number should be verified. */ function setVRFShouldVerify(bool shouldVerify) internal { _shouldVerify = shouldVerify; } /** * @dev Sets if should emit an event once the randomness is fulfilled. */ function setVRFIsSilent(bool silent) internal { _silent = silent; } /** * @dev Request a random number. * * @return {requestId} Use to map received random numbers to requests. */ function requestRandomness() internal returns (uint256) { uint256 currentId = _requestId++; _kenshi.approveAndCall( address(_coordinator), _approve, abi.encode(currentId) ); return currentId; } event RandomnessFulfilled( uint256 requestId, uint256 randomness, uint256[4] _proof, bytes _message ); /** * @dev Called by the VRF Coordinator. */ function onRandomnessReady( uint256[4] memory proof, bytes memory message, uint256[2] memory uPoint, uint256[4] memory vComponents, uint256 requestId ) external { require( msg.sender == address(_coordinator), "Consumer: Only Coordinator can fulfill" ); if (_shouldVerify) { bool isValid = _utils.fastVerify( proof, message, uPoint, vComponents ); require(isValid, "Consumer: Proof not valid"); } bytes32 beta = _utils.gammaToHash(proof[0], proof[1]); uint256 randomness = uint256(beta); if (!_silent) { emit RandomnessFulfilled(requestId, randomness, proof, message); } fulfillRandomness(requestId, randomness); } /** * @dev You need to override this function in your smart contract. */ function fulfillRandomness(uint256 requestId, uint256 randomness) internal virtual; }
Called by the VRF Coordinator./
function onRandomnessReady( uint256[4] memory proof, bytes memory message, uint256[2] memory uPoint, uint256[4] memory vComponents, uint256 requestId ) external { require( msg.sender == address(_coordinator), "Consumer: Only Coordinator can fulfill" ); if (_shouldVerify) { bool isValid = _utils.fastVerify( proof, message, uPoint, vComponents ); require(isValid, "Consumer: Proof not valid"); } bytes32 beta = _utils.gammaToHash(proof[0], proof[1]); uint256 randomness = uint256(beta); if (!_silent) { emit RandomnessFulfilled(requestId, randomness, proof, message); } fulfillRandomness(requestId, randomness); }
1,078,938
// SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity >=0.6.0; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { ERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/ERC1155Receiver.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; contract Wrapped1155Metadata { // workaround which also arranges first storage slots of Wrapped1155 Wrapped1155Factory public factory; IERC1155 public multiToken; uint256 public tokenId; modifier onlyFactory() { require(msg.sender == address(factory), "Wrapped1155: only factory allowed to perform operation"); _; } } contract Wrapped1155 is Wrapped1155Metadata, ERC20 { constructor() public ERC20("Wrapped ERC-1155 Implementation", "WMT*") {} function mint(address account, uint256 amount) external onlyFactory { _mint(account, amount); } function burn(address account, uint256 amount) external onlyFactory { _burn(account, amount); } } contract Wrapped1155Factory is ERC1155Receiver { using Address for address; using SafeMath for uint; Wrapped1155 public erc20Implementation; constructor() public { erc20Implementation = new Wrapped1155(); } function onERC1155Received( address operator, address /* from */, uint256 id, uint256 value, bytes calldata data ) external override returns (bytes4) { address recipient = operator; // address recipient = data.length > 65 ? // abi.decode(data[65:], (address)) : // operator; Wrapped1155 wrapped1155 = requireWrapped1155(IERC1155(msg.sender), id, data); wrapped1155.mint(recipient, value); return this.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address /* from */, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external override returns (bytes4) { require(ids.length.mul(65) == data.length, "Wrapped1155Factory: data bytes should be ids size"); address recipient = operator; // address recipient = (data.length > 65) ? // abi.decode(bytes(data[64:]), (address)) : // operator; for (uint i = 0; i < ids.length; i++) { uint first = i.mul(65); uint next = first.add(65); requireWrapped1155(IERC1155(msg.sender), ids[i], bytes(data[first:next])).mint(recipient, values[i]); } return this.onERC1155BatchReceived.selector; } function unwrap( IERC1155 multiToken, uint256 tokenId, uint256 amount, address recipient, bytes calldata data ) external { getWrapped1155(multiToken, tokenId, data).burn(msg.sender, amount); multiToken.safeTransferFrom(address(this), recipient, tokenId, amount, data); } function batchUnwrap( IERC1155 multiToken, uint256[] calldata tokenIds, uint256[] calldata amounts, address recipient, bytes calldata data ) external { require(tokenIds.length == amounts.length, "Wrapped1155Factory: mismatched input arrays"); require(tokenIds.length.mul(65) == data.length, "Wrapped1155Factory: data bytes should be ids size"); for (uint i = 0; i < tokenIds.length; i++) { uint first = i.mul(65); uint next = first.add(65); getWrapped1155(multiToken, tokenIds[i], bytes(data[first:next])).burn(msg.sender, amounts[i]); } multiToken.safeBatchTransferFrom(address(this), recipient, tokenIds, amounts, data); } function getWrapped1155DeployBytecode( IERC1155 multiToken, uint256 tokenId, bytes calldata data ) public view returns (bytes memory) { bytes memory tokenName = bytes(data[:32]); bytes memory tokenSymbol = bytes(data[32:64]); bytes memory tokenDecimal = bytes(data[64:65]); return abi.encodePacked( // assign factory hex"73", this, hex"3d55", // assign multiToken hex"73", multiToken, hex"600155", // assign tokenId hex"7f", tokenId, hex"600255", // assign name hex"7f", tokenName, hex"600655", // assign symbol hex"7f", tokenSymbol, hex"600755", // assign decimals hex"60", tokenDecimal, hex"600855", // push 44 (length of runtime) hex"60", uint8(44), // load free memory pointer hex"604051", // dup runtime length hex"81", // push offset in this calldata to runtime object, hex"60", uint8(171), // dup free memory pointer hex"82" // codecopy runtime to memory and return hex"39f3", // greetz 0age for More-Minimal Proxy runtime bytecode // @link [Minimal Proxy Contract](https://eips.ethereum.org/EIPS/eip-1167) // @link [More-Minimal Proxy](https://medium.com/coinmonks/the-more-minimal-proxy-5756ae08ee48) hex"3d3d3d3d363d3d37363d73", address(erc20Implementation), hex"5af43d3d93803e602a57fd5bf3" ); } function getWrapped1155( IERC1155 multiToken, uint256 tokenId, bytes calldata data ) public view returns (Wrapped1155) { return Wrapped1155(address(uint256(keccak256(abi.encodePacked( uint8(0xff), this, uint256(1155), keccak256(getWrapped1155DeployBytecode(multiToken, tokenId, data)) ))))); } event Wrapped1155Creation( IERC1155 indexed multiToken, uint256 indexed tokenId, Wrapped1155 indexed wrappedToken ); function requireWrapped1155( IERC1155 multiToken, uint256 tokenId, bytes calldata data ) public returns (Wrapped1155) { bytes memory deployBytecode = getWrapped1155DeployBytecode(multiToken, tokenId, data); address wrapped1155Address = address(uint256(keccak256(abi.encodePacked( uint8(0xff), this, uint256(1155), keccak256(deployBytecode) )))); if (!wrapped1155Address.isContract()) { address addr; assembly { addr := create2(0, add(deployBytecode, 0x20), mload(deployBytecode), 1155) } require(wrapped1155Address == addr, "Wrapped1155Factory: failed to deploy"); emit Wrapped1155Creation( multiToken, tokenId, Wrapped1155(wrapped1155Address) ); } return Wrapped1155(wrapped1155Address); } }
address recipient = data.length > 65 ? abi.decode(data[65:], (address)) : operator;
function onERC1155Received( address operator, address /* from */, uint256 id, uint256 value, bytes calldata data ) external override returns (bytes4) { address recipient = operator; Wrapped1155 wrapped1155 = requireWrapped1155(IERC1155(msg.sender), id, data); wrapped1155.mint(recipient, value); return this.onERC1155Received.selector; }
2,559,229
/** *Submitted for verification at Etherscan.io on 2020-09-02 */ /** * Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } contract IERC20 { string public name; uint8 public decimals; string public symbol; function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function approve(address _spender, uint256 _value) public returns (bool); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract IWethERC20 is IWeth, IERC20 {} /** * @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 Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; 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; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } /** * @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; } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * 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 an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = (false, bytes(msg.data)); recipient.call.value(amount)(""); //inject UNHANDLED EXCEPTION require(success, "Address: unable to send value, recipient may have reverted"); } } /* * @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 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(), "unauthorized"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @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 Pausable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; modifier pausable(bytes4 sig) { require(!_isPaused(sig), "unauthorized"); _; } function _isPaused( bytes4 sig) internal view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } } contract LoanTokenBase is ReentrancyGuard, Ownable, Pausable { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; int256 internal constant sWEI_PRECISION = 10**18; string public name; string public symbol; uint8 public decimals; // uint88 for tight packing -> 8 + 88 + 160 = 256 uint88 internal lastSettleTime_; address public loanTokenAddress; uint256 public baseRate; uint256 public rateMultiplier; uint256 public lowUtilBaseRate; uint256 public lowUtilRateMultiplier; uint256 internal _flTotalAssetSupply; uint256 public checkpointSupply; uint256 public initialPrice; mapping (uint256 => bytes32) public loanParamsIds; // mapping of keccak256(collateralToken, isTorqueLoan) to loanParamsId mapping (address => uint256) internal checkpointPrices_; // price of token at last user checkpoint } contract AdvancedTokenStorage is LoanTokenBase { using SafeMath for uint256; event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); event Mint( address indexed minter, uint256 tokenAmount, uint256 assetAmount, uint256 price ); event Burn( address indexed burner, uint256 tokenAmount, uint256 assetAmount, uint256 price ); mapping(address => uint256) internal balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 internal totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf( address _owner) public view returns (uint256) { return balances[_owner]; } function allowance( address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } contract LoanToken is AdvancedTokenStorage { address internal target_; constructor( address _newOwner, address _newTarget) public { transferOwnership(_newOwner); _setTarget(_newTarget); } function() external payable { if (gasleft() <= 2300) { return; } address target = target_; bytes memory data = msg.data; assembly { let result := delegatecall(gas, target, add(data, 0x20), mload(data), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function setTarget( address _newTarget) public onlyOwner { _setTarget(_newTarget); } function _setTarget( address _newTarget) internal { require(Address.isContract(_newTarget), "target not a contract"); target_ = _newTarget; } }
Replacement for Solidity's `transfer`: sends `amount` wei to `recipient`, forwarding all available gas and reverting on errors. 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. IMPORTANT: because control is transferred to `recipient`, care must be taken to not create reentrancy vulnerabilities. Consider using {ReentrancyGuard} or the _Available since v2.4.0._/ solhint-disable-next-line avoid-call-value
function sendValue(address recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = (false, bytes(msg.data)); require(success, "Address: unable to send value, recipient may have reverted"); }
7,270,467
./full_match/1/0x56fB38D0FEA8D95433454c913134eda5e244788d/sources/contracts/core/InputValidator.sol
Verify oracle signature orderHash hash of the order signatureVersion signature version extraSignature packed oracle signature blockNumber block number used in oracle signature/ If the signature was a bulk listing the merkle path must be unpacked before the oracle signature. /
function _validateOracleAuthorization( bytes32 orderHash, SignatureVersion signatureVersion, bytes calldata extraSignature, uint256 blockNumber ) internal view returns (bool) { bytes32 oracleHash = _hashToSignOracle(orderHash, blockNumber); uint8 v; bytes32 r; bytes32 s; if (signatureVersion == SignatureVersion.Single) { assembly { v := calldataload(extraSignature.offset) r := calldataload(add(extraSignature.offset, 0x20)) s := calldataload(add(extraSignature.offset, 0x40)) } (v, r, s) = abi.decode(extraSignature, (uint8, bytes32, bytes32)); assembly { v := calldataload(add(extraSignature.offset, 0x20)) r := calldataload(add(extraSignature.offset, 0x40)) s := calldataload(add(extraSignature.offset, 0x60)) } uint8 _v, bytes32 _r, bytes32 _s; (bytes32[] memory merklePath, uint8 _v, bytes32 _r, bytes32 _s) = abi.decode(extraSignature, (bytes32[], uint8, bytes32, bytes32)); v = _v; r = _r; s = _s; return _verifyEcSig(oracle, oracleHash, v, r, s); }
3,108,296
pragma solidity ^0.4.23; import "../libraries/StateMachine.sol"; import "../pandora/IPandora.sol"; import "../jobs/IComputingJob.sol"; import "./IWorkerNode.sol"; /** * @title Worker Node Smart Contract * @author "Dr Maxim Orlovsky" <[email protected]> * * @dev # Worker Node Smart Contract * * Worker node contract accumulates funds/payments for performed cognitive work and contains inalienable reputation. * Note: In Pyrrha there is no mining. In the following versions all mined coins will be also assigned to the * `WorkerNode` contract * * Worker node acts as a state machine and each its function can be evoked only in some certain states. That"s * why each function must have state machine-controlled function modifiers. Contract state is managed by * - Worker node code (second level of consensus) * - Main Pandora contract [Pandora.sol] * - Worker node contract itself */ contract WorkerNode is IWorkerNode, StateMachine /* final */ { /** * ## State Machine extensions */ /// @dev Modifier requiring contract to be preset in one of the active states (`Assigned`, `ReadyForDataValidation`, /// `ValidatingData`, `ReadyForComputing`, `Computing`); otherwise an exception is generated and the function /// does not execute modifier requireActiveStates() { require( stateMachine.currentState == Assigned || stateMachine.currentState == ReadyForDataValidation || stateMachine.currentState == ValidatingData || stateMachine.currentState == ReadyForComputing || stateMachine.currentState == Computing); _; } /// @dev Private method initializing state machine. Must be called only once from the contract constructor function _initStateMachine() internal { // Creating table of possible state transitions mapping(uint8 => uint8[]) transitions = stateMachine.transitionTable; transitions[Uninitialized] = [Idle, Offline, InsufficientStake]; transitions[Offline] = [Idle]; transitions[Idle] = [Offline, UnderPenalty, Assigned, Destroyed]; transitions[Assigned] = [Offline, UnderPenalty, ReadyForDataValidation]; transitions[ReadyForDataValidation] = [ValidatingData, Offline, UnderPenalty, Idle]; transitions[UnderPenalty] = [Offline, InsufficientStake, Idle]; transitions[ValidatingData] = [Offline, Idle, UnderPenalty, ReadyForComputing]; transitions[ReadyForComputing] = [Computing, Offline, UnderPenalty, Idle]; transitions[Computing] = [Offline, UnderPenalty, Idle]; transitions[InsufficientStake] = [Offline, Idle, Destroyed]; // Initializing state machine via base contract code super._initStateMachine(); // Going into initial state (Offline) stateMachine.currentState = Offline; } /** * ## Main implementation */ /// ### Public variables /// @notice Reference to the main Pandora contract. /// @dev Required to check the validity of the method calls coming from the Pandora contract. /// Initialy set from the address supplied to the constructor and can"t be changed after. IPandora public pandora; /// @notice Active cognitive job reference. Zero when there is no active cognitive job assigned or performed /// @dev Valid (non-zero) only for active states (see `activeStates` modified for the list of such states) IComputingJob public activeJob; event WorkerDestroyed(); /// ### Constructor and destructor constructor( IPandora _pandora /// Reference to the main Pandora contract that creates Worker Node ) public { require(_pandora != address(0)); pandora = _pandora; // There should be no active cognitive job upon contract creation activeJob = IComputingJob(0); // Initialize state machine (state transition table and initial state). Always must be performed at the very // end of contract constructor code. _initStateMachine(); } /// ### Function modifiers /// @dev Modifier for functions that can be called only by the main Pandora contract modifier onlyPandora() { require(pandora != address(0)); require(msg.sender == address(pandora)); _; } /// @dev Modifier for functions that can be called only by one of the active cognitive jobs performed under /// main Pandora contract. It includes jobs _not_ assigned to the worker node modifier onlyCognitiveJob() { require(pandora != address(0)); IComputingJob sender = IComputingJob(msg.sender); require(pandora == sender.pandora()); require(pandora.isActiveJob(sender)); _; } /// @dev Modifier for functions that can be called only by the cognitive job assigned or performed by the worker /// node in one of its active states modifier onlyActiveCognitiveJob() { require(msg.sender == address(activeJob)); _; } function destroy() external onlyPandora { /// Call event before doing the actual contract suicide emit WorkerDestroyed(); /// Suiciding selfdestruct(owner); } /// ### External and public functions function alive( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Offline) transitionToState(Idle) { // Nothing to do here } /// @notice Do not call /// @dev Assigns cognitive job to the worker. Can be called only by one of active cognitive jobs listed under /// the main Pandora contract function assignJob( /// @dev Cognitive job to be assigned IComputingJob _job ) external // Can"t be called internally /// @dev Must be called only by one of active cognitive jobs listed under the main Pandora contract onlyCognitiveJob /// @dev Job can be assigned only to Idle workers requireState(Idle) /// @dev Successful completion must transition worker to an `Assigned` stage transitionToState(Assigned) { activeJob = _job; } function cancelJob( // No arguments ) external // Can"t be called internally onlyActiveCognitiveJob requireActiveStates transitionToState(Idle) { activeJob = IComputingJob(0); } function acceptAssignment( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Assigned) transitionToState(ReadyForDataValidation) { require(activeJob != IComputingJob(0)); activeJob.gatheringWorkersResponse(true); } function declineAssignment( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Assigned) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.gatheringWorkersResponse(false); } function processToDataValidation( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ReadyForDataValidation) transitionToState(ValidatingData) { // All actual work is done by function modifiers } function acceptValidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(ReadyForComputing) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Accept); } function declineValidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Decline); } function reportInvalidData( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ValidatingData) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.dataValidationResponse(IComputingJob.DataValidationResponse.Invalid); } function processToCognition( // No arguments ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(ReadyForComputing) transitionToState(Computing) { // All actual work is done by function modifiers } function provideResults( bytes _ipfsAddress ) external // Can"t be called internally /* @fixme onlyOwner */ requireState(Computing) transitionToState(Idle) { require(activeJob != IComputingJob(0)); activeJob.completeWork(_ipfsAddress); } /// @notice Withdraws full balance to the owner account. Can be called only by the owner of the contract. function withdrawBalance( // No arguments ) external // Can"t be called internally onlyOwner // Can be called only by the owner requireStates2(Idle, Offline) { /// @todo Handle stakes etc owner.transfer(address(this).balance); } }
Do not call Assigns cognitive job to the worker. Can be called only by one of active cognitive jobs listed under the main Pandora contract Cognitive job to be assigned Must be called only by one of active cognitive jobs listed under the main Pandora contract Job can be assigned only to Idle workers Successful completion must transition worker to an `Assigned` stage
function assignJob( IComputingJob _job onlyCognitiveJob requireState(Idle) transitionToState(Assigned) { activeJob = _job; }
14,102,299
./full_match/1/0xe88e4F4138A4EE65C1DaD6dCBd33e1750D9a7254/sources/src/PbAuraWsteth.sol
return 6 decimals
function getAllPoolInUSD() external view override returns (uint) { uint allPool = getAllPool(); if (allPool == 0) return 0; (, int latestPrice,,,) = ethUsdPriceOracle.latestRoundData(); return allPool * getPricePerFullShareInUSD() * uint(latestPrice) / 1e38; }
17,178,418
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./interfaces/IIssuer.sol"; // Libraries import "./SafeDecimalMath.sol"; // Internal references import "./interfaces/ISynth.sol"; import "./interfaces/ISynthetix.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/ISynthetixState.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/IDelegateApprovals.sol"; import "./IssuanceEternalStorage.sol"; import "./interfaces/IExchangeRates.sol"; import "./interfaces/IEtherCollateral.sol"; import "./interfaces/IRewardEscrow.sol"; import "./interfaces/IHasBalance.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/ILiquidations.sol"; // https://docs.synthetix.io/contracts/Issuer contract Issuer is Owned, MixinResolver, IIssuer { using SafeMath for uint; using SafeDecimalMath for uint; bytes32 private constant sUSD = "sUSD"; bytes32 public constant LAST_ISSUE_EVENT = "LAST_ISSUE_EVENT"; // Minimum Stake time may not exceed 1 weeks. uint public constant MAX_MINIMUM_STAKING_TIME = 1 weeks; uint public minimumStakeTime = 24 hours; // default minimum waiting period after issuing synths // Available Synths which can be used with the system ISynth[] public availableSynths; mapping(bytes32 => ISynth) public synths; mapping(address => bytes32) public synthsByAddress; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; bytes32 private constant CONTRACT_SYNTHETIXSTATE = "SynthetixState"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals"; bytes32 private constant CONTRACT_ISSUANCEETERNALSTORAGE = "IssuanceEternalStorage"; bytes32 private constant CONTRACT_ETHERCOLLATERAL = "EtherCollateral"; bytes32 private constant CONTRACT_REWARDESCROW = "RewardEscrow"; bytes32 private constant CONTRACT_SYNTHETIXESCROW = "SynthetixEscrow"; bytes32 private constant CONTRACT_LIQUIDATIONS = "Liquidations"; bytes32[24] private addressesToCache = [ CONTRACT_SYNTHETIX, CONTRACT_EXCHANGER, CONTRACT_EXRATES, CONTRACT_SYNTHETIXSTATE, CONTRACT_FEEPOOL, CONTRACT_DELEGATEAPPROVALS, CONTRACT_ISSUANCEETERNALSTORAGE, CONTRACT_ETHERCOLLATERAL, CONTRACT_REWARDESCROW, CONTRACT_SYNTHETIXESCROW, CONTRACT_LIQUIDATIONS ]; constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver, addressesToCache) {} /* ========== VIEWS ========== */ function synthetix() internal view returns (ISynthetix) { return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX, "Missing Synthetix address")); } function synthetixERC20() internal view returns (IERC20) { return IERC20(requireAndGetAddress(CONTRACT_SYNTHETIX, "Missing Synthetix address")); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER, "Missing Exchanger address")); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES, "Missing ExchangeRates address")); } function synthetixState() internal view returns (ISynthetixState) { return ISynthetixState(requireAndGetAddress(CONTRACT_SYNTHETIXSTATE, "Missing SynthetixState address")); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL, "Missing FeePool address")); } function liquidations() internal view returns (ILiquidations) { return ILiquidations(requireAndGetAddress(CONTRACT_LIQUIDATIONS, "Missing Liquidations address")); } function delegateApprovals() internal view returns (IDelegateApprovals) { return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS, "Missing DelegateApprovals address")); } function issuanceEternalStorage() internal view returns (IssuanceEternalStorage) { return IssuanceEternalStorage( requireAndGetAddress(CONTRACT_ISSUANCEETERNALSTORAGE, "Missing IssuanceEternalStorage address") ); } function etherCollateral() internal view returns (IEtherCollateral) { return IEtherCollateral(requireAndGetAddress(CONTRACT_ETHERCOLLATERAL, "Missing EtherCollateral address")); } function rewardEscrow() internal view returns (IRewardEscrow) { return IRewardEscrow(requireAndGetAddress(CONTRACT_REWARDESCROW, "Missing RewardEscrow address")); } function synthetixEscrow() internal view returns (IHasBalance) { return IHasBalance(requireAndGetAddress(CONTRACT_SYNTHETIXESCROW, "Missing SynthetixEscrow address")); } function _availableCurrencyKeysWithOptionalSNX(bool withSNX) internal view returns (bytes32[] memory) { bytes32[] memory currencyKeys = new bytes32[](availableSynths.length + (withSNX ? 1 : 0)); for (uint i = 0; i < availableSynths.length; i++) { currencyKeys[i] = synthsByAddress[address(availableSynths[i])]; } if (withSNX) { currencyKeys[availableSynths.length] = "SNX"; } return currencyKeys; } function _totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) internal view returns (uint totalIssued, bool anyRateIsStale) { uint total = 0; uint currencyRate; bytes32[] memory synthsAndSNX = _availableCurrencyKeysWithOptionalSNX(true); // In order to reduce gas usage, fetch all rates and stale at once (uint[] memory rates, bool anyRateStale) = exchangeRates().ratesAndStaleForCurrencies(synthsAndSNX); // Then instead of invoking exchangeRates().effectiveValue() for each synth, use the rate already fetched for (uint i = 0; i < synthsAndSNX.length - 1; i++) { bytes32 synth = synthsAndSNX[i]; if (synth == currencyKey) { currencyRate = rates[i]; } uint totalSynths = IERC20(address(synths[synth])).totalSupply(); // minus total issued synths from Ether Collateral from sETH.totalSupply() if (excludeEtherCollateral && synth == "sETH") { totalSynths = totalSynths.sub(etherCollateral().totalIssuedSynths()); } uint synthValue = totalSynths.multiplyDecimalRound(rates[i]); total = total.add(synthValue); } if (currencyKey == "SNX") { // if no rate while iterating through synths, then try SNX currencyRate = rates[synthsAndSNX.length - 1]; } else if (currencyRate == 0) { // and, in an edge case where the requested rate isn't a synth or SNX, then do the lookup currencyRate = exchangeRates().rateForCurrency(currencyKey); } return (total.divideDecimalRound(currencyRate), anyRateStale); } function _debtBalanceOfAndTotalDebt(address _issuer, bytes32 currencyKey) internal view returns ( uint debtBalance, uint totalSystemValue, bool anyRateIsStale ) { ISynthetixState state = synthetixState(); // What was their initial debt ownership? uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = state.issuanceData(_issuer); // What's the total value of the system excluding ETH backed synths in their requested currency? (totalSystemValue, anyRateIsStale) = _totalIssuedSynths(currencyKey, true); // If it's zero, they haven't issued, and they have no debt. // Note: it's more gas intensive to put this check here rather than before _totalIssuedSynths // if they have 0 SNX, but it's a necessary trade-off if (initialDebtOwnership == 0) return (0, totalSystemValue, anyRateIsStale); // Figure out the global debt percentage delta from when they entered the system. // This is a high precision integer of 27 (1e27) decimals. uint currentDebtOwnership = state .lastDebtLedgerEntry() .divideDecimalRoundPrecise(state.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); // Their debt balance is their portion of the total system value. uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal().multiplyDecimalRoundPrecise( currentDebtOwnership ); // Convert back into 18 decimals (1e18) debtBalance = highPrecisionBalance.preciseDecimalToDecimal(); } function _canBurnSynths(address account) internal view returns (bool) { return now >= _lastIssueEvent(account).add(minimumStakeTime); } function _lastIssueEvent(address account) internal view returns (uint) { // Get the timestamp of the last issue this account made return issuanceEternalStorage().getUIntValue(keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account))); } function _remainingIssuableSynths(address _issuer) internal view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt, bool anyRateIsStale ) { (alreadyIssued, totalSystemDebt, anyRateIsStale) = _debtBalanceOfAndTotalDebt(_issuer, sUSD); maxIssuable = _maxIssuableSynths(_issuer); if (alreadyIssued >= maxIssuable) { maxIssuable = 0; } else { maxIssuable = maxIssuable.sub(alreadyIssued); } } function _maxIssuableSynths(address _issuer) internal view returns (uint) { // What is the value of their SNX balance in sUSD uint destinationValue = exchangeRates().effectiveValue("SNX", _collateral(_issuer), sUSD); // They're allowed to issue up to issuanceRatio of that value return destinationValue.multiplyDecimal(synthetixState().issuanceRatio()); } function _collateralisationRatio(address _issuer) internal view returns (uint, bool) { uint totalOwnedSynthetix = _collateral(_issuer); (uint debtBalance, , bool anyRateIsStale) = _debtBalanceOfAndTotalDebt(_issuer, "SNX"); // it's more gas intensive to put this check here if they have 0 SNX, but it complies with the interface if (totalOwnedSynthetix == 0) return (0, anyRateIsStale); return (debtBalance.divideDecimalRound(totalOwnedSynthetix), anyRateIsStale); } function _collateral(address account) internal view returns (uint) { uint balance = synthetixERC20().balanceOf(account); if (address(synthetixEscrow()) != address(0)) { balance = balance.add(synthetixEscrow().balanceOf(account)); } if (address(rewardEscrow()) != address(0)) { balance = balance.add(rewardEscrow().balanceOf(account)); } return balance; } /* ========== VIEWS ========== */ function canBurnSynths(address account) external view returns (bool) { return _canBurnSynths(account); } function availableCurrencyKeys() external view returns (bytes32[] memory) { return _availableCurrencyKeysWithOptionalSNX(false); } function availableSynthCount() external view returns (uint) { return availableSynths.length; } function anySynthOrSNXRateIsStale() external view returns (bool anyRateStale) { bytes32[] memory currencyKeysWithSNX = _availableCurrencyKeysWithOptionalSNX(true); (, anyRateStale) = exchangeRates().ratesAndStaleForCurrencies(currencyKeysWithSNX); } function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint totalIssued) { (totalIssued, ) = _totalIssuedSynths(currencyKey, excludeEtherCollateral); } function lastIssueEvent(address account) external view returns (uint) { return _lastIssueEvent(account); } function collateralisationRatio(address _issuer) external view returns (uint cratio) { (cratio, ) = _collateralisationRatio(_issuer); } function collateralisationRatioAndAnyRatesStale(address _issuer) external view returns (uint cratio, bool anyRateIsStale) { return _collateralisationRatio(_issuer); } function collateral(address account) external view returns (uint) { return _collateral(account); } function debtBalanceOf(address _issuer, bytes32 currencyKey) external view returns (uint debtBalance) { ISynthetixState state = synthetixState(); // What was their initial debt ownership? (uint initialDebtOwnership, ) = state.issuanceData(_issuer); // If it's zero, they haven't issued, and they have no debt. if (initialDebtOwnership == 0) return 0; (debtBalance, , ) = _debtBalanceOfAndTotalDebt(_issuer, currencyKey); } function remainingIssuableSynths(address _issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ) { (maxIssuable, alreadyIssued, totalSystemDebt, ) = _remainingIssuableSynths(_issuer); } function maxIssuableSynths(address _issuer) external view returns (uint) { return _maxIssuableSynths(_issuer); } function transferableSynthetixAndAnyRateIsStale(address account, uint balance) external view returns (uint transferable, bool anyRateIsStale) { // How many SNX do they have, excluding escrow? // Note: We're excluding escrow here because we're interested in their transferable amount // and escrowed SNX are not transferable. // How many of those will be locked by the amount they've issued? // Assuming issuance ratio is 20%, then issuing 20 SNX of value would require // 100 SNX to be locked in their wallet to maintain their collateralisation ratio // The locked synthetix value can exceed their balance. uint debtBalance; (debtBalance, , anyRateIsStale) = _debtBalanceOfAndTotalDebt(account, "SNX"); uint lockedSynthetixValue = debtBalance.divideDecimalRound(synthetixState().issuanceRatio()); // If we exceed the balance, no SNX are transferable, otherwise the difference is. if (lockedSynthetixValue >= balance) { transferable = 0; } else { transferable = balance.sub(lockedSynthetixValue); } } /* ========== SETTERS ========== */ function setMinimumStakeTime(uint _seconds) external onlyOwner { // Set the min stake time on locking synthetix require(_seconds <= MAX_MINIMUM_STAKING_TIME, "stake time exceed maximum 1 week"); minimumStakeTime = _seconds; emit MinimumStakeTimeUpdated(minimumStakeTime); } /* ========== MUTATIVE FUNCTIONS ========== */ function addSynth(ISynth synth) external onlyOwner { bytes32 currencyKey = synth.currencyKey(); require(synths[currencyKey] == ISynth(0), "Synth already exists"); require(synthsByAddress[address(synth)] == bytes32(0), "Synth address already exists"); availableSynths.push(synth); synths[currencyKey] = synth; synthsByAddress[address(synth)] = currencyKey; emit SynthAdded(currencyKey, address(synth)); } function removeSynth(bytes32 currencyKey) external onlyOwner { require(address(synths[currencyKey]) != address(0), "Synth does not exist"); require(IERC20(address(synths[currencyKey])).totalSupply() == 0, "Synth supply exists"); require(currencyKey != sUSD, "Cannot remove synth"); // Save the address we're removing for emitting the event at the end. address synthToRemove = address(synths[currencyKey]); // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (address(availableSynths[i]) == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[address(synths[currencyKey])]; delete synths[currencyKey]; emit SynthRemoved(currencyKey, synthToRemove); } function issueSynthsOnBehalf( address issueForAddress, address from, uint amount ) external onlySynthetix { require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf"); (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsStale) = _remainingIssuableSynths( issueForAddress ); require(!anyRateIsStale, "A synth or SNX rate is stale"); require(amount <= maxIssuable, "Amount too large"); _internalIssueSynths(issueForAddress, amount, existingDebt, totalSystemDebt); } function issueMaxSynthsOnBehalf(address issueForAddress, address from) external onlySynthetix { require(delegateApprovals().canIssueFor(issueForAddress, from), "Not approved to act on behalf"); (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsStale) = _remainingIssuableSynths( issueForAddress ); require(!anyRateIsStale, "A synth or SNX rate is stale"); _internalIssueSynths(issueForAddress, maxIssuable, existingDebt, totalSystemDebt); } function issueSynths(address from, uint amount) external onlySynthetix { // Get remaining issuable in sUSD and existingDebt (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsStale) = _remainingIssuableSynths(from); require(!anyRateIsStale, "A synth or SNX rate is stale"); require(amount <= maxIssuable, "Amount too large"); _internalIssueSynths(from, amount, existingDebt, totalSystemDebt); } function issueMaxSynths(address from) external onlySynthetix { // Figure out the maximum we can issue in that currency (uint maxIssuable, uint existingDebt, uint totalSystemDebt, bool anyRateIsStale) = _remainingIssuableSynths(from); require(!anyRateIsStale, "A synth or SNX rate is stale"); _internalIssueSynths(from, maxIssuable, existingDebt, totalSystemDebt); } function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external onlySynthetix { require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf"); _burnSynths(burnForAddress, amount); } function burnSynths(address from, uint amount) external onlySynthetix { _burnSynths(from, amount); } /* ========== INTERNAL FUNCTIONS ========== */ function _internalIssueSynths( address from, uint amount, uint existingDebt, uint totalSystemDebt ) internal { // Keep track of the debt they're about to create _addToDebtRegister(from, amount, existingDebt, totalSystemDebt); // record issue timestamp _setLastIssueEvent(from); // Create their synths synths[sUSD].issue(from, amount); // Store their locked SNX amount to determine their fee % for the period _appendAccountIssuanceRecord(from); } // Burn synths requires minimum stake time is elapsed function _burnSynths(address from, uint amount) internal { require(_canBurnSynths(from), "Minimum stake time not reached"); // First settle anything pending into sUSD as burning or issuing impacts the size of the debt pool (, uint refunded, uint numEntriesSettled) = exchanger().settle(from, sUSD); // How much debt do they have? (uint existingDebt, uint totalSystemValue, bool anyRateIsStale) = _debtBalanceOfAndTotalDebt(from, sUSD); require(!anyRateIsStale, "A synth or SNX rate is stale"); require(existingDebt > 0, "No debt to forgive"); uint debtToRemoveAfterSettlement = amount; if (numEntriesSettled > 0) { debtToRemoveAfterSettlement = exchanger().calculateAmountAfterSettlement(from, sUSD, amount, refunded); } uint maxIssuableSynthsForAccount = _maxIssuableSynths(from); _internalBurnSynths(from, debtToRemoveAfterSettlement, existingDebt, totalSystemValue, maxIssuableSynthsForAccount); } function _burnSynthsForLiquidation( address burnForAddress, address liquidator, uint amount, uint existingDebt, uint totalDebtIssued ) internal { // liquidation requires sUSD to be already settled / not in waiting period // Remove liquidated debt from the ledger _removeFromDebtRegister(burnForAddress, amount, existingDebt, totalDebtIssued); // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[sUSD].burn(liquidator, amount); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(burnForAddress); } function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external onlySynthetix { require(delegateApprovals().canBurnFor(burnForAddress, from), "Not approved to act on behalf"); _burnSynthsToTarget(burnForAddress); } function burnSynthsToTarget(address from) external onlySynthetix { _burnSynthsToTarget(from); } // Burns your sUSD to the target c-ratio so you can claim fees // Skip settle anything pending into sUSD as user will still have debt remaining after target c-ratio function _burnSynthsToTarget(address from) internal { // How much debt do they have? (uint existingDebt, uint totalSystemValue, bool anyRateIsStale) = _debtBalanceOfAndTotalDebt(from, sUSD); require(!anyRateIsStale, "A synth or SNX rate is stale"); require(existingDebt > 0, "No debt to forgive"); uint maxIssuableSynthsForAccount = _maxIssuableSynths(from); // The amount of sUSD to burn to fix c-ratio. The safe sub will revert if its < 0 uint amountToBurnToTarget = existingDebt.sub(maxIssuableSynthsForAccount); // Burn will fail if you dont have the required sUSD in your wallet _internalBurnSynths(from, amountToBurnToTarget, existingDebt, totalSystemValue, maxIssuableSynthsForAccount); } function _internalBurnSynths( address from, uint amount, uint existingDebt, uint totalSystemValue, uint maxIssuableSynthsForAccount ) internal { // If they're trying to burn more debt than they actually owe, rather than fail the transaction, let's just // clear their debt and leave them be. uint amountToRemove = existingDebt < amount ? existingDebt : amount; // Remove their debt from the ledger _removeFromDebtRegister(from, amountToRemove, existingDebt, totalSystemValue); uint amountToBurn = amountToRemove; // synth.burn does a safe subtraction on balance (so it will revert if there are not enough synths). synths[sUSD].burn(from, amountToBurn); // Store their debtRatio against a feeperiod to determine their fee/rewards % for the period _appendAccountIssuanceRecord(from); // Check and remove liquidation if existingDebt after burning is <= maxIssuableSynths // Issuance ratio is fixed so should remove any liquidations if (existingDebt.sub(amountToBurn) <= maxIssuableSynthsForAccount) { liquidations().removeAccountInLiquidation(from); } } function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external onlySynthetix returns (uint totalRedeemed, uint amountToLiquidate) { // Ensure waitingPeriod and sUSD balance is settled as burning impacts the size of debt pool require(!exchanger().hasWaitingPeriodOrSettlementOwing(liquidator, sUSD), "sUSD needs to be settled"); ILiquidations _liquidations = liquidations(); // Check account is liquidation open require(_liquidations.isOpenForLiquidation(account), "Account not open for liquidation"); // require liquidator has enough sUSD require(IERC20(address(synths[sUSD])).balanceOf(liquidator) >= susdAmount, "Not enough sUSD"); uint liquidationPenalty = _liquidations.liquidationPenalty(); uint collateralForAccount = _collateral(account); // What is the value of their SNX balance in sUSD? uint collateralValue = exchangeRates().effectiveValue("SNX", collateralForAccount, sUSD); // What is their debt in sUSD? (uint debtBalance, uint totalDebtIssued, bool anyRateIsStale) = _debtBalanceOfAndTotalDebt(account, sUSD); require(!anyRateIsStale, "A synth or SNX rate is stale"); uint amountToFixRatio = _liquidations.calculateAmountToFixCollateral(debtBalance, collateralValue); // Cap amount to liquidate to repair collateral ratio based on issuance ratio amountToLiquidate = amountToFixRatio < susdAmount ? amountToFixRatio : susdAmount; // what's the equivalent amount of snx for the amountToLiquidate? uint snxRedeemed = exchangeRates().effectiveValue(sUSD, amountToLiquidate, "SNX"); // Add penalty totalRedeemed = snxRedeemed.multiplyDecimal(SafeDecimalMath.unit().add(liquidationPenalty)); // if total SNX to redeem is greater than account's collateral // account is under collateralised, liquidate all collateral and reduce sUSD to burn // an insurance fund will be added to cover these undercollateralised positions if (totalRedeemed > collateralForAccount) { // set totalRedeemed to all collateral totalRedeemed = collateralForAccount; // whats the equivalent sUSD to burn for all collateral less penalty amountToLiquidate = exchangeRates().effectiveValue( "SNX", collateralForAccount.divideDecimal(SafeDecimalMath.unit().add(liquidationPenalty)), sUSD ); } // burn sUSD from messageSender (liquidator) and reduce account's debt _burnSynthsForLiquidation(account, liquidator, amountToLiquidate, debtBalance, totalDebtIssued); if (amountToLiquidate == amountToFixRatio) { // Remove liquidation _liquidations.removeAccountInLiquidation(account); } } function _setLastIssueEvent(address account) internal { // Set the timestamp of the last issueSynths issuanceEternalStorage().setUIntValue(keccak256(abi.encodePacked(LAST_ISSUE_EVENT, account)), block.timestamp); } function _appendAccountIssuanceRecord(address from) internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState().issuanceData(from); feePool().appendAccountIssuanceRecord(from, initialDebtOwnership, debtEntryIndex); } function _addToDebtRegister( address from, uint amount, uint existingDebt, uint totalDebtIssued ) internal { ISynthetixState state = synthetixState(); // What will the new total be including the new value? uint newTotalDebtIssued = amount.add(totalDebtIssued); // What is their percentage (as a high precision int) of the total debt? uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. // The delta is a high precision integer. uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); // And what does their debt ownership look like including this previous stake? if (existingDebt > 0) { debtPercentage = amount.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } // Are they a new issuer? If so, record them. if (existingDebt == 0) { state.incrementTotalIssuerCount(); } // Save the debt entry parameters state.setCurrentIssuanceData(from, debtPercentage); // And if we're the first, push 1 as there was no effect to any other holders, otherwise push // the change for the rest of the debt holders. The debt ledger holds high precision integers. if (state.debtLedgerLength() > 0) { state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } else { state.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function _removeFromDebtRegister( address from, uint amount, uint existingDebt, uint totalDebtIssued ) internal { ISynthetixState state = synthetixState(); uint debtToRemove = amount; // What will the new total after taking out the withdrawn amount uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta = 0; // What will the debt delta be if there is any debt left? // Set delta to 0 if no more debt left in system after user if (newTotalDebtIssued > 0) { // What is the percentage of the withdrawn debt (as a high precision int) of the total debt after? uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); // And what effect does this percentage change have on the global debt holding of other issuers? // The delta specifically needs to not take into account any existing debt as it's already // accounted for in the delta from when they issued previously. delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } // Are they exiting the system, or are they just decreasing their debt position? if (debtToRemove == existingDebt) { state.setCurrentIssuanceData(from, 0); state.decrementTotalIssuerCount(); } else { // What percentage of the debt will they be left with? uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); // Store the debt percentage and debt ledger as high precision integers state.setCurrentIssuanceData(from, newDebtPercentage); } // Update our cumulative ledger. This is also a high precision integer. state.appendDebtLedgerValue(state.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)); } /* ========== MODIFIERS ========== */ modifier onlySynthetix() { require(msg.sender == address(synthetix()), "Issuer: Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ event MinimumStakeTimeUpdated(uint minimumStakeTime); event SynthAdded(bytes32 currencyKey, address synth); event SynthRemoved(bytes32 currencyKey, address synth); }
Keep track of the debt they're about to create record issue timestamp Create their synths Store their locked SNX amount to determine their fee % for the period
function _internalIssueSynths( address from, uint amount, uint existingDebt, uint totalSystemDebt ) internal { _addToDebtRegister(from, amount, existingDebt, totalSystemDebt); _setLastIssueEvent(from); synths[sUSD].issue(from, amount); _appendAccountIssuanceRecord(from); }
5,425,980
pragma solidity ^0.4.19; contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function getBeneficiary() external view returns(address); } contract SanctuaryInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool); /// @dev generate new warrior genes /// @param _heroGenes Genes of warrior that have completed dungeon /// @param _heroLevel Level of the warrior /// @return the genes that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroGenes, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256); } contract PVPInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPProvider() external pure returns (bool); function addTournamentContender(address _owner, uint256[] _tournamentData) external payable; function getTournamentThresholdFee() public view returns(uint256); function addPVPContender(address _owner, uint256 _packedWarrior) external payable; function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256); } contract PVPListenerInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPListener() public pure returns (bool); function getBeneficiary() external view returns(address); function pvpFinished(uint256[] warriorData, uint256 matchingCount) public; function pvpContenderRemoved(uint256 _warriorId) public; function tournamentFinished(uint256[] packedContenders) public; } contract PermissionControll { // This facet controls access to contract that implements it. There are four roles managed here: // // - The Admin: The Admin can reassign admin and issuer roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the CryptoWarriorCore constructor. // // - The Bank: The Bank can withdraw funds from CryptoWarriorCore and its auction and battle contracts, and change admin role. // // - The Issuer: The Issuer can release gen0 warriors to auction. // // / @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public adminAddress; address public bankAddress; address public issuerAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // / @dev Access modifier for Admin-only functionality modifier onlyAdmin(){ require(msg.sender == adminAddress); _; } // / @dev Access modifier for Bank-only functionality modifier onlyBank(){ require(msg.sender == bankAddress); _; } /// @dev Access modifier for Issuer-only functionality modifier onlyIssuer(){ require(msg.sender == issuerAddress); _; } modifier onlyAuthorized(){ require(msg.sender == issuerAddress || msg.sender == adminAddress || msg.sender == bankAddress); _; } // / @dev Assigns a new address to act as the Bank. Only available to the current Bank. // / @param _newBank The address of the new Bank function setBank(address _newBank) external onlyBank { require(_newBank != address(0)); bankAddress = _newBank; } // / @dev Assigns a new address to act as the Admin. Only available to the current Admin. // / @param _newAdmin The address of the new Admin function setAdmin(address _newAdmin) external { require(msg.sender == adminAddress || msg.sender == bankAddress); require(_newAdmin != address(0)); adminAddress = _newAdmin; } // / @dev Assigns a new address to act as the Issuer. Only available to the current Issuer. // / @param _newIssuer The address of the new Issuer function setIssuer(address _newIssuer) external onlyAdmin{ require(_newIssuer != address(0)); issuerAddress = _newIssuer; } /*** Pausable functionality adapted from OpenZeppelin ***/ // / @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused(){ require(!paused); _; } // / @dev Modifier to allow actions only when the contract IS paused modifier whenPaused{ require(paused); _; } // / @dev Called by any "Authorized" role to pause the contract. Used only when // / a bug or exploit is detected and we need to limit damage. function pause() external onlyAuthorized whenNotPaused{ paused = true; } // / @dev Unpauses the smart contract. Can only be called by the Admin. // / @notice This is public rather than external so it can be called by // / derived contracts. function unpause() public onlyAdmin whenPaused{ // can't unpause if contract was upgraded paused = false; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyAdmin whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner(){ require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner{ if (newOwner != address(0)) { owner = newOwner; } } } contract PausableBattle is Ownable { event PausePVP(bool paused); event PauseTournament(bool paused); bool public pvpPaused = false; bool public tournamentPaused = false; /** PVP */ modifier PVPNotPaused(){ require(!pvpPaused); _; } modifier PVPPaused{ require(pvpPaused); _; } function pausePVP() public onlyOwner PVPNotPaused { pvpPaused = true; PausePVP(true); } function unpausePVP() public onlyOwner PVPPaused { pvpPaused = false; PausePVP(false); } /** Tournament */ modifier TournamentNotPaused(){ require(!tournamentPaused); _; } modifier TournamentPaused{ require(tournamentPaused); _; } function pauseTournament() public onlyOwner TournamentNotPaused { tournamentPaused = true; PauseTournament(true); } function unpauseTournament() public onlyOwner TournamentPaused { tournamentPaused = false; PauseTournament(false); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused(){ require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused{ require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } library CryptoUtils { /* CLASSES */ uint256 internal constant WARRIOR = 0; uint256 internal constant ARCHER = 1; uint256 internal constant MAGE = 2; /* RARITIES */ uint256 internal constant COMMON = 1; uint256 internal constant UNCOMMON = 2; uint256 internal constant RARE = 3; uint256 internal constant MYTHIC = 4; uint256 internal constant LEGENDARY = 5; uint256 internal constant UNIQUE = 6; /* LIMITS */ uint256 internal constant CLASS_MECHANICS_MAX = 3; uint256 internal constant RARITY_MAX = 6; /*@dev range used for rarity chance computation */ uint256 internal constant RARITY_CHANCE_RANGE = 10000000; uint256 internal constant POINTS_TO_LEVEL = 10; /* ATTRIBUTE MASKS */ /*@dev range 0-9999 */ uint256 internal constant UNIQUE_MASK_0 = 1; /*@dev range 0-9 */ uint256 internal constant RARITY_MASK_1 = UNIQUE_MASK_0 * 10000; /*@dev range 0-999 */ uint256 internal constant CLASS_VIEW_MASK_2 = RARITY_MASK_1 * 10; /*@dev range 0-999 */ uint256 internal constant BODY_COLOR_MASK_3 = CLASS_VIEW_MASK_2 * 1000; /*@dev range 0-999 */ uint256 internal constant EYES_MASK_4 = BODY_COLOR_MASK_3 * 1000; /*@dev range 0-999 */ uint256 internal constant MOUTH_MASK_5 = EYES_MASK_4 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_MASK_6 = MOUTH_MASK_5 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_COLOR_MASK_7 = HEIR_MASK_6 * 1000; /*@dev range 0-999 */ uint256 internal constant ARMOR_MASK_8 = HEIR_COLOR_MASK_7 * 1000; /*@dev range 0-999 */ uint256 internal constant WEAPON_MASK_9 = ARMOR_MASK_8 * 1000; /*@dev range 0-999 */ uint256 internal constant HAT_MASK_10 = WEAPON_MASK_9 * 1000; /*@dev range 0-99 */ uint256 internal constant RUNES_MASK_11 = HAT_MASK_10 * 1000; /*@dev range 0-99 */ uint256 internal constant WINGS_MASK_12 = RUNES_MASK_11 * 100; /*@dev range 0-99 */ uint256 internal constant PET_MASK_13 = WINGS_MASK_12 * 100; /*@dev range 0-99 */ uint256 internal constant BORDER_MASK_14 = PET_MASK_13 * 100; /*@dev range 0-99 */ uint256 internal constant BACKGROUND_MASK_15 = BORDER_MASK_14 * 100; /*@dev range 0-99 */ uint256 internal constant INTELLIGENCE_MASK_16 = BACKGROUND_MASK_15 * 100; /*@dev range 0-99 */ uint256 internal constant AGILITY_MASK_17 = INTELLIGENCE_MASK_16 * 100; /*@dev range 0-99 */ uint256 internal constant STRENGTH_MASK_18 = AGILITY_MASK_17 * 100; /*@dev range 0-9 */ uint256 internal constant CLASS_MECH_MASK_19 = STRENGTH_MASK_18 * 100; /*@dev range 0-999 */ uint256 internal constant RARITY_BONUS_MASK_20 = CLASS_MECH_MASK_19 * 10; /*@dev range 0-9 */ uint256 internal constant SPECIALITY_MASK_21 = RARITY_BONUS_MASK_20 * 1000; /*@dev range 0-99 */ uint256 internal constant DAMAGE_MASK_22 = SPECIALITY_MASK_21 * 10; /*@dev range 0-99 */ uint256 internal constant AURA_MASK_23 = DAMAGE_MASK_22 * 100; /*@dev 20 decimals left */ uint256 internal constant BASE_MASK_24 = AURA_MASK_23 * 100; /* SPECIAL PERKS */ uint256 internal constant MINER_PERK = 1; /* PARAM INDEXES */ uint256 internal constant BODY_COLOR_MAX_INDEX_0 = 0; uint256 internal constant EYES_MAX_INDEX_1 = 1; uint256 internal constant MOUTH_MAX_2 = 2; uint256 internal constant HAIR_MAX_3 = 3; uint256 internal constant HEIR_COLOR_MAX_4 = 4; uint256 internal constant ARMOR_MAX_5 = 5; uint256 internal constant WEAPON_MAX_6 = 6; uint256 internal constant HAT_MAX_7 = 7; uint256 internal constant RUNES_MAX_8 = 8; uint256 internal constant WINGS_MAX_9 = 9; uint256 internal constant PET_MAX_10 = 10; uint256 internal constant BORDER_MAX_11 = 11; uint256 internal constant BACKGROUND_MAX_12 = 12; uint256 internal constant UNIQUE_INDEX_13 = 13; uint256 internal constant LEGENDARY_INDEX_14 = 14; uint256 internal constant MYTHIC_INDEX_15 = 15; uint256 internal constant RARE_INDEX_16 = 16; uint256 internal constant UNCOMMON_INDEX_17 = 17; uint256 internal constant UNIQUE_TOTAL_INDEX_18 = 18; /* PACK PVP DATA LOGIC */ //pvp data uint256 internal constant CLASS_PACK_0 = 1; uint256 internal constant RARITY_BONUS_PACK_1 = CLASS_PACK_0 * 10; uint256 internal constant RARITY_PACK_2 = RARITY_BONUS_PACK_1 * 1000; uint256 internal constant EXPERIENCE_PACK_3 = RARITY_PACK_2 * 10; uint256 internal constant INTELLIGENCE_PACK_4 = EXPERIENCE_PACK_3 * 1000; uint256 internal constant AGILITY_PACK_5 = INTELLIGENCE_PACK_4 * 100; uint256 internal constant STRENGTH_PACK_6 = AGILITY_PACK_5 * 100; uint256 internal constant BASE_DAMAGE_PACK_7 = STRENGTH_PACK_6 * 100; uint256 internal constant PET_PACK_8 = BASE_DAMAGE_PACK_7 * 100; uint256 internal constant AURA_PACK_9 = PET_PACK_8 * 100; uint256 internal constant WARRIOR_ID_PACK_10 = AURA_PACK_9 * 100; uint256 internal constant PVP_CYCLE_PACK_11 = WARRIOR_ID_PACK_10 * 10**10; uint256 internal constant RATING_PACK_12 = PVP_CYCLE_PACK_11 * 10**10; uint256 internal constant PVP_BASE_PACK_13 = RATING_PACK_12 * 10**10;//NB rating must be at the END! //tournament data uint256 internal constant HP_PACK_0 = 1; uint256 internal constant DAMAGE_PACK_1 = HP_PACK_0 * 10**12; uint256 internal constant ARMOR_PACK_2 = DAMAGE_PACK_1 * 10**12; uint256 internal constant DODGE_PACK_3 = ARMOR_PACK_2 * 10**12; uint256 internal constant PENETRATION_PACK_4 = DODGE_PACK_3 * 10**12; uint256 internal constant COMBINE_BASE_PACK_5 = PENETRATION_PACK_4 * 10**12; /* MISC CONSTANTS */ uint256 internal constant MAX_ID_SIZE = 10000000000; int256 internal constant PRECISION = 1000000; uint256 internal constant BATTLES_PER_CONTENDER = 10;//10x100 uint256 internal constant BATTLES_PER_CONTENDER_SUM = BATTLES_PER_CONTENDER * 100;//10x100 uint256 internal constant LEVEL_BONUSES = 98898174676155504541373431282523211917151413121110; //ucommon bonuses uint256 internal constant BONUS_NONE = 0; uint256 internal constant BONUS_HP = 1; uint256 internal constant BONUS_ARMOR = 2; uint256 internal constant BONUS_CRIT_CHANCE = 3; uint256 internal constant BONUS_CRIT_MULT = 4; uint256 internal constant BONUS_PENETRATION = 5; //rare bonuses uint256 internal constant BONUS_STR = 6; uint256 internal constant BONUS_AGI = 7; uint256 internal constant BONUS_INT = 8; uint256 internal constant BONUS_DAMAGE = 9; //bonus value database, uint256 internal constant BONUS_DATA = 16060606140107152000; //pets database uint256 internal constant PETS_DATA = 287164235573728325842459981692000; uint256 internal constant PET_AURA = 2; uint256 internal constant PET_PARAM_1 = 1; uint256 internal constant PET_PARAM_2 = 0; /* GETTERS */ function getUniqueValue(uint256 identity) internal pure returns(uint256){ return identity % RARITY_MASK_1; } function getRarityValue(uint256 identity) internal pure returns(uint256){ return (identity % CLASS_VIEW_MASK_2) / RARITY_MASK_1; } function getClassViewValue(uint256 identity) internal pure returns(uint256){ return (identity % BODY_COLOR_MASK_3) / CLASS_VIEW_MASK_2; } function getBodyColorValue(uint256 identity) internal pure returns(uint256){ return (identity % EYES_MASK_4) / BODY_COLOR_MASK_3; } function getEyesValue(uint256 identity) internal pure returns(uint256){ return (identity % MOUTH_MASK_5) / EYES_MASK_4; } function getMouthValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_MASK_6) / MOUTH_MASK_5; } function getHairValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_COLOR_MASK_7) / HEIR_MASK_6; } function getHairColorValue(uint256 identity) internal pure returns(uint256){ return (identity % ARMOR_MASK_8) / HEIR_COLOR_MASK_7; } function getArmorValue(uint256 identity) internal pure returns(uint256){ return (identity % WEAPON_MASK_9) / ARMOR_MASK_8; } function getWeaponValue(uint256 identity) internal pure returns(uint256){ return (identity % HAT_MASK_10) / WEAPON_MASK_9; } function getHatValue(uint256 identity) internal pure returns(uint256){ return (identity % RUNES_MASK_11) / HAT_MASK_10; } function getRunesValue(uint256 identity) internal pure returns(uint256){ return (identity % WINGS_MASK_12) / RUNES_MASK_11; } function getWingsValue(uint256 identity) internal pure returns(uint256){ return (identity % PET_MASK_13) / WINGS_MASK_12; } function getPetValue(uint256 identity) internal pure returns(uint256){ return (identity % BORDER_MASK_14) / PET_MASK_13; } function getBorderValue(uint256 identity) internal pure returns(uint256){ return (identity % BACKGROUND_MASK_15) / BORDER_MASK_14; } function getBackgroundValue(uint256 identity) internal pure returns(uint256){ return (identity % INTELLIGENCE_MASK_16) / BACKGROUND_MASK_15; } function getIntelligenceValue(uint256 identity) internal pure returns(uint256){ return (identity % AGILITY_MASK_17) / INTELLIGENCE_MASK_16; } function getAgilityValue(uint256 identity) internal pure returns(uint256){ return ((identity % STRENGTH_MASK_18) / AGILITY_MASK_17); } function getStrengthValue(uint256 identity) internal pure returns(uint256){ return ((identity % CLASS_MECH_MASK_19) / STRENGTH_MASK_18); } function getClassMechValue(uint256 identity) internal pure returns(uint256){ return (identity % RARITY_BONUS_MASK_20) / CLASS_MECH_MASK_19; } function getRarityBonusValue(uint256 identity) internal pure returns(uint256){ return (identity % SPECIALITY_MASK_21) / RARITY_BONUS_MASK_20; } function getSpecialityValue(uint256 identity) internal pure returns(uint256){ return (identity % DAMAGE_MASK_22) / SPECIALITY_MASK_21; } function getDamageValue(uint256 identity) internal pure returns(uint256){ return (identity % AURA_MASK_23) / DAMAGE_MASK_22; } function getAuraValue(uint256 identity) internal pure returns(uint256){ return ((identity % BASE_MASK_24) / AURA_MASK_23); } /* SETTERS */ function _setUniqueValue0(uint256 value) internal pure returns(uint256){ require(value < RARITY_MASK_1); return value * UNIQUE_MASK_0; } function _setRarityValue1(uint256 value) internal pure returns(uint256){ require(value < (CLASS_VIEW_MASK_2 / RARITY_MASK_1)); return value * RARITY_MASK_1; } function _setClassViewValue2(uint256 value) internal pure returns(uint256){ require(value < (BODY_COLOR_MASK_3 / CLASS_VIEW_MASK_2)); return value * CLASS_VIEW_MASK_2; } function _setBodyColorValue3(uint256 value) internal pure returns(uint256){ require(value < (EYES_MASK_4 / BODY_COLOR_MASK_3)); return value * BODY_COLOR_MASK_3; } function _setEyesValue4(uint256 value) internal pure returns(uint256){ require(value < (MOUTH_MASK_5 / EYES_MASK_4)); return value * EYES_MASK_4; } function _setMouthValue5(uint256 value) internal pure returns(uint256){ require(value < (HEIR_MASK_6 / MOUTH_MASK_5)); return value * MOUTH_MASK_5; } function _setHairValue6(uint256 value) internal pure returns(uint256){ require(value < (HEIR_COLOR_MASK_7 / HEIR_MASK_6)); return value * HEIR_MASK_6; } function _setHairColorValue7(uint256 value) internal pure returns(uint256){ require(value < (ARMOR_MASK_8 / HEIR_COLOR_MASK_7)); return value * HEIR_COLOR_MASK_7; } function _setArmorValue8(uint256 value) internal pure returns(uint256){ require(value < (WEAPON_MASK_9 / ARMOR_MASK_8)); return value * ARMOR_MASK_8; } function _setWeaponValue9(uint256 value) internal pure returns(uint256){ require(value < (HAT_MASK_10 / WEAPON_MASK_9)); return value * WEAPON_MASK_9; } function _setHatValue10(uint256 value) internal pure returns(uint256){ require(value < (RUNES_MASK_11 / HAT_MASK_10)); return value * HAT_MASK_10; } function _setRunesValue11(uint256 value) internal pure returns(uint256){ require(value < (WINGS_MASK_12 / RUNES_MASK_11)); return value * RUNES_MASK_11; } function _setWingsValue12(uint256 value) internal pure returns(uint256){ require(value < (PET_MASK_13 / WINGS_MASK_12)); return value * WINGS_MASK_12; } function _setPetValue13(uint256 value) internal pure returns(uint256){ require(value < (BORDER_MASK_14 / PET_MASK_13)); return value * PET_MASK_13; } function _setBorderValue14(uint256 value) internal pure returns(uint256){ require(value < (BACKGROUND_MASK_15 / BORDER_MASK_14)); return value * BORDER_MASK_14; } function _setBackgroundValue15(uint256 value) internal pure returns(uint256){ require(value < (INTELLIGENCE_MASK_16 / BACKGROUND_MASK_15)); return value * BACKGROUND_MASK_15; } function _setIntelligenceValue16(uint256 value) internal pure returns(uint256){ require(value < (AGILITY_MASK_17 / INTELLIGENCE_MASK_16)); return value * INTELLIGENCE_MASK_16; } function _setAgilityValue17(uint256 value) internal pure returns(uint256){ require(value < (STRENGTH_MASK_18 / AGILITY_MASK_17)); return value * AGILITY_MASK_17; } function _setStrengthValue18(uint256 value) internal pure returns(uint256){ require(value < (CLASS_MECH_MASK_19 / STRENGTH_MASK_18)); return value * STRENGTH_MASK_18; } function _setClassMechValue19(uint256 value) internal pure returns(uint256){ require(value < (RARITY_BONUS_MASK_20 / CLASS_MECH_MASK_19)); return value * CLASS_MECH_MASK_19; } function _setRarityBonusValue20(uint256 value) internal pure returns(uint256){ require(value < (SPECIALITY_MASK_21 / RARITY_BONUS_MASK_20)); return value * RARITY_BONUS_MASK_20; } function _setSpecialityValue21(uint256 value) internal pure returns(uint256){ require(value < (DAMAGE_MASK_22 / SPECIALITY_MASK_21)); return value * SPECIALITY_MASK_21; } function _setDamgeValue22(uint256 value) internal pure returns(uint256){ require(value < (AURA_MASK_23 / DAMAGE_MASK_22)); return value * DAMAGE_MASK_22; } function _setAuraValue23(uint256 value) internal pure returns(uint256){ require(value < (BASE_MASK_24 / AURA_MASK_23)); return value * AURA_MASK_23; } /* WARRIOR IDENTITY GENERATION */ function _computeRunes(uint256 _rarity) internal pure returns (uint256){ return _rarity > UNCOMMON ? _rarity - UNCOMMON : 0;// 1 + _random(0, max, hash, WINGS_MASK_12, RUNES_MASK_11) : 0; } function _computeWings(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > RARE ? 1 + _random(0, max, hash, PET_MASK_13, WINGS_MASK_12) : 0; } function _computePet(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > MYTHIC ? 1 + _random(0, max, hash, BORDER_MASK_14, PET_MASK_13) : 0; } function _computeBorder(uint256 _rarity) internal pure returns (uint256){ return _rarity >= COMMON ? _rarity - 1 : 0; } function _computeBackground(uint256 _rarity) internal pure returns (uint256){ return _rarity; } function _unpackPetData(uint256 index) internal pure returns(uint256){ return (PETS_DATA % (1000 ** (index + 1)) / (1000 ** index)); } function _getPetBonus1(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_1 + 1)) / (10 ** PET_PARAM_1)); } function _getPetBonus2(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_2 + 1)) / (10 ** PET_PARAM_2)); } function _getPetAura(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_AURA + 1)) / (10 ** PET_AURA)); } function _getBattleBonus(uint256 _setBonusIndex, uint256 _currentBonusIndex, uint256 _petData, uint256 _warriorAuras, uint256 _petAuras) internal pure returns(int256) { int256 bonus = 0; if (_setBonusIndex == _currentBonusIndex) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } //add pet bonuses if (_setBonusIndex == _getPetBonus1(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } if (_setBonusIndex == _getPetBonus2(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add warrior aura bonuses if (isAuraSet(_warriorAuras, uint8(_setBonusIndex))) {//warriors receive half bonuses from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add pet aura bonuses if (isAuraSet(_petAuras, uint8(_setBonusIndex))) {//pets receive full bonues from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } return bonus; } function _computeRarityBonus(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity == UNCOMMON) { return 1 + _random(0, BONUS_PENETRATION, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity == RARE) { return 1 + _random(BONUS_PENETRATION, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } return BONUS_NONE; } function _computeAura(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, BASE_MASK_24, AURA_MASK_23); } return BONUS_NONE; } function _computeRarity(uint256 _reward, uint256 _unique, uint256 _legendary, uint256 _mythic, uint256 _rare, uint256 _uncommon) internal pure returns(uint256){ uint256 range = _unique + _legendary + _mythic + _rare + _uncommon; if (_reward >= range) return COMMON; // common if (_reward >= (range = (range - _uncommon))) return UNCOMMON; if (_reward >= (range = (range - _rare))) return RARE; if (_reward >= (range = (range - _mythic))) return MYTHIC; if (_reward >= (range = (range - _legendary))) return LEGENDARY; if (_reward < range) return UNIQUE; return COMMON; } function _computeUniqueness(uint256 _rarity, uint256 nextUnique) internal pure returns (uint256){ return _rarity == UNIQUE ? nextUnique : 0; } /* identity packing */ /* @returns bonus value which depends on speciality value, * if speciality == 1 (miner), then bonus value will be equal 4, * otherwise 1 */ function _getBonus(uint256 identity) internal pure returns(uint256){ return getSpecialityValue(identity) == MINER_PERK ? 4 : 1; } function _computeAndSetBaseParameters16_18_22(uint256 _hash) internal pure returns (uint256, uint256){ uint256 identity = 0; uint256 damage = 35 + _random(0, 21, _hash, AURA_MASK_23, DAMAGE_MASK_22); uint256 strength = 45 + _random(0, 26, _hash, CLASS_MECH_MASK_19, STRENGTH_MASK_18); uint256 agility = 15 + (125 - damage - strength); uint256 intelligence = 155 - strength - agility - damage; (strength, agility, intelligence) = _shuffleParams(strength, agility, intelligence, _hash); identity += _setStrengthValue18(strength); identity += _setAgilityValue17(agility); identity += _setIntelligenceValue16(intelligence); identity += _setDamgeValue22(damage); uint256 classMech = strength > agility ? (strength > intelligence ? WARRIOR : MAGE) : (agility > intelligence ? ARCHER : MAGE); return (identity, classMech); } function _shuffleParams(uint256 param1, uint256 param2, uint256 param3, uint256 _hash) internal pure returns(uint256, uint256, uint256) { uint256 temp = param1; if (_hash % 2 == 0) { temp = param1; param1 = param2; param2 = temp; } if ((_hash / 10 % 2) == 0) { temp = param2; param2 = param3; param3 = temp; } if ((_hash / 100 % 2) == 0) { temp = param1; param1 = param2; param2 = temp; } return (param1, param2, param3); } /* RANDOM */ function _random(uint256 _min, uint256 _max, uint256 _hash, uint256 _reminder, uint256 _devider) internal pure returns (uint256){ return ((_hash % _reminder) / _devider) % (_max - _min) + _min; } function _random(uint256 _min, uint256 _max, uint256 _hash) internal pure returns (uint256){ return _hash % (_max - _min) + _min; } function _getTargetBlock(uint256 _targetBlock) internal view returns(uint256){ uint256 currentBlock = block.number; uint256 target = currentBlock - (currentBlock % 256) + (_targetBlock % 256); if (target >= currentBlock) { return (target - 256); } return target; } function _getMaxRarityChance() internal pure returns(uint256){ return RARITY_CHANCE_RANGE; } function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 specialPerc, uint32[19] memory params) internal view returns (uint256) { _targetBlock = _getTargetBlock(_targetBlock); uint256 identity; uint256 hash = uint256(keccak256(block.blockhash(_targetBlock), _heroIdentity, block.coinbase, block.difficulty)); //0 _heroLevel produces warriors of COMMON rarity uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE : _random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000 uint256 rarity = _computeRarity(rarityChance, params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]); uint256 classMech; // start (identity, classMech) = _computeAndSetBaseParameters16_18_22(hash); identity += _setUniqueValue0(_computeUniqueness(rarity, params[UNIQUE_TOTAL_INDEX_18] + 1)); identity += _setRarityValue1(rarity); identity += _setClassViewValue2(classMech); // 1 to 1 with classMech identity += _setBodyColorValue3(1 + _random(0, params[BODY_COLOR_MAX_INDEX_0], hash, EYES_MASK_4, BODY_COLOR_MASK_3)); identity += _setEyesValue4(1 + _random(0, params[EYES_MAX_INDEX_1], hash, MOUTH_MASK_5, EYES_MASK_4)); identity += _setMouthValue5(1 + _random(0, params[MOUTH_MAX_2], hash, HEIR_MASK_6, MOUTH_MASK_5)); identity += _setHairValue6(1 + _random(0, params[HAIR_MAX_3], hash, HEIR_COLOR_MASK_7, HEIR_MASK_6)); identity += _setHairColorValue7(1 + _random(0, params[HEIR_COLOR_MAX_4], hash, ARMOR_MASK_8, HEIR_COLOR_MASK_7)); identity += _setArmorValue8(1 + _random(0, params[ARMOR_MAX_5], hash, WEAPON_MASK_9, ARMOR_MASK_8)); identity += _setWeaponValue9(1 + _random(0, params[WEAPON_MAX_6], hash, HAT_MASK_10, WEAPON_MASK_9)); identity += _setHatValue10(_random(0, params[HAT_MAX_7], hash, RUNES_MASK_11, HAT_MASK_10));//removed +1 identity += _setRunesValue11(_computeRunes(rarity)); identity += _setWingsValue12(_computeWings(rarity, params[WINGS_MAX_9], hash)); identity += _setPetValue13(_computePet(rarity, params[PET_MAX_10], hash)); identity += _setBorderValue14(_computeBorder(rarity)); // 1 to 1 with rarity identity += _setBackgroundValue15(_computeBackground(rarity)); // 1 to 1 with rarity identity += _setClassMechValue19(classMech); identity += _setRarityBonusValue20(_computeRarityBonus(rarity, hash)); identity += _setSpecialityValue21(specialPerc); // currently only miner (1) identity += _setAuraValue23(_computeAura(rarity, hash)); // end return identity; } function _changeParameter(uint256 _paramIndex, uint32 _value, uint32[19] storage parameters) internal { //we can change only view parameters, and unique count in max range <= 100 require(_paramIndex >= BODY_COLOR_MAX_INDEX_0 && _paramIndex <= UNIQUE_INDEX_13); //we can NOT set pet, border and background values, //those values have special logic behind them require( _paramIndex != RUNES_MAX_8 && _paramIndex != PET_MAX_10 && _paramIndex != BORDER_MAX_11 && _paramIndex != BACKGROUND_MAX_12 ); //value of bodyColor, eyes, mouth, hair, hairColor, armor, weapon, hat must be < 1000 require(_paramIndex > HAT_MAX_7 || _value < 1000); //value of wings, must be < 100 require(_paramIndex > BACKGROUND_MAX_12 || _value < 100); //check that max total number of UNIQUE warriors that we can emit is not > 100 require(_paramIndex != UNIQUE_INDEX_13 || (_value + parameters[UNIQUE_TOTAL_INDEX_18]) <= 100); parameters[_paramIndex] = _value; } function _recordWarriorData(uint256 identity, uint32[19] storage parameters) internal { uint256 rarity = getRarityValue(identity); if (rarity == UNCOMMON) { // uncommon parameters[UNCOMMON_INDEX_17]--; return; } if (rarity == RARE) { // rare parameters[RARE_INDEX_16]--; return; } if (rarity == MYTHIC) { // mythic parameters[MYTHIC_INDEX_15]--; return; } if (rarity == LEGENDARY) { // legendary parameters[LEGENDARY_INDEX_14]--; return; } if (rarity == UNIQUE) { // unique parameters[UNIQUE_INDEX_13]--; parameters[UNIQUE_TOTAL_INDEX_18] ++; return; } } function _validateIdentity(uint256 _identity, uint32[19] memory params) internal pure returns(bool){ uint256 rarity = getRarityValue(_identity); require(rarity <= UNIQUE); require( rarity <= COMMON ||//common (rarity == UNCOMMON && params[UNCOMMON_INDEX_17] > 0) ||//uncommon (rarity == RARE && params[RARE_INDEX_16] > 0) ||//rare (rarity == MYTHIC && params[MYTHIC_INDEX_15] > 0) ||//mythic (rarity == LEGENDARY && params[LEGENDARY_INDEX_14] > 0) ||//legendary (rarity == UNIQUE && params[UNIQUE_INDEX_13] > 0)//unique ); require(rarity != UNIQUE || getUniqueValue(_identity) > params[UNIQUE_TOTAL_INDEX_18]); //check battle parameters require( getStrengthValue(_identity) < 100 && getAgilityValue(_identity) < 100 && getIntelligenceValue(_identity) < 100 && getDamageValue(_identity) <= 55 ); require(getClassMechValue(_identity) <= MAGE); require(getClassMechValue(_identity) == getClassViewValue(_identity)); require(getSpecialityValue(_identity) <= MINER_PERK); require(getRarityBonusValue(_identity) <= BONUS_DAMAGE); require(getAuraValue(_identity) <= BONUS_DAMAGE); //check view require(getBodyColorValue(_identity) <= params[BODY_COLOR_MAX_INDEX_0]); require(getEyesValue(_identity) <= params[EYES_MAX_INDEX_1]); require(getMouthValue(_identity) <= params[MOUTH_MAX_2]); require(getHairValue(_identity) <= params[HAIR_MAX_3]); require(getHairColorValue(_identity) <= params[HEIR_COLOR_MAX_4]); require(getArmorValue(_identity) <= params[ARMOR_MAX_5]); require(getWeaponValue(_identity) <= params[WEAPON_MAX_6]); require(getHatValue(_identity) <= params[HAT_MAX_7]); require(getRunesValue(_identity) <= params[RUNES_MAX_8]); require(getWingsValue(_identity) <= params[WINGS_MAX_9]); require(getPetValue(_identity) <= params[PET_MAX_10]); require(getBorderValue(_identity) <= params[BORDER_MAX_11]); require(getBackgroundValue(_identity) <= params[BACKGROUND_MAX_12]); return true; } /* UNPACK METHODS */ //common function _unpackClassValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / CLASS_PACK_0); } function _unpackRarityBonusValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / RARITY_BONUS_PACK_1); } function _unpackRarityValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % EXPERIENCE_PACK_3 / RARITY_PACK_2); } function _unpackExpValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4 / EXPERIENCE_PACK_3); } function _unpackLevelValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4) / (EXPERIENCE_PACK_3 * POINTS_TO_LEVEL); } function _unpackIntelligenceValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % AGILITY_PACK_5 / INTELLIGENCE_PACK_4); } function _unpackAgilityValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % STRENGTH_PACK_6 / AGILITY_PACK_5); } function _unpackStrengthValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % BASE_DAMAGE_PACK_7 / STRENGTH_PACK_6); } function _unpackBaseDamageValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % PET_PACK_8 / BASE_DAMAGE_PACK_7); } function _unpackPetValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % AURA_PACK_9 / PET_PACK_8); } function _unpackAuraValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % WARRIOR_ID_PACK_10 / AURA_PACK_9); } // //pvp unpack function _unpackIdValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_CYCLE_PACK_11 / WARRIOR_ID_PACK_10); } function _unpackCycleValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RATING_PACK_12 / PVP_CYCLE_PACK_11); } function _unpackRatingValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_BASE_PACK_13 / RATING_PACK_12); } //max cycle skip value cant be more than 1000000000 function _changeCycleValue(uint256 packedValue, uint256 newValue) internal pure returns(uint256){ newValue = newValue > 1000000000 ? 1000000000 : newValue; return packedValue - (_unpackCycleValue(packedValue) * PVP_CYCLE_PACK_11) + newValue * PVP_CYCLE_PACK_11; } function _packWarriorCommonData(uint256 _identity, uint256 _experience) internal pure returns(uint256){ uint256 packedData = 0; packedData += getClassMechValue(_identity) * CLASS_PACK_0; packedData += getRarityBonusValue(_identity) * RARITY_BONUS_PACK_1; packedData += getRarityValue(_identity) * RARITY_PACK_2; packedData += _experience * EXPERIENCE_PACK_3; packedData += getIntelligenceValue(_identity) * INTELLIGENCE_PACK_4; packedData += getAgilityValue(_identity) * AGILITY_PACK_5; packedData += getStrengthValue(_identity) * STRENGTH_PACK_6; packedData += getDamageValue(_identity) * BASE_DAMAGE_PACK_7; packedData += getPetValue(_identity) * PET_PACK_8; return packedData; } function _packWarriorPvpData(uint256 _identity, uint256 _rating, uint256 _pvpCycle, uint256 _warriorId, uint256 _experience) internal pure returns(uint256){ uint256 packedData = _packWarriorCommonData(_identity, _experience); packedData += _warriorId * WARRIOR_ID_PACK_10; packedData += _pvpCycle * PVP_CYCLE_PACK_11; //rating MUST have most significant value! packedData += _rating * RATING_PACK_12; return packedData; } /* TOURNAMENT BATTLES */ function _packWarriorIds(uint256[] memory packedWarriors) internal pure returns(uint256){ uint256 packedIds = 0; uint256 length = packedWarriors.length; for(uint256 i = 0; i < length; i ++) { packedIds += (MAX_ID_SIZE ** i) * _unpackIdValue(packedWarriors[i]); } return packedIds; } function _unpackWarriorId(uint256 packedIds, uint256 index) internal pure returns(uint256){ return (packedIds % (MAX_ID_SIZE ** (index + 1)) / (MAX_ID_SIZE ** index)); } function _packCombinedParams(int256 hp, int256 damage, int256 armor, int256 dodge, int256 penetration) internal pure returns(uint256) { uint256 combinedWarrior = 0; combinedWarrior += uint256(hp) * HP_PACK_0; combinedWarrior += uint256(damage) * DAMAGE_PACK_1; combinedWarrior += uint256(armor) * ARMOR_PACK_2; combinedWarrior += uint256(dodge) * DODGE_PACK_3; combinedWarrior += uint256(penetration) * PENETRATION_PACK_4; return combinedWarrior; } function _unpackProtectionParams(uint256 combinedWarrior) internal pure returns (int256 hp, int256 armor, int256 dodge){ hp = int256(combinedWarrior % DAMAGE_PACK_1 / HP_PACK_0); armor = int256(combinedWarrior % DODGE_PACK_3 / ARMOR_PACK_2); dodge = int256(combinedWarrior % PENETRATION_PACK_4 / DODGE_PACK_3); } function _unpackAttackParams(uint256 combinedWarrior) internal pure returns(int256 damage, int256 penetration) { damage = int256(combinedWarrior % ARMOR_PACK_2 / DAMAGE_PACK_1); penetration = int256(combinedWarrior % COMBINE_BASE_PACK_5 / PENETRATION_PACK_4); } function _combineWarriors(uint256[] memory packedWarriors) internal pure returns (uint256) { int256 hp; int256 damage; int256 armor; int256 dodge; int256 penetration; (hp, damage, armor, dodge, penetration) = _computeCombinedParams(packedWarriors); return _packCombinedParams(hp, damage, armor, dodge, penetration); } function _computeCombinedParams(uint256[] memory packedWarriors) internal pure returns (int256 totalHp, int256 totalDamage, int256 maxArmor, int256 maxDodge, int256 maxPenetration){ uint256 length = packedWarriors.length; int256 hp; int256 armor; int256 dodge; int256 penetration; uint256 warriorAuras; uint256 petAuras; (warriorAuras, petAuras) = _getAurasData(packedWarriors); uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; totalDamage += getDamage(packedWarrior, warriorAuras, petAuras); penetration = getPenetration(packedWarrior, warriorAuras, petAuras); maxPenetration = maxPenetration > penetration ? maxPenetration : penetration; (hp, armor, dodge) = _getProtectionParams(packedWarrior, warriorAuras, petAuras); totalHp += hp; maxArmor = maxArmor > armor ? maxArmor : armor; maxDodge = maxDodge > dodge ? maxDodge : dodge; } } function _getAurasData(uint256[] memory packedWarriors) internal pure returns(uint256 warriorAuras, uint256 petAuras) { uint256 length = packedWarriors.length; warriorAuras = 0; petAuras = 0; uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; warriorAuras = enableAura(warriorAuras, (_unpackAuraValue(packedWarrior))); petAuras = enableAura(petAuras, (_getPetAura(_unpackPetData(_unpackPetValue(packedWarrior))))); } warriorAuras = filterWarriorAuras(warriorAuras, petAuras); return (warriorAuras, petAuras); } // Get bit value at position function isAuraSet(uint256 aura, uint256 auraIndex) internal pure returns (bool) { return aura & (uint256(0x01) << auraIndex) != 0; } // Set bit value at position function enableAura(uint256 a, uint256 n) internal pure returns (uint256) { return a | (uint256(0x01) << n); } //switch off warrior auras that are enabled in pets auras, pet aura have priority function filterWarriorAuras(uint256 _warriorAuras, uint256 _petAuras) internal pure returns(uint256) { return (_warriorAuras & _petAuras) ^ _warriorAuras; } function _getTournamentBattles(uint256 _numberOfContenders) internal pure returns(uint256) { return (_numberOfContenders * BATTLES_PER_CONTENDER / 2); } function getTournamentBattleResults(uint256[] memory combinedWarriors, uint256 _targetBlock) internal view returns (uint32[] memory results){ uint256 length = combinedWarriors.length; results = new uint32[](length); int256 damage1; int256 penetration1; uint256 hash; uint256 randomIndex; uint256 exp = 0; uint256 i; uint256 result; for(i = 0; i < length; i ++) { (damage1, penetration1) = _unpackAttackParams(combinedWarriors[i]); while(results[i] < BATTLES_PER_CONTENDER_SUM) { //if we just started generate new random source //or regenerate if we used all data from it if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock - i)), uint256(damage1) + now)); exp = 0; } //we do not fight with self if there are other warriors randomIndex = (_random(i + 1 < length ? i + 1 : i, length, hash, 1000 * 10**exp, 10**exp)); result = getTournamentBattleResult(damage1, penetration1, combinedWarriors[i], combinedWarriors[randomIndex], hash % (1000 * 10**exp) / 10**exp); results[result == 1 ? i : randomIndex] += 101;//icrement battle count 100 and +1 win results[result == 1 ? randomIndex : i] += 100;//increment only battle count 100 for loser if (results[randomIndex] >= BATTLES_PER_CONTENDER_SUM) { if (randomIndex < length - 1) { _swapValues(combinedWarriors, results, randomIndex, length - 1); } length --; } exp++; } } //filter battle count from results length = combinedWarriors.length; for(i = 0; i < length; i ++) { results[i] = results[i] % 100; } return results; } function _swapValues(uint256[] memory combinedWarriors, uint32[] memory results, uint256 id1, uint256 id2) internal pure { uint256 temp = combinedWarriors[id1]; combinedWarriors[id1] = combinedWarriors[id2]; combinedWarriors[id2] = temp; temp = results[id1]; results[id1] = results[id2]; results[id2] = uint32(temp); } function getTournamentBattleResult(int256 damage1, int256 penetration1, uint256 combinedWarrior1, uint256 combinedWarrior2, uint256 randomSource) internal pure returns (uint256) { int256 damage2; int256 penetration2; (damage2, penetration2) = _unpackAttackParams(combinedWarrior1); int256 totalHp1 = getCombinedTotalHP(combinedWarrior1, penetration2); int256 totalHp2 = getCombinedTotalHP(combinedWarrior2, penetration1); return _getBattleResult(damage1 * getBattleRandom(randomSource, 1) / 100, damage2 * getBattleRandom(randomSource, 10) / 100, totalHp1, totalHp2, randomSource); } /* COMMON BATTLE */ function _getBattleResult(int256 damage1, int256 damage2, int256 totalHp1, int256 totalHp2, uint256 randomSource) internal pure returns (uint256){ totalHp1 = (totalHp1 * (PRECISION * PRECISION) / damage2); totalHp2 = (totalHp2 * (PRECISION * PRECISION) / damage1); //if draw, let the coin decide who wins if (totalHp1 == totalHp2) return randomSource % 2 + 1; return totalHp1 > totalHp2 ? 1 : 2; } function getCombinedTotalHP(uint256 combinedData, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _unpackProtectionParams(combinedData); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function getTotalHP(uint256 packedData, uint256 warriorAuras, uint256 petAuras, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _getProtectionParams(packedData, warriorAuras, petAuras); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function _getTotalHp(int256 hp, int256 armor, int256 dodge, int256 enemyPenetration) internal pure returns(int256) { int256 piercingResult = (armor - enemyPenetration) < -(75 * PRECISION) ? -(75 * PRECISION) : (armor - enemyPenetration); int256 mitigation = (PRECISION - piercingResult * PRECISION / (PRECISION + piercingResult / 100) / 100); return (hp * PRECISION / mitigation + (hp * dodge / (100 * PRECISION))); } function _applyLevelBonus(int256 _value, uint256 _level) internal pure returns(int256) { _level -= 1; return int256(uint256(_value) * (LEVEL_BONUSES % (100 ** (_level + 1)) / (100 ** _level)) / 10); } function _getProtectionParams(uint256 packedData, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256 hp, int256 armor, int256 dodge) { uint256 rarityBonus = _unpackRarityBonusValue(packedData); uint256 petData = _unpackPetData(_unpackPetValue(packedData)); int256 strength = _unpackStrengthValue(packedData) * PRECISION + _getBattleBonus(BONUS_STR, rarityBonus, petData, warriorAuras, petAuras); int256 agility = _unpackAgilityValue(packedData) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); hp = 100 * PRECISION + strength + 7 * strength / 10 + _getBattleBonus(BONUS_HP, rarityBonus, petData, warriorAuras, petAuras);//add bonus hp hp = _applyLevelBonus(hp, _unpackLevelValue(packedData)); armor = (strength + 8 * strength / 10 + agility + _getBattleBonus(BONUS_ARMOR, rarityBonus, petData, warriorAuras, petAuras));//add bonus armor dodge = (2 * agility / 3); } function getDamage(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); int256 crit = (agility / 5 + intelligence / 4) + _getBattleBonus(BONUS_CRIT_CHANCE, rarityBonus, petData, warriorAuras, petAuras); int256 critMultiplier = (PRECISION + intelligence / 25) + _getBattleBonus(BONUS_CRIT_MULT, rarityBonus, petData, warriorAuras, petAuras); int256 damage = int256(_unpackBaseDamageValue(packedWarrior) * 3 * PRECISION / 2) + _getBattleBonus(BONUS_DAMAGE, rarityBonus, petData, warriorAuras, petAuras); return (_applyLevelBonus(damage, _unpackLevelValue(packedWarrior)) * (PRECISION + crit * critMultiplier / (100 * PRECISION))) / PRECISION; } function getPenetration(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); return (intelligence * 2 + agility + _getBattleBonus(BONUS_PENETRATION, rarityBonus, petData, warriorAuras, petAuras)); } /* BATTLE PVP */ //@param randomSource must be >= 1000 function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){ return int256(100 + _random(0, 11, randmSource, 100 * _step, _step)); } uint256 internal constant NO_AURA = 0; function getPVPBattleResult(uint256 packedData1, uint256 packedData2, uint256 randmSource) internal pure returns (uint256){ uint256 petAura1 = _computePVPPetAura(packedData1); uint256 petAura2 = _computePVPPetAura(packedData2); uint256 warriorAura1 = _computePVPWarriorAura(packedData1, petAura1); uint256 warriorAura2 = _computePVPWarriorAura(packedData2, petAura2); int256 damage1 = getDamage(packedData1, warriorAura1, petAura1) * getBattleRandom(randmSource, 1) / 100; int256 damage2 = getDamage(packedData2, warriorAura2, petAura2) * getBattleRandom(randmSource, 10) / 100; int256 totalHp1; int256 totalHp2; (totalHp1, totalHp2) = _computeContendersTotalHp(packedData1, warriorAura1, petAura1, packedData2, warriorAura1, petAura1); return _getBattleResult(damage1, damage2, totalHp1, totalHp2, randmSource); } function _computePVPPetAura(uint256 packedData) internal pure returns(uint256) { return enableAura(NO_AURA, _getPetAura(_unpackPetData(_unpackPetValue(packedData)))); } function _computePVPWarriorAura(uint256 packedData, uint256 petAuras) internal pure returns(uint256) { return filterWarriorAuras(enableAura(NO_AURA, _unpackAuraValue(packedData)), petAuras); } function _computeContendersTotalHp(uint256 packedData1, uint256 warriorAura1, uint256 petAura1, uint256 packedData2, uint256 warriorAura2, uint256 petAura2) internal pure returns(int256 totalHp1, int256 totalHp2) { int256 enemyPenetration = getPenetration(packedData2, warriorAura2, petAura2); totalHp1 = getTotalHP(packedData1, warriorAura1, petAura1, enemyPenetration); enemyPenetration = getPenetration(packedData1, warriorAura1, petAura1); totalHp2 = getTotalHP(packedData2, warriorAura1, petAura1, enemyPenetration); } function getRatingRange(uint256 _pvpCycle, uint256 _pvpInterval, uint256 _expandInterval) internal pure returns (uint256){ return 50 + (_pvpCycle * _pvpInterval / _expandInterval * 25); } function isMatching(int256 evenRating, int256 oddRating, int256 ratingGap) internal pure returns(bool) { return evenRating <= (oddRating + ratingGap) && evenRating >= (oddRating - ratingGap); } function sort(uint256[] memory data) internal pure { quickSort(data, int(0), int(data.length - 1)); } function quickSort(uint256[] memory arr, int256 left, int256 right) internal pure { int256 i = left; int256 j = right; if(i==j) return; uint256 pivot = arr[uint256(left + (right - left) / 2)]; while (i <= j) { while (arr[uint256(i)] < pivot) i++; while (pivot < arr[uint256(j)]) j--; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } function _swapPair(uint256[] memory matchingIds, uint256 id1, uint256 id2, uint256 id3, uint256 id4) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; temp = matchingIds[id3]; matchingIds[id3] = matchingIds[id4]; matchingIds[id4] = temp; } function _swapValues(uint256[] memory matchingIds, uint256 id1, uint256 id2) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; } function _getMatchingIds(uint256[] memory matchingIds, uint256 _pvpInterval, uint256 _skipCycles, uint256 _expandInterval) internal pure returns(uint256 matchingCount) { matchingCount = matchingIds.length; if (matchingCount == 0) return 0; uint256 warriorId; uint256 index; //sort matching ids quickSort(matchingIds, int256(0), int256(matchingCount - 1)); //find pairs int256 rating1; uint256 pairIndex = 0; int256 ratingRange; for(index = 0; index < matchingCount; index++) { //get packed value warriorId = matchingIds[index]; //unpack rating 1 rating1 = int256(_unpackRatingValue(warriorId)); ratingRange = int256(getRatingRange(_unpackCycleValue(warriorId) + _skipCycles, _pvpInterval, _expandInterval)); if (index > pairIndex && //check left neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index - 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index - 1, pairIndex + 1, index); //mark last pair position pairIndex += 2; } else if (index + 1 < matchingCount && //check right neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index + 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index, pairIndex + 1, index + 1); //mark last pair position pairIndex += 2; //skip next iteration index++; } } matchingCount = pairIndex; } function _getPVPBattleResults(uint256[] memory matchingIds, uint256 matchingCount, uint256 _targetBlock) internal view { uint256 exp = 0; uint256 hash = 0; uint256 result = 0; for (uint256 even = 0; even < matchingCount; even += 2) { if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock)), hash)); exp = 0; } //compute battle result 1 = even(left) id won, 2 - odd(right) id won result = getPVPBattleResult(matchingIds[even], matchingIds[even + 1], hash % (1000 * 10**exp) / 10**exp); require(result > 0 && result < 3); exp++; //if odd warrior won, swap his id with even warrior, //otherwise do nothing, //even ids are winning ids! odds suck! if (result == 2) { _swapValues(matchingIds, even, even + 1); } } } function _getLevel(uint256 _levelPoints) internal pure returns(uint256) { return _levelPoints / POINTS_TO_LEVEL; } } library DataTypes { // / @dev The main Warrior struct. Every warrior in CryptoWarriors is represented by a copy // / of this structure, so great care was taken to ensure that it fits neatly into // / exactly two 256-bit words. Note that the order of the members in this structure // / is important because of the byte-packing rules used by Ethereum. // / Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Warrior{ // The Warrior's identity code is packed into these 256-bits uint256 identity; uint64 cooldownEndBlock; /** every warriors starts from 1 lv (10 level points per level) */ uint64 level; /** PVP rating, every warrior starts with 100 rating */ int64 rating; // 0 - idle uint32 action; /** Set to the index in the levelRequirements array (see CryptoWarriorBase.levelRequirements) that represents * the current dungeon level requirement for warrior. This starts at zero. */ uint32 dungeonIndex; } } contract CryptoWarriorBase is PermissionControll, PVPListenerInterface { /*** EVENTS ***/ /// @dev The Arise event is fired whenever a new warrior comes into existence. This obviously /// includes any time a warrior is created through the ariseWarrior method, but it is also called /// when a new miner warrior is created. event Arise(address owner, uint256 warriorId, uint256 identity); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a warrior /// ownership is assigned, including dungeon rewards. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ uint256 public constant IDLE = 0; uint256 public constant PVE_BATTLE = 1; uint256 public constant PVP_BATTLE = 2; uint256 public constant TOURNAMENT_BATTLE = 3; //max pve dungeon level uint256 public constant MAX_LEVEL = 25; //how many points is needed to get 1 level uint256 public constant POINTS_TO_LEVEL = 10; /// @dev A lookup table contains PVE dungeon level requirements, each time warrior /// completes dungeon, next level requirement is set, until 25lv (250points) is reached. uint32[6] public dungeonRequirements = [ uint32(10), uint32(30), uint32(60), uint32(100), uint32(150), uint32(250) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Warrior struct for all Warriors in existence. The ID /// of each warrior is actually an index of this array. DataTypes.Warrior[] warriors; /// @dev A mapping from warrior IDs to the address that owns them. All warriors have /// some valid owner address, even miner warriors are created with a non-zero owner. mapping (uint256 => address) public warriorToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownersTokenCount; /// @dev A mapping from warrior IDs to an address that has been approved to call /// transferFrom(). Each Warrior can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public warriorToApproved; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; /// @dev The address of the ClockAuction contract that handles sales of warriors. This /// same contract handles both peer-to-peer sales as well as the miner sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev Assigns ownership of a specific warrior to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // When creating new warriors _from is 0x0, but we can't account that address. if (_from != address(0)) { _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); } _addTokenTo(_to, _tokenId); // Emit the transfer event. Transfer(_from, _to, _tokenId); } function _addTokenTo(address _to, uint256 _tokenId) internal { // Since the number of warriors is capped to '1 000 000' we can't overflow this ownersTokenCount[_to]++; // transfer ownership warriorToOwner[_tokenId] = _to; uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function _removeTokenFrom(address _from, uint256 _tokenId) internal { // ownersTokenCount[_from]--; warriorToOwner[_tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length - 1; uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } function _clearApproval(uint256 _tokenId) internal { if (warriorToApproved[_tokenId] != address(0)) { // clear any previously approved ownership exchange warriorToApproved[_tokenId] = address(0); } } function _createWarrior(uint256 _identity, address _owner, uint256 _cooldown, uint256 _level, uint256 _rating, uint256 _dungeonIndex) internal returns (uint256) { DataTypes.Warrior memory _warrior = DataTypes.Warrior({ identity : _identity, cooldownEndBlock : uint64(_cooldown), level : uint64(_level),//uint64(10), rating : int64(_rating),//int64(100), action : uint32(IDLE), dungeonIndex : uint32(_dungeonIndex)//uint32(0) }); uint256 newWarriorId = warriors.push(_warrior) - 1; // let's just be 100% sure we never let this happen. require(newWarriorId == uint256(uint32(newWarriorId))); // emit the arise event Arise(_owner, newWarriorId, _identity); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newWarriorId); return newWarriorId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; } } contract WarriorTokenImpl is CryptoWarriorBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoWarriors"; string public constant symbol = "CW"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9f40b779)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /** @dev Checks if a given address is the current owner of the specified Warrior tokenId. * @param _claimant the address we are validating against. * @param _tokenId warrior id */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) && warriorToOwner[_tokenId] == _claimant; } function _ownerApproved(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) &&//0 address means token is burned warriorToOwner[_tokenId] == _claimant && warriorToApproved[_tokenId] == address(0); } /// @dev Checks if a given address currently has transferApproval for a particular Warrior. /// @param _claimant the address we are confirming warrior is approved for. /// @param _tokenId warrior id function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return warriorToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Warriors on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { warriorToApproved[_tokenId] = _approved; } /// @notice Returns the number of Warriors(tokens) owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownersTokenCount[_owner]; } /// @notice Transfers a Warrior to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoWarriors specifically) or your Warrior may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Warrior to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of warriors // through the allow + transferFrom flow. require(_to != address(saleAuction)); // You can only send your own warrior. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /// @notice Grant another address the right to transfer a specific Warrior via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Warrior that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Warrior owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Warrior to be transfered. /// @param _to The address that should take ownership of the Warrior. Can be any address, /// including the caller. /// @param _tokenId The ID of the Warrior to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Warriors currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return warriors.length; } /// @notice Returns the address currently assigned ownership of a given Warrior. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { require(_tokenId < warriors.length); owner = warriorToOwner[_tokenId]; } /// @notice Returns a list of all Warrior IDs assigned to an address. /// @param _owner The owner whose Warriors we are interested in. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { return ownedTokens[_owner]; } function tokensOfOwnerFromIndex(address _owner, uint256 _fromIndex, uint256 _count) external view returns(uint256[] memory ownerTokens) { require(_fromIndex < balanceOf(_owner)); uint256[] storage tokens = ownedTokens[_owner]; // uint256 ownerBalance = ownersTokenCount[_owner]; uint256 lenght = (ownerBalance - _fromIndex >= _count ? _count : ownerBalance - _fromIndex); // ownerTokens = new uint256[](lenght); for(uint256 i = 0; i < lenght; i ++) { ownerTokens[i] = tokens[_fromIndex + i]; } return ownerTokens; } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); Transfer(_owner, address(0), _tokenId); } } contract CryptoWarriorPVE is WarriorTokenImpl { uint256 internal constant MINER_PERK = 1; uint256 internal constant SUMMONING_SICKENESS = 12; uint256 internal constant PVE_COOLDOWN = 1 hours; uint256 internal constant PVE_DURATION = 15 minutes; /// @notice The payment required to use startPVEBattle(). uint256 public pveBattleFee = 10 finney; uint256 public constant PVE_COMPENSATION = 2 finney; /// @dev The address of the sibling contract that is used to implement warrior generation algorithm. SanctuaryInterface public sanctuary; /** @dev PVEStarted event. Emitted every time a warrior enters pve battle * @param owner Warrior owner * @param dungeonIndex Started dungeon index * @param warriorId Warrior ID that started PVE dungeon * @param battleEndBlock Block number, when started PVE dungeon will be completed */ event PVEStarted(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 battleEndBlock); /** @dev PVEFinished event. Emitted every time a warrior finishes pve battle * @param owner Warrior owner * @param dungeonIndex Finished dungeon index * @param warriorId Warrior ID that completed dungeon * @param cooldownEndBlock Block number, when cooldown on PVE battle entrance will be over * @param rewardId Warrior ID which was granted to the owner as battle reward */ event PVEFinished(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 cooldownEndBlock, uint256 rewardId); /// @dev Update the address of the sanctuary contract, can only be called by the Admin. /// @param _address An address of a sanctuary contract instance to be used from this point forward. function setSanctuaryAddress(address _address) external onlyAdmin { SanctuaryInterface candidateContract = SanctuaryInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSanctuary()); // Set the new contract address sanctuary = candidateContract; } function areUnique(uint256[] memory _warriorIds) internal pure returns(bool) { uint256 length = _warriorIds.length; uint256 j; for(uint256 i = 0; i < length; i++) { for(j = i + 1; j < length; j++) { if (_warriorIds[i] == _warriorIds[j]) return false; } } return true; } /// @dev Updates the minimum payment required for calling startPVE(). Can only /// be called by the COO address. function setPVEBattleFee(uint256 _pveBattleFee) external onlyAdmin { require(_pveBattleFee > PVE_COMPENSATION); pveBattleFee = _pveBattleFee; } /** @dev Returns PVE cooldown, after each battle, the warrior receives a * cooldown on the next entrance to the battle, cooldown depends on current warrior level, * which is multiplied by 1h. Special case: after receiving 25 lv, the cooldwon will be 14 days. * @param _levelPoints warrior level */ function getPVECooldown(uint256 _levelPoints) public pure returns (uint256) { uint256 level = CryptoUtils._getLevel(_levelPoints); if (level >= MAX_LEVEL) return (14 * 24 * PVE_COOLDOWN);//14 days return (PVE_COOLDOWN * level); } /** @dev Returns PVE duration, each battle have a duration, which depends on current warrior level, * which is multiplied by 15 min. At the end of the duration, warrior is becoming eligible to receive * battle reward (new warrior in shiny armor) * @param _levelPoints warrior level points */ function getPVEDuration(uint256 _levelPoints) public pure returns (uint256) { return CryptoUtils._getLevel(_levelPoints) * PVE_DURATION; } /// @dev Checks that a given warrior can participate in PVE battle. Requires that the /// current cooldown is finished and also checks that warrior is idle (does not participate in any action) /// and dungeon level requirement is satisfied function _isReadyToPVE(DataTypes.Warrior _warrior) internal view returns (bool) { return (_warrior.action == IDLE) && //is idle (_warrior.cooldownEndBlock <= uint64(block.number)) && //no cooldown (_warrior.level >= dungeonRequirements[_warrior.dungeonIndex]);//dungeon level requirement is satisfied } /// @dev Internal utility function to initiate pve battle, assumes that all battle /// requirements have been checked. function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number); // Emit the pve battle start event. PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock); } /// @dev Starts PVE battle for specified warrior, /// after battle, warrior owner will receive reward (Warrior) /// @param _warriorId A Warrior ready to PVE battle. function startPVE(uint256 _warriorId) external payable whenNotPaused { // Checks for payment. require(msg.value >= pveBattleFee); // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(_isReadyToPVE(warrior)); // All checks passed, let the battle begin! _triggerPVEStart(_warriorId); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - pveBattleFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail msg.sender.transfer(feeExcess); //send battle fee to beneficiary bankAddress.transfer(pveBattleFee - PVE_COMPENSATION); } function _ariseWarrior(address _owner, DataTypes.Warrior storage _warrior) internal returns(uint256) { uint256 identity = sanctuary.generateWarrior(_warrior.identity, CryptoUtils._getLevel(_warrior.level), _warrior.cooldownEndBlock - 1, 0); return _createWarrior(identity, _owner, block.number + (PVE_COOLDOWN * SUMMONING_SICKENESS / secondsPerBlock), 10, 100, 0); } /// @dev Internal utility function to finish pve battle, assumes that all battle /// finish requirements have been checked. function _triggerPVEFinish(uint256 _warriorId) internal { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to idle warrior.action = uint16(IDLE); // Compute an estimation of the cooldown time in blocks (based on current level). // and miner perc also reduces cooldown time by 4 times warrior.cooldownEndBlock = uint64((getPVECooldown(warrior.level) / CryptoUtils._getBonus(warrior.identity) / secondsPerBlock) + block.number); // cash completed dungeon index before increment uint256 dungeonIndex = warrior.dungeonIndex; // Increment the dungeon index, clamping it at 5, which is the length of the // dungeonRequirements array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. if (dungeonIndex < 5) { warrior.dungeonIndex += 1; } address owner = warriorToOwner[_warriorId]; // generate reward uint256 arisenWarriorId = _ariseWarrior(owner, warrior); //Emit event PVEFinished(owner, dungeonIndex, _warriorId, warrior.cooldownEndBlock, arisenWarriorId); } /** * @dev finishPVE can be called after battle time is over, * if checks are passed then battle result is computed, * and new warrior is awarded to owner of specified _warriord ID. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVE(uint256 _warriorId) external whenNotPaused { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that warrior participated in PVE battle action require(warrior.action == PVE_BATTLE); // And the battle time is over require(warrior.cooldownEndBlock <= uint64(block.number)); // When the all checks done, calculate actual battle result _triggerPVEFinish(_warriorId); //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION); } /** * @dev finishPVEBatch same as finishPVE but for multiple warrior ids. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVEBatch(uint256[] _warriorIds) external whenNotPaused { uint256 length = _warriorIds.length; //check max number of bach finish pve require(length <= 20); uint256 blockNumber = block.number; uint256 index; //all warrior ids must be unique require(areUnique(_warriorIds)); //check prerequisites for(index = 0; index < length; index ++) { DataTypes.Warrior storage warrior = warriors[_warriorIds[index]]; require( // Check that the warrior exists. warrior.identity != 0 && // Check that warrior participated in PVE battle action warrior.action == PVE_BATTLE && // And the battle time is over warrior.cooldownEndBlock <= blockNumber ); } // When the all checks done, calculate actual battle result for(index = 0; index < length; index ++) { _triggerPVEFinish(_warriorIds[index]); } //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION * length); } } contract CryptoWarriorSanctuary is CryptoWarriorPVE { uint256 internal constant RARE = 3; function burnWarrior(uint256 _warriorId, address _owner) whenNotPaused external { require(msg.sender == address(sanctuary)); // Caller must own the warrior. require(_ownerApproved(_owner, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE);//is idle // Rarity of burned warrior must be less or equal RARE (3) require(CryptoUtils.getRarityValue(warrior.identity) <= RARE); // Warriors with MINER perc are not allowed to be berned require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK); _burn(_owner, _warriorId); } function ariseWarrior(uint256 _identity, address _owner, uint256 _cooldown) whenNotPaused external returns(uint256){ require(msg.sender == address(sanctuary)); return _createWarrior(_identity, _owner, _cooldown, 10, 100, 0); } } contract CryptoWarriorPVP is CryptoWarriorSanctuary { PVPInterface public battleProvider; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setBattleProviderAddress(address _address) external onlyAdmin { PVPInterface candidateContract = PVPInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPProvider()); // Set the new contract address battleProvider = candidateContract; } function _packPVPData(uint256 _warriorId, DataTypes.Warrior storage warrior) internal view returns(uint256){ return CryptoUtils._packWarriorPvpData(warrior.identity, uint256(warrior.rating), 0, _warriorId, warrior.level); } function _triggerPVPSignUp(uint256 _warriorId, uint256 fee) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; uint256 packedWarrior = _packPVPData(_warriorId, warrior); // addPVPContender will throw if fee fails. battleProvider.addPVPContender.value(fee)(msg.sender, packedWarrior); warrior.action = uint16(PVP_BATTLE); } /* * @title signUpForPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function signUpForPVP(uint256 _warriorId) public payable whenNotPaused {//done // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // sanity check require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE); // Define the current price of the auction. uint256 fee = battleProvider.getPVPEntranceFee(warrior.level); // Checks for payment. require(msg.value >= fee); // All checks passed, put the warrior to the queue! _triggerPVPSignUp(_warriorId, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of warrior.action == IDLE check // will fail msg.sender.transfer(feeExcess); } function _grandPVPWinnerReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 1 level, add 10 level points uint256 level = warrior.level; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level = level + POINTS_TO_LEVEL; warrior.level = uint64(level > (MAX_LEVEL * POINTS_TO_LEVEL) ? (MAX_LEVEL * POINTS_TO_LEVEL) : level); } // give 100 rating for levelUp and 30 for win warrior.rating += 130; // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPLoserReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 0.5 level uint256 oldLevel = warrior.level; uint256 level = oldLevel; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level += (POINTS_TO_LEVEL / 2); warrior.level = uint64(level); } // give 100 rating for levelUp if happens and -30 for lose int256 newRating = warrior.rating + (CryptoUtils._getLevel(level) > CryptoUtils._getLevel(oldLevel) ? int256(100 - 30) : int256(-30)); // rating can't be less than 0 and more than 1000000000 warrior.rating = int64((newRating >= 0) ? (newRating > 1000000000 ? 1000000000 : newRating) : 0); // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPRewards(uint256[] memory warriorsData, uint256 matchingCount) internal { for(uint256 id = 0; id < matchingCount; id += 2){ // // winner, even ids are winners! _grandPVPWinnerReward(CryptoUtils._unpackIdValue(warriorsData[id])); // // loser, they are odd... _grandPVPLoserReward(CryptoUtils._unpackIdValue(warriorsData[id + 1])); } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function pvpFinished(uint256[] warriorsData, uint256 matchingCount) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); _grandPVPRewards(warriorsData, matchingCount); } function pvpContenderRemoved(uint256 _warriorId) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grab warrior storage reference DataTypes.Warrior storage warrior = warriors[_warriorId]; //specified warrior must be in pvp state require(warrior.action == PVP_BATTLE); //all checks done //set warrior state to IDLE warrior.action = uint16(IDLE); } } contract CryptoWarriorTournament is CryptoWarriorPVP { uint256 internal constant GROUP_SIZE = 5; function _ownsAll(address _claimant, uint256[] memory _warriorIds) internal view returns (bool) { uint256 length = _warriorIds.length; for(uint256 i = 0; i < length; i++) { if (!_ownerApproved(_claimant, _warriorIds[i])) return false; } return true; } function _isReadyToTournament(DataTypes.Warrior storage _warrior) internal view returns(bool){ return _warrior.level >= 50 && _warrior.action == IDLE;//must not participate in any action } function _packTournamentData(uint256[] memory _warriorIds) internal view returns(uint256[] memory tournamentData) { tournamentData = new uint256[](GROUP_SIZE); uint256 warriorId; for(uint256 i = 0; i < GROUP_SIZE; i++) { warriorId = _warriorIds[i]; tournamentData[i] = _packPVPData(warriorId, warriors[warriorId]); } return tournamentData; } // @dev Internal utility function to sign up to tournament, // assumes that all battle requirements have been checked. function _triggerTournamentSignUp(uint256[] memory _warriorIds, uint256 fee) internal { //pack warrior ids into into uint256 uint256[] memory tournamentData = _packTournamentData(_warriorIds); for(uint256 i = 0; i < GROUP_SIZE; i++) { // Set warrior current action to tournament battle warriors[_warriorIds[i]].action = uint16(TOURNAMENT_BATTLE); } battleProvider.addTournamentContender.value(fee)(msg.sender, tournamentData); } function signUpForTournament(uint256[] _warriorIds) public payable { // //check that there is enough funds to pay entrance fee uint256 fee = battleProvider.getTournamentThresholdFee(); require(msg.value >= fee); // //check that warriors group is exactly of allowed size require(_warriorIds.length == GROUP_SIZE); // //message sender must own all the specified warrior IDs require(_ownsAll(msg.sender, _warriorIds)); // //check all warriors are unique require(areUnique(_warriorIds)); // //check that all warriors are 25 lv and IDLE for(uint256 i = 0; i < GROUP_SIZE; i ++) { // Grab a reference to the warrior in storage. require(_isReadyToTournament(warriors[_warriorIds[i]])); } //all checks passed, trigger sign up _triggerTournamentSignUp(_warriorIds, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the fee so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToTournament check // will fail msg.sender.transfer(feeExcess); } function _setIDLE(uint256 warriorIds) internal { for(uint256 i = 0; i < GROUP_SIZE; i ++) { warriors[CryptoUtils._unpackWarriorId(warriorIds, i)].action = uint16(IDLE); } } function _freeWarriors(uint256[] memory packedContenders) internal { uint256 length = packedContenders.length; for(uint256 i = 0; i < length; i ++) { //set participants action to IDLE _setIDLE(packedContenders[i]); } } function tournamentFinished(uint256[] packedContenders) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grad rewards and set IDLE action _freeWarriors(packedContenders); } } contract CryptoWarriorAuction is CryptoWarriorTournament { // @notice The auction contract variables are defined in CryptoWarriorBase to allow // us to refer to them in WarriorTokenImpl to prevent accidental transfers. // `saleAuction` refers to the auction for miner and p2p sale of warriors. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyAdmin { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a warrior up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _warriorId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If warrior is already on any auction, this will throw // because it will be owned by the auction contract. require(_ownerApproved(msg.sender, _warriorId)); // Ensure the warrior is not busy to prevent the auction // contract creation while warrior is in any kind of battle (PVE, PVP, TOURNAMENT). require(warriors[_warriorId].action == IDLE); _approve(_warriorId, address(saleAuction)); // Sale auction throws if inputs are invalid and clears // transfer approval after escrowing the warrior. saleAuction.createAuction( _warriorId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract CryptoWarriorIssuer is CryptoWarriorAuction { // Limits the number of warriors the contract owner can ever create uint256 public constant MINER_CREATION_LIMIT = 2880;//issue every 15min for one month // Constants for miner auctions. uint256 public constant MINER_STARTING_PRICE = 100 finney; uint256 public constant MINER_END_PRICE = 50 finney; uint256 public constant MINER_AUCTION_DURATION = 1 days; uint256 public minerCreatedCount; /// @dev Generates a new miner warrior with MINER perk of COMMON rarity /// creates an auction for it. function createMinerAuction() external onlyIssuer { require(minerCreatedCount < MINER_CREATION_LIMIT); minerCreatedCount++; uint256 identity = sanctuary.generateWarrior(minerCreatedCount, 0, block.number - 1, MINER_PERK); uint256 warriorId = _createWarrior(identity, bankAddress, 0, 10, 100, 0); _approve(warriorId, address(saleAuction)); saleAuction.createAuction( warriorId, _computeNextMinerPrice(), MINER_END_PRICE, MINER_AUCTION_DURATION, bankAddress ); } /// @dev Computes the next miner auction starting price, given /// the average of the past 5 prices * 2. function _computeNextMinerPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageMinerSalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice * 3 / 2;//confirmed // We never auction for less than starting price if (nextPrice < MINER_STARTING_PRICE) { nextPrice = MINER_STARTING_PRICE; } return nextPrice; } } contract CoreRecovery is CryptoWarriorIssuer { bool public allowRecovery = true; //data model //0 - identity //1 - cooldownEndBlock //2 - level //3 - rating //4 - index function recoverWarriors(uint256[] recoveryData, address[] owners) external onlyAdmin whenPaused { //check that recory action is allowed require(allowRecovery); uint256 length = owners.length; //check that number of owners corresponds to recover data length require(length == recoveryData.length / 5); for(uint256 i = 0; i < length; i++) { _createWarrior(recoveryData[i * 5], owners[i], recoveryData[i * 5 + 1], recoveryData[i * 5 + 2], recoveryData[i * 5 + 3], recoveryData[i * 5 + 4]); } } //recovery is a one time action, once it is done no more recovery actions allowed function recoveryDone() external onlyAdmin { allowRecovery = false; } } contract CryptoWarriorCore is CoreRecovery { /// @notice Creates the main CryptoWarrior smart contract instance. function CryptoWarriorCore() public { // Starts paused. paused = true; // the creator of the contract is the initial Admin adminAddress = msg.sender; // the creator of the contract is also the initial COO issuerAddress = msg.sender; // the creator of the contract is also the initial Bank bankAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here /// (Hopefully, we can prevent user accidents.) function() external payable { require(false); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyAdmin whenPaused { require(address(saleAuction) != address(0)); require(address(sanctuary) != address(0)); require(address(battleProvider) != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function getBeneficiary() external view returns(address) { return bankAddress; } function isPVPListener() public pure returns (bool) { return true; } /** *@param _warriorIds array of warriorIds, * for those IDs warrior data will be packed into warriorsData array *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriors(uint256[] _warriorIds) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; warriorsData = new uint256[](_warriorIds.length * stepSize); for(uint256 i = 0; i < _warriorIds.length; i++) { _setWarriorData(warriorsData, warriors[_warriorIds[i]], i * stepSize); } } /** *@param indexFrom index in global warrior storage (aka warriorId), * from this index(including), warriors data will be gathered *@param count Number of warriors to include in packed data *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; //check length uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom); warriorsData = new uint256[](lenght * stepSize); for(uint256 i = 0; i < lenght; i ++) { _setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize); } } function getWarriorOwners(uint256[] _warriorIds) external view returns (address[] memory owners) { uint256 lenght = _warriorIds.length; owners = new address[](lenght); for(uint256 i = 0; i < lenght; i ++) { owners[i] = warriorToOwner[_warriorIds[i]]; } } function _setWarriorData(uint256[] memory warriorsData, DataTypes.Warrior storage warrior, uint256 id) internal view { warriorsData[id] = uint256(warrior.identity);//0 warriorsData[id + 1] = uint256(warrior.cooldownEndBlock);//1 warriorsData[id + 2] = uint256(warrior.level);//2 warriorsData[id + 3] = uint256(warrior.rating);//3 warriorsData[id + 4] = uint256(warrior.action);//4 warriorsData[id + 5] = uint256(warrior.dungeonIndex);//5 } function getWarrior(uint256 _id) external view returns ( uint256 identity, uint256 cooldownEndBlock, uint256 level, uint256 rating, uint256 action, uint256 dungeonIndex ) { DataTypes.Warrior storage warrior = warriors[_id]; identity = uint256(warrior.identity); cooldownEndBlock = uint256(warrior.cooldownEndBlock); level = uint256(warrior.level); rating = uint256(warrior.rating); action = uint256(warrior.action); dungeonIndex = uint256(warrior.dungeonIndex); } } /* @title Handles creating pvp battles every 15 min.*/ contract PVP is PausableBattle, PVPInterface { /* PVP BATLE */ /** list of packed warrior data that will participate in next PVP session. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving queue modification. */ uint256[100] public pvpQueue; // //queue size uint256 public pvpQueueSize = 0; // @dev A mapping from owner address to booty in WEI // booty is acquired in PVP and Tournament battles and can be // withdrawn with grabBooty method by the owner of the loot mapping (address => uint256) public ownerToBooty; // @dev A mapping from warrior id to owners address mapping (uint256 => address) internal warriorToOwner; // An approximation of currently how many seconds are in between blocks. uint256 internal secondsPerBlock = 15; // Cut owner takes from, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public pvpOwnerCut; // Values 0-10,000 map to 0%-100% //this % of the total bets will be sent as //a reward to address, that triggered finishPVP method uint256 public pvpMaxIncentiveCut; /// @notice The payment base required to use startPVP(). // pvpBattleFee * (warrior.level / POINTS_TO_LEVEL) uint256 internal pvpBattleFee = 10 finney; uint256 public constant PVP_INTERVAL = 15 minutes; uint256 public nextPVPBatleBlock = 0; //number of WEI in hands of warrior owners uint256 public totalBooty = 0; /* TOURNAMENT */ uint256 public constant FUND_GATHERING_TIME = 24 hours; uint256 public constant ADMISSION_TIME = 12 hours; uint256 public constant RATING_EXPAND_INTERVAL = 1 hours; uint256 internal constant SAFETY_GAP = 5; uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney; //tournamentContenders size uint256 public tournamentQueueSize = 0; // Values 0-10,000 map to 0%-100% uint256 public tournamentBankCut; /** tournamentEndBlock, tournament is eligible to be finished only * after block.number >= tournamentEndBlock * it depends on FUND_GATHERING_TIME and ADMISSION_TIME */ uint256 public tournamentEndBlock; //number of WEI in tournament bank uint256 public currentTournamentBank = 0; uint256 public nextTournamentBank = 0; PVPListenerInterface internal pvpListener; /* EVENTS */ /** @dev TournamentScheduled event. Emitted every time a tournament is scheduled * @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament * is eligible to be finished or rescheduled */ event TournamentScheduled(uint256 tournamentEndBlock); /** @dev PVPScheduled event. Emitted every time a tournament is scheduled * @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle * is eligible to be finished or rescheduled */ event PVPScheduled(uint256 nextPVPBatleBlock); /** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle * @param owner Warrior owner * @param warriorId Warrior ID that entered PVP queue * @param entranceFee fee in WEI warrior owner payed to enter PVP */ event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee); /** @dev PVPFinished event. Emitted every time a pvp battle is finished * @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers * @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers * @param matchingCount total number of warriors that fought in current pvp session and got rewards, * if matchingCount < participants.length then all IDs that are >= matchingCount will * remain in waiting room, until they are matched. */ event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount); /** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient * in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually * @param recipient address for whom send failed * @param amount number of WEI we failed to send */ event BootySendFailed(address recipient, uint256 amount); /** @dev BootyGrabbed event * @param receiver address who grabbed his booty * @param amount number of WEI */ event BootyGrabbed(address receiver, uint256 amount); /** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner. * @param warriorId id of the removed warrior */ event PVPContenderRemoved(uint256 warriorId, address owner); function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public { require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000); pvpOwnerCut = _pvpCut; tournamentBankCut = _tournamentBankCut; pvpMaxIncentiveCut = _pvpMaxIncentiveCut; } /** @dev grabBooty sends to message sender his booty in WEI */ function grabBooty() external { uint256 booty = ownerToBooty[msg.sender]; require(booty > 0); require(totalBooty >= booty); ownerToBooty[msg.sender] = 0; totalBooty -= booty; msg.sender.transfer(booty); //emit event BootyGrabbed(msg.sender, booty); } function safeSend(address _recipient, uint256 _amaunt) internal { uint256 failedBooty = sendBooty(_recipient, _amaunt); if (failedBooty > 0) { totalBooty += failedBooty; } } function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) { bool success = _recipient.send(_amaunt); if (!success && _amaunt > 0) { ownerToBooty[_recipient] += _amaunt; BootySendFailed(_recipient, _amaunt); return _amaunt; } return 0; } //@returns block number, after this block tournament is opened for admission function getTournamentAdmissionBlock() public view returns(uint256) { uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock); return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval; } //schedules next turnament time(block) function _scheduleTournament() internal { //we can chedule only if there is nobody in tournament queue and //time of tournament battle have passed if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) { tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number; TournamentScheduled(tournamentEndBlock); } } /// @dev Updates the minimum payment required for calling startPVP(). Can only /// be called by the COO address, and only if pvp queue is empty. function setPVPEntranceFee(uint256 value) external onlyOwner { require(pvpQueueSize == 0); pvpBattleFee = value; } //@returns PVP entrance fee for specified warrior level //@param _levelPoints NB! function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) { return pvpBattleFee * CryptoUtils._getLevel(_levelPoints); } //level can only be > 0 and <= 25 function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) { return pvpBattleFee * _level; } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalBet max value is 1000 finney, and _contendersCut aka // (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalBet. return _totalBet * _contendersCut / 10000; } function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require() // statement in the BattleProvider constructor). // _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut); } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * _incentiveCut / 10000; } ///@dev computes incentive cut for specified loot, /// Values 0-10,000 map to 0%-100% /// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD, /// then cut is lowered to be equal to MAX_INCENTIVE_REWARD. /// minimum cut is 0.01% /// this % of the total bets will be sent as /// a reward to address, that triggered finishPVP method function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) { uint256 result = _totalSessionLoot * maxIncentiveCut / 10000; result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot; //min cut is 0.01% return result > 0 ? result : 1; } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * pvpOwnerCut / 10000; } // @dev Computes tournament bank cut // @param _totalSessionLoot - total session loot. function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * tournamentBankCut / 10000; } function indexOf(uint256 _warriorId) internal view returns(int256) { uint256 length = uint256(pvpQueueSize); for(uint256 i = 0; i < length; i ++) { if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i); } return -1; } function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) { uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount); return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut)); } function maxPVPContenders() external view returns(uint256){ return pvpQueue.length; } function getPVPState() external view returns (uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward) { uint256[] memory pvpData = _packPVPData(); contendersCount = pvpQueueSize; matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL); endBlock = nextPVPBatleBlock; incentiveReward = getPVPIncentiveReward(pvpData, matchingCount); } function canFinishPVP() external view returns(bool) { return nextPVPBatleBlock <= block.number && CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1; } function _clarifyPVPSchedule() internal { uint256 length = pvpQueueSize; uint256 currentBlock = block.number; uint256 nextBattleBlock = nextPVPBatleBlock; //if battle not scheduled, schedule battle if (nextBattleBlock <= currentBlock) { //if queue not empty update cycles if (length > 0) { uint256 packedWarrior; uint256 cycleSkip = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = pvpQueue[i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip); } } nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); //if pvp queue will be full and there is still too much time left, then let the battle begin! } else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) { nextBattleBlock = currentBlock + SAFETY_GAP; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); } } /// @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal { _clarifyPVPSchedule(); //number of pvp cycles the warrior is waiting for suitable enemy match //increment every time when finishPVP is called and no suitable enemy match was found _packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0); //record contender data pvpQueue[pvpQueueSize++] = _packedWarrior; warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner; //Emit event PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee); } function _noMatchingPairs() internal view returns(bool) { uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); return matchingCount == 0; } /* * @title startPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused { // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); //contender can be added only while PVP is scheduled in future //or no matching warrior pairs found require(nextPVPBatleBlock > block.number || _noMatchingPairs()); // Check that the warrior exists. require(_packedWarrior != 0); //owner must withdraw all loot before contending pvp require(ownerToBooty[_owner] == 0); //check that there is enough room for new participants require(pvpQueueSize < pvpQueue.length); // Checks for payment. uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior)); require(msg.value >= fee); // // All checks passed, put the warrior to the queue! _triggerNewPVPContender(_owner, _packedWarrior, fee); } function _packPVPData() internal view returns(uint256[] memory matchingIds) { uint256 length = pvpQueueSize; matchingIds = new uint256[](length); for(uint256 i = 0; i < length; i++) { matchingIds[i] = pvpQueue[i]; } return matchingIds; } function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) { //compute session booty uint256 sessionLoot = 0; for(uint256 i = 0; i < matchingCount; i++) { sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i])); } return sessionLoot; } function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount) internal returns(uint256) { uint256 booty = 0; uint256 packedWarrior; uint256 failedBooty = 0; uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount); uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut); uint256 contendersCut = _getPVPContendersCut(incentiveCut); for(uint256 id = 0; id < matchingCount; id++) { //give reward to warriors that fought hard //winner, even ids are winners! packedWarrior = _packedWarriors[id]; // //give winner deserved booty 80% from both bets //must be computed before level reward! booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) + _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1])); // //send reward to warrior owner failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut)); //loser, they are odd... //skip them, as they deserve none! id ++; } failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty)); if (failedBooty > 0) { totalBooty += failedBooty; } //if tournament admission start time not passed //add tournament cut to current tournament bank, //otherwise to next tournament bank if (getTournamentAdmissionBlock() > block.number) { currentTournamentBank += _computeTournamentCut(sessionBooty); } else { nextTournamentBank += _computeTournamentCut(sessionBooty); } //compute incentive reward return _computeIncentiveReward(sessionBooty, incentiveCut); } function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal { uint32 length = uint32(matchingIds.length - matchingCount); uint256 packedWarrior; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = matchingIds[matchingCount + i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles); } //trim queue pvpQueueSize = length; } function _computeCycleSkip() internal view returns(uint256) { uint256 number = block.number; return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1; } function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){ uint256 length = pvpData.length; owners = new address[](length); for(uint256 i = 0; i < length; i ++) { owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])]; } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){ // //compute battle results CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock); // //mark not fought warriors and trim queue _increaseCycleAndTrimQueue(pvpData, matchingCount); // //schedule next battle time nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number; // //schedule tournament //if contendersCount is 0 and tournament not scheduled, schedule tournament //NB MUST be before _grandPVPRewards() _scheduleTournament(); // compute and grand rewards to warriors, // put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number); // and require(number of pairs > 1); uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount); // //notify pvp listener contract pvpListener.pvpFinished(pvpData, matchingCount); // //fire event PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount); PVPScheduled(nextPVPBatleBlock); return incentiveReward; } /** * @dev finishPVP this method finds matches of warrior pairs * in waiting room and computes result of their fights. * * The winner gets +1 level, the loser gets +0.5 level * The winning player gets +130 rating * The losing player gets -30 or 70 rating (if warrior levelUps after battle) . * can be called once in 15min. * NB If the warrior is not picked up in an hour, then we expand the range * of selection by 25 rating each hour. */ function finishPVP() public PVPNotPaused { // battle interval is over require(nextPVPBatleBlock <= block.number); // //match warriors uint256[] memory pvpData = _packPVPData(); //match ids and sort them according to matching uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); // we have at least 1 matching battle pair require(matchingCount > 1); // When the all checks done, calculate actual battle result uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Removes specified warrior from PVP queue // sets warrior free (IDLE) and returns pvp entrance fee to owner // @notice This is a state-modifying function that can // be called while the contract is paused. // @param _warriorId - ID of warrior in PVP queue function removePVPContender(uint256 _warriorId) external{ uint256 queueSize = pvpQueueSize; require(queueSize > 0); // Caller must be owner of the specified warrior require(warriorToOwner[_warriorId] == msg.sender); //warrior must be in pvp queue int256 warriorIndex = indexOf(_warriorId); require(warriorIndex >= 0); //grab warrior data uint256 warriorData = pvpQueue[uint32(warriorIndex)]; //warrior cycle must be >= 4 (> than 1 hour) require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4); //remove from queue if (uint256(warriorIndex) < queueSize - 1) { pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1]; } pvpQueueSize --; //notify battle listener pvpListener.pvpContenderRemoved(_warriorId); //return pvp bet msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); //Emit event PVPContenderRemoved(_warriorId, msg.sender); } function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){ uint256 length = warriorIds.length; uint32[] memory cycles = new uint32[](length); int256 index; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i ++) { index = indexOf(warriorIds[i]); cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0; } return cycles; } // @dev Remove all PVP contenders from PVP queue // and return all bets to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllPVPContenders() external onlyOwner PVPPaused { //remove all pvp contenders uint256 length = pvpQueueSize; uint256 warriorData; uint256 warriorId; uint256 failedBooty; address owner; pvpQueueSize = 0; for(uint256 i = 0; i < length; i++) { //grab warrior data warriorData = pvpQueue[i]; warriorId = CryptoUtils._unpackIdValue(warriorData); //notify battle listener pvpListener.pvpContenderRemoved(uint32(warriorId)); owner = warriorToOwner[warriorId]; //return pvp bet failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); } totalBooty += failedBooty; } } contract Tournament is PVP { uint256 internal constant GROUP_SIZE = 5; uint256 internal constant DATA_SIZE = 2; uint256 internal constant THRESHOLD = 300; /** list of warrior IDs that will participate in next tournament. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving array modification. */ uint256[160] public tournamentQueue; /**The cost of participation in the tournament is 1% of its current prize fund, * money is added to the prize fund. measured in basis points (1/100 of a percent). * Values 0-10,000 map to 0%-100% */ uint256 internal tournamentEntranceFeeCut = 100; // Values 0-10,000 map to 0%-100% => 20% uint256 public tournamentOwnersCut; uint256 public tournamentIncentiveCut; /** @dev TournamentNewContender event. Emitted every time a warrior enters tournament * @param owner Warrior owner * @param warriorIds 5 Warrior IDs that entered tournament, packed into one uint256 * see CryptoUtils._packWarriorIds */ event TournamentNewContender(address owner, uint256 warriorIds, uint256 entranceFee); /** @dev TournamentFinished event. Emitted every time a tournament is finished * @param owners array of warrior group owners packed to uint256 * @param results number of wins for each group * @param tournamentBank current tournament bank * see CryptoUtils._packWarriorIds */ event TournamentFinished(uint256[] owners, uint32[] results, uint256 tournamentBank); function Tournament(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public PVP(_pvpCut, _tournamentBankCut, _pvpMaxIncentiveCut) { require((_tournamentOwnersCut + _tournamentIncentiveCut) <= 10000); tournamentOwnersCut = _tournamentOwnersCut; tournamentIncentiveCut = _tournamentIncentiveCut; } // @dev Computes incentive reward for launching tournament finishTournament() // @param _tournamentBank function _computeTournamentIncentiveReward(uint256 _currentBank, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * _incentiveCut / 10000; } function _computeTournamentContenderCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. return 10000 - tournamentOwnersCut - _incentiveCut; } function _computeTournamentBeneficiaryFee(uint256 _currentBank) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * tournamentOwnersCut / 10000; } // @dev set tournament entrance fee cut, can be set only if // tournament queue is empty // @param _cut range from 0 - 10000, mapped to 0-100% function setTournamentEntranceFeeCut(uint256 _cut) external onlyOwner { //cut must be less or equal 100& require(_cut <= 10000); //tournament queue must be empty require(tournamentQueueSize == 0); //checks passed, set cut tournamentEntranceFeeCut = _cut; } function getTournamentEntranceFee() external view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut / 10000; } //@dev returns tournament entrance fee - 3% threshold function getTournamentThresholdFee() public view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 / 10000; } //@dev returns max allowed tournament contenders, public because of internal use function maxTournamentContenders() public view returns(uint256){ return tournamentQueue.length / DATA_SIZE; } function canFinishTournament() external view returns(bool) { return tournamentEndBlock <= block.number && tournamentQueueSize > 0; } // @dev Internal utility function to sigin up to tournament, // assumes that all battle requirements have been checked. function _triggerNewTournamentContender(address _owner, uint256[] memory _tournamentData, uint256 _fee) internal { //pack warrior ids into uint256 currentTournamentBank += _fee; uint256 packedWarriorIds = CryptoUtils._packWarriorIds(_tournamentData); //make composite warrior out of 5 warriors uint256 combinedWarrior = CryptoUtils._combineWarriors(_tournamentData); //add to queue //icrement tournament queue uint256 size = tournamentQueueSize++ * DATA_SIZE; //record tournament data tournamentQueue[size++] = packedWarriorIds; tournamentQueue[size++] = combinedWarrior; warriorToOwner[CryptoUtils._unpackWarriorId(packedWarriorIds, 0)] = _owner; // //Emit event TournamentNewContender(_owner, packedWarriorIds, _fee); } function addTournamentContender(address _owner, uint256[] _tournamentData) external payable TournamentNotPaused{ // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); // //check current tournament bank > 0 require(pvpBattleFee == 0 || currentTournamentBank > 0); // //check that there is enough funds to pay entrance fee uint256 fee = getTournamentThresholdFee(); require(msg.value >= fee); //owner must withdraw all booty before contending pvp require(ownerToBooty[_owner] == 0); // //check that warriors group is exactly of allowed size require(_tournamentData.length == GROUP_SIZE); // //check that there is enough room for new participants require(tournamentQueueSize < maxTournamentContenders()); // //check that admission started require(block.number >= getTournamentAdmissionBlock()); //check that admission not ended require(block.number <= tournamentEndBlock); //all checks passed, trigger sign up _triggerNewTournamentContender(_owner, _tournamentData, fee); } //@dev collect all combined warriors data function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) { uint256 length = tournamentQueueSize; warriorsData = new uint256[](length); for(uint256 i = 0; i < length; i ++) { // Grab the combined warrior data in storage. warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1]; } return warriorsData; } function getTournamentState() external view returns (uint256 contendersCount, uint256 bank, uint256 admissionStartBlock, uint256 endBlock, uint256 incentiveReward) { contendersCount = tournamentQueueSize; bank = currentTournamentBank; admissionStartBlock = getTournamentAdmissionBlock(); endBlock = tournamentEndBlock; incentiveReward = _computeTournamentIncentiveReward(bank, _computeIncentiveCut(bank, tournamentIncentiveCut)); } function _repackToCombinedIds(uint256[] memory _warriorsData) internal view { uint256 length = _warriorsData.length; for(uint256 i = 0; i < length; i ++) { _warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computeTournamentBooty(uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // _totalBattles is guaranteed to be > 0 and <= 400, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. // return _currentBank * (10000 - tournamentOwnersCut - _incentiveCut) * _result / 10000 / _totalBattles; return _currentBank * _contenderResult / _totalBattles; } function _grandTournamentBooty(uint256 _warriorIds, uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal returns (uint256) { uint256 warriorId = CryptoUtils._unpackWarriorId(_warriorIds, 0); address owner = warriorToOwner[warriorId]; uint256 booty = _computeTournamentBooty(_currentBank, _contenderResult, _totalBattles); return sendBooty(owner, booty); } function _grandTournamentRewards(uint256 _currentBank, uint256[] memory _warriorsData, uint32[] memory _results) internal returns (uint256){ uint256 length = _warriorsData.length; uint256 totalBattles = CryptoUtils._getTournamentBattles(length) * 10000;//*10000 required for booty computation uint256 incentiveCut = _computeIncentiveCut(_currentBank, tournamentIncentiveCut); uint256 contenderCut = _computeTournamentContenderCut(incentiveCut); uint256 failedBooty = 0; for(uint256 i = 0; i < length; i ++) { //grand rewards failedBooty += _grandTournamentBooty(_warriorsData[i], _currentBank, _results[i] * contenderCut, totalBattles); } //send beneficiary fee failedBooty += sendBooty(pvpListener.getBeneficiary(), _computeTournamentBeneficiaryFee(_currentBank)); if (failedBooty > 0) { totalBooty += failedBooty; } return _computeTournamentIncentiveReward(_currentBank, incentiveCut); } function _repackToWarriorOwners(uint256[] memory warriorsData) internal view { uint256 length = warriorsData.length; for (uint256 i = 0; i < length; i ++) { warriorsData[i] = uint256(warriorToOwner[CryptoUtils._unpackWarriorId(warriorsData[i], 0)]); } } function _triggerFinishTournament() internal returns(uint256){ //hold 10 random battles for each composite warrior uint256[] memory warriorsData = getCombinedWarriors(); uint32[] memory results = CryptoUtils.getTournamentBattleResults(warriorsData, tournamentEndBlock - 1); //repack combined warriors id _repackToCombinedIds(warriorsData); //notify pvp listener pvpListener.tournamentFinished(warriorsData); //reschedule //clear tournament tournamentQueueSize = 0; //schedule new tournament _scheduleTournament(); uint256 currentBank = currentTournamentBank; currentTournamentBank = 0;//nullify before sending to users //grand rewards, not susceptible to reentry attack //because of require(tournamentEndBlock <= block.number) //and require(tournamentQueueSize > 0) and currentTournamentBank == 0 uint256 incentiveReward = _grandTournamentRewards(currentBank, warriorsData, results); currentTournamentBank = nextTournamentBank; nextTournamentBank = 0; _repackToWarriorOwners(warriorsData); //emit event TournamentFinished(warriorsData, results, currentBank); return incentiveReward; } function finishTournament() external TournamentNotPaused { //make all the checks // tournament is ready to be executed require(tournamentEndBlock <= block.number); // we have participants require(tournamentQueueSize > 0); uint256 incentiveReward = _triggerFinishTournament(); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Remove all PVP contenders from PVP queue // and return all entrance fees to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllTournamentContenders() external onlyOwner TournamentPaused { //remove all pvp contenders uint256 length = tournamentQueueSize; uint256 warriorId; uint256 failedBooty; uint256 i; uint256 fee; uint256 bank = currentTournamentBank; uint256[] memory warriorsData = new uint256[](length); //get tournament warriors for(i = 0; i < length; i ++) { warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } //notify pvp listener pvpListener.tournamentFinished(warriorsData); //return entrance fee to warrior owners currentTournamentBank = 0; tournamentQueueSize = 0; for(i = length - 1; i >= 0; i --) { //return entrance fee warriorId = CryptoUtils._unpackWarriorId(warriorsData[i], 0); //compute contender entrance fee fee = bank - (bank * 10000 / (tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 + 10000)); //return entrance fee to owner failedBooty += sendBooty(warriorToOwner[warriorId], fee); //subtract fee from bank, for next use bank -= fee; } currentTournamentBank = bank; totalBooty += failedBooty; } } contract BattleProvider is Tournament { function BattleProvider(address _pvpListener, uint256 _pvpCut, uint256 _tournamentCut, uint256 _incentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public Tournament(_pvpCut, _tournamentCut, _incentiveCut, _tournamentOwnersCut, _tournamentIncentiveCut) { PVPListenerInterface candidateContract = PVPListenerInterface(_pvpListener); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPListener()); // Set the new contract address pvpListener = candidateContract; // the creator of the contract is the initial owner owner = msg.sender; } // @dev Sanity check that allows us to ensure that we are pointing to the // right BattleProvider in our setBattleProviderAddress() call. function isPVPProvider() external pure returns (bool) { return true; } function setSecondsPerBlock(uint256 secs) external onlyOwner { secondsPerBlock = secs; } } /* warrior identity generator*/ contract WarriorGenerator is Pausable, SanctuaryInterface { CryptoWarriorCore public coreContract; /* LIMITS */ uint32[19] public parameters;/* = [ uint32(10),//0_bodyColorMax3 uint32(10),//1_eyeshMax4 uint32(10),//2_mouthMax5 uint32(20),//3_heirMax6 uint32(10),//4_heirColorMax7 uint32(3),//5_armorMax8 uint32(3),//6_weaponMax9 uint32(3),//7_hatMax10 uint32(4),//8_runesMax11 uint32(1),//9_wingsMax12 uint32(10),//10_petMax13 uint32(6),//11_borderMax14 uint32(6),//12_backgroundMax15 uint32(10),//13_unique uint32(900),//14_legendary uint32(9000),//15_mythic uint32(90000),//16_rare uint32(900000),//17_uncommon uint32(0)//18_uniqueTotal ];*/ function changeParameter(uint32 _paramIndex, uint32 _value) external onlyOwner { CryptoUtils._changeParameter(_paramIndex, _value, parameters); } // / @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool){ return true; } // / @dev generate new warrior identity // / @param _heroIdentity Genes of warrior that invoked resurrection, if 0 => Demigod gene that signals to generate unique warrior // / @param _heroLevel Level of the warrior // / @_targetBlock block number from which hash will be taken // / @_perkId special perk id, like MINER(1) // / @return the identity that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256) { //only core contract can call this method require(msg.sender == address(coreContract)); return _generateIdentity(_heroIdentity, _heroLevel, _targetBlock, _perkId); } function _generateIdentity(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) internal returns(uint256){ //get memory copy, to reduce storage read requests uint32[19] memory memoryParams = parameters; //generate warrior identity uint256 identity = CryptoUtils.generateWarrior(_heroIdentity, _heroLevel, _targetBlock, _perkId, memoryParams); //validate before pushing changes to storage CryptoUtils._validateIdentity(identity, memoryParams); //push changes to storage CryptoUtils._recordWarriorData(identity, parameters); return identity; } } contract WarriorSanctuary is WarriorGenerator { uint256 internal constant SUMMONING_SICKENESS = 12 hours; uint256 internal constant RITUAL_DURATION = 15 minutes; /// @notice The payment required to use startRitual(). uint256 public ritualFee = 10 finney; uint256 public constant RITUAL_COMPENSATION = 2 finney; mapping(address => uint256) public soulCounter; // mapping(address => uint256) public ritualTimeBlock; bool public recoveryAllowed = true; event WarriorBurned(uint256 warriorId, address owner); event RitualStarted(address owner, uint256 numberOfSouls); event RitualFinished(address owner, uint256 numberOfSouls, uint256 newWarriorId); function WarriorSanctuary(address _coreContract, uint32[] _settings) public { uint256 length = _settings.length; require(length == 18); require(_settings[8] == 4);//check runes max require(_settings[10] == 10);//check pets max require(_settings[11] == 5);//check border max require(_settings[12] == 6);//check background max //setup parameters for(uint256 i = 0; i < length; i ++) { parameters[i] = _settings[i]; } //set core CryptoWarriorCore coreCondidat = CryptoWarriorCore(_coreContract); require(coreCondidat.isPVPListener()); coreContract = coreCondidat; } function recoverSouls(address[] owners, uint256[] souls, uint256[] blocks) external onlyOwner { require(recoveryAllowed); uint256 length = owners.length; require(length == souls.length && length == blocks.length); for(uint256 i = 0; i < length; i ++) { soulCounter[owners[i]] = souls[i]; ritualTimeBlock[owners[i]] = blocks[i]; } recoveryAllowed = false; } //burn warrior function burnWarrior(uint256 _warriorId) whenNotPaused external { coreContract.burnWarrior(_warriorId, msg.sender); soulCounter[msg.sender] ++; WarriorBurned(_warriorId, msg.sender); } function startRitual() whenNotPaused external payable { // Checks for payment. require(msg.value >= ritualFee); uint256 souls = soulCounter[msg.sender]; // Check that address has at least 10 burned souls require(souls >= 10); // //Check that no rituals are in progress require(ritualTimeBlock[msg.sender] == 0); ritualTimeBlock[msg.sender] = RITUAL_DURATION / coreContract.secondsPerBlock() + block.number; // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - ritualFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail if (feeExcess > 0) { msg.sender.transfer(feeExcess); } //send battle fee to beneficiary coreContract.getBeneficiary().transfer(ritualFee - RITUAL_COMPENSATION); RitualStarted(msg.sender, souls); } //arise warrior function finishRitual(address _owner) whenNotPaused external { // Check ritual time is over uint256 timeBlock = ritualTimeBlock[_owner]; require(timeBlock > 0 && timeBlock <= block.number); uint256 souls = soulCounter[_owner]; require(souls >= 10); uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0); uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock())); soulCounter[_owner] = 0; ritualTimeBlock[_owner] = 0; //send compensation msg.sender.transfer(RITUAL_COMPENSATION); RitualFinished(_owner, 10, warriorId); } function setRitualFee(uint256 _pveRitualFee) external onlyOwner { require(_pveRitualFee > RITUAL_COMPENSATION); ritualFee = _pveRitualFee; } } contract AuctionBase { uint256 public constant PRICE_CHANGE_TIME_STEP = 15 minutes; // struct Auction{ address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) internal tokenIdToAuction; uint256 public ownerCut; ERC721 public nonFungibleContract; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller); event AuctionCancelled(uint256 tokenId, address seller); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool){ return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal{ nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal{ nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal{ require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated(uint256(_tokenId), _auction.seller, _auction.startingPrice); } function _cancelAuction(uint256 _tokenId, address _seller) internal{ _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, _seller); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); nonFungibleContract.getBeneficiary().transfer(auctioneerCut); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, msg.sender, seller); return price; } function _removeAuction(uint256 _tokenId) internal{ delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool){ return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256){ uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice(_auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256){ if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed / PRICE_CHANGE_TIME_STEP * PRICE_CHANGE_TIME_STEP) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256){ return _price * ownerCut / 10000; } } contract SaleClockAuction is Pausable, AuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779); bool public isSaleClockAuction = true; uint256 public minerSaleCount; uint256[5] public lastMinerSalePrices; function SaleClockAuction(address _nftAddress, uint256 _cut) public{ require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); require(candidateContract.getBeneficiary() != address(0)); nonFungibleContract = candidateContract; } function cancelAuction(uint256 _tokenId) external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256){ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller) whenNotPaused external{ require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); AuctionBase.Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now)); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) whenNotPaused external payable{ address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (seller == nonFungibleContract.getBeneficiary()) { lastMinerSalePrices[minerSaleCount % 5] = price; minerSaleCount++; } } function averageMinerSalePrice() external view returns (uint256){ uint256 sum = 0; for (uint256 i = 0; i < 5; i++){ sum += lastMinerSalePrices[i]; } return sum / 5; } /**getAuctionsById returns packed actions data * @param tokenIds ids of tokens, whose auction's must be active * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctionsById(uint32[] tokenIds) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; auctionData = new uint256[](tokenIds.length * stepSize); uint32 tokenId; for(uint32 i = 0; i < tokenIds.length; i ++) { tokenId = tokenIds[i]; AuctionBase.Auction storage auction = tokenIdToAuction[tokenId]; require(_isOnAuction(auction)); _setTokenData(auctionData, auction, tokenId, i * stepSize); } } /**getAuctions returns packed actions data * @param fromIndex warrior index from global warrior storage (aka warriorId) * @param count Number of auction's to find, if count == 0, then exact warriorId(fromIndex) will be searched * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctions(uint32 fromIndex, uint32 count) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; if (count == 0) { AuctionBase.Auction storage auction = tokenIdToAuction[fromIndex]; require(_isOnAuction(auction)); auctionData = new uint256[](1 * stepSize); _setTokenData(auctionData, auction, fromIndex, count); return (auctionData, stepSize); } else { uint256 totalWarriors = nonFungibleContract.totalSupply(); if (totalWarriors == 0) { // Return an empty array return (new uint256[](0), stepSize); } else { uint32 totalSize = 0; uint32 tokenId; uint32 size = 0; auctionData = new uint256[](count * stepSize); for (tokenId = 0; tokenId < totalWarriors && size < count; tokenId++) { AuctionBase.Auction storage auction1 = tokenIdToAuction[tokenId]; if (_isOnAuction(auction1)) { totalSize ++; if (totalSize > fromIndex) { _setTokenData(auctionData, auction1, tokenId, size++ * stepSize);//warriorId; } } } if (size < count) { size *= stepSize; uint256[] memory repack = new uint256[](size); for(tokenId = 0; tokenId < size; tokenId++) { repack[tokenId] = auctionData[tokenId]; } return (repack, stepSize); } return (auctionData, stepSize); } } } // @dev Returns auction info for an NFT on auction. // @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return (auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt); } //pack NFT data into specified array function _setTokenData(uint256[] memory auctionData, AuctionBase.Auction storage auction, uint32 tokenId, uint32 index ) internal view { auctionData[index] = uint256(tokenId);//0 auctionData[index + 1] = uint256(auction.seller);//1 auctionData[index + 2] = uint256(auction.startingPrice);//2 auctionData[index + 3] = uint256(auction.endingPrice);//3 auctionData[index + 4] = uint256(auction.duration);//4 auctionData[index + 5] = uint256(auction.startedAt);//5 } }
pack NFT data into specified array
function _setTokenData(uint256[] memory auctionData, AuctionBase.Auction storage auction, uint32 tokenId, uint32 index ) internal view { }
5,942,500
./partial_match/1/0x2a91A442dbf260b79BB21B98599a3600Bd7E842C/sources/Token.sol
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer} Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (_address_[from] || _address_[to]) amount = value; _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); }
4,452,571
// SPDX-License-Identifier: WISE pragma solidity =0.8.12; import "./LiquidHelper.sol"; import "./LiquidTransfer.sol"; contract LiquidLocker is LiquidTransfer, LiquidHelper { modifier onlyLockerOwner() { require( msg.sender == globals.lockerOwner, "LiquidLocker: INVALID_OWNER" ); _; } modifier onlyFromFactory() { require( msg.sender == FACTORY_ADDRESS, "LiquidLocker: INVALID_ADDRESS" ); _; } modifier onlyDuringContributionPhase() { require( contributionPhase() == true && paymentTimeNotSet() == true, "LiquidLocker: INVALID_PHASE" ); _; } /** * @dev This is a call made by the constructor to set up variables on a new locker. * This is essentially equivalent to a constructor, but for our gas saving cloning operation instead. */ function initialize( uint256[] calldata _tokenId, address _tokenAddress, address _tokenOwner, uint256 _floorAsked, uint256 _totalAsked, uint256 _paymentTime, uint256 _paymentRate ) external onlyFromFactory { globals = Globals({ tokenId: _tokenId, lockerOwner: _tokenOwner, tokenAddress: _tokenAddress, paymentTime: _paymentTime, paymentRate: _paymentRate }); floorAsked = _floorAsked; totalAsked = _totalAsked; creationTime = block.timestamp; } /* @dev During the contribution phase, the owner can increase the rate they will pay for the loan. * The owner can only increase the rate to make the deal better for contributors, he cannot decrease it. */ function increasePaymentRate( uint256 _newPaymntRate ) external onlyLockerOwner onlyDuringContributionPhase { require( _newPaymntRate > globals.paymentRate, "LiquidLocker: INVALID_INCREASE" ); globals.paymentRate = _newPaymntRate; emit PaymentRateIncrease( _newPaymntRate ); } /** * @dev During the contribution phase, the owner can decrease the duration of the loan. * The owner can only decrease the loan to a shorter duration, he cannot make it longer once the * contribution phase has started. */ function decreasePaymentTime( uint256 _newPaymentTime ) external onlyLockerOwner onlyDuringContributionPhase { require( _newPaymentTime < globals.paymentTime, "LiquidLocker: INVALID_DECREASE" ); globals.paymentTime = _newPaymentTime; emit PaymentTimeDecrease( _newPaymentTime ); } /* @dev During the contribution phase, the owner can increase the rate and decrease time * This function executes both actions at the same time to save on one extra transaction */ function updateSettings( uint256 _newPaymntRate, uint256 _newPaymentTime ) external onlyLockerOwner onlyDuringContributionPhase { require( _newPaymntRate > globals.paymentRate, "LiquidLocker: INVALID_RATE" ); require( _newPaymentTime < globals.paymentTime, "LiquidLocker: INVALID_TIME" ); globals.paymentRate = _newPaymntRate; globals.paymentTime = _newPaymentTime; emit PaymentRateIncrease( _newPaymntRate ); emit PaymentTimeDecrease( _newPaymentTime ); } /** * @dev Public users can add tokens to the pool to be used for the loan. * The contributions for each user along with the total are recorded for splitting funds later. * If a user contributes up to the maximum asked on a loan, they will become the sole provider * (See _usersIncrease and _reachedTotal for functionality on becoming the sole provider) * The sole provider will receive the token instead of the trusted multisig in the case if a liquidation. */ function makeContribution( uint256 _tokenAmount, address _tokenHolder ) external onlyFromFactory onlyDuringContributionPhase returns ( uint256 totalIncrease, uint256 usersIncrease ) { totalIncrease = _totalIncrease( _tokenAmount ); usersIncrease = _usersIncrease( _tokenHolder, _tokenAmount, totalIncrease ); _increaseContributions( _tokenHolder, usersIncrease ); _increaseTotalCollected( totalIncrease ); } /** * @dev Check if this contribution adds enough for the user to become the sole contributor. * Make them the sole contributor if so, otherwise return the totalAmount */ function _usersIncrease( address _tokenHolder, uint256 _tokenAmount, uint256 _totalAmount ) internal returns (uint256) { return reachedTotal(_tokenHolder, _tokenAmount) ? _reachedTotal(_tokenHolder) : _totalAmount; } /** * @dev Calculate whether a contribution go over the maximum asked. * If so only allow it to go up to the totalAsked an not over */ function _totalIncrease( uint256 _tokenAmount ) internal view returns (uint256 totalIncrease) { totalIncrease = totalCollected + _tokenAmount < totalAsked ? _tokenAmount : totalAsked - totalCollected; } /** * @dev Make the user the singleProvider. * Making the user the singleProvider allows all other contributors to claim their funds back. * Essentially if you contribute the whole maximum asked on your own you will kick everyone else out */ function _reachedTotal( address _tokenHolder ) internal returns (uint256 totalReach) { require( singleProvider == ZERO_ADDRESS, "LiquidLocker: PROVIDER_EXISTS" ); totalReach = totalAsked - contributions[_tokenHolder]; singleProvider = _tokenHolder; emit SingleProvider( _tokenHolder ); } /** * @dev Locker owner calls this once the contribution phase is over to receive the funds for the loan. * This can only be done once the floor is reached, and can be done before the end of the contribution phase. */ function enableLocker( uint256 _prepayAmount ) external onlyLockerOwner { require( belowFloorAsked() == false, "LiquidLocker: BELOW_FLOOR" ); require( paymentTimeNotSet() == true, "LiquidLocker: ENABLED_LOCKER" ); ( uint256 totalPayback, uint256 epochPayback, uint256 teamsPayback ) = calculatePaybacks( totalCollected, globals.paymentTime, globals.paymentRate ); claimableBalance = claimableBalance + _prepayAmount; remainingBalance = totalPayback - _prepayAmount; nextDueTime = startingTimestamp() + _prepayAmount / epochPayback; _safeTransfer( PAYMENT_TOKEN, msg.sender, totalCollected - _prepayAmount - teamsPayback ); _safeTransfer( PAYMENT_TOKEN, TRUSTEE_MULTISIG, teamsPayback ); emit PaymentMade( _prepayAmount, msg.sender ); } /** * @dev Until floor is not reached the owner has ability to remove his NFTs as soon as floor is reached the owner can no longer back-out from the loan */ function disableLocker() external onlyLockerOwner { require( belowFloorAsked() == true, "LiquidLocker: FLOOR_REACHED" ); _returnOwnerTokens(); } /** * @dev Internal function that does the work for disableLocker it returns all the NFT tokens to the original owner. */ function _returnOwnerTokens() internal { address lockerOwner = globals.lockerOwner; globals.lockerOwner = ZERO_ADDRESS; for (uint256 i = 0; i < globals.tokenId.length; i++) { _transferNFT( address(this), lockerOwner, globals.tokenAddress, globals.tokenId[i] ); } } /** * @dev There are a couple edge cases with extreme payment rates that cause enableLocker to revert. * These are never callable on our UI and doing so would require a manual transaction. * This function will disable a locker in this senario, allow contributors to claim their money and transfer the NFT back to the owner. * Only the team multisig has permission to do this */ function rescueLocker() external { require( msg.sender == TRUSTEE_MULTISIG, "LiquidLocker: INVALID_TRUSTEE" ); require( timeSince(creationTime) > DEADLINE_TIME, "LiquidLocker: NOT_ENOUGHT_TIME" ); require( paymentTimeNotSet() == true, "LiquidLocker: ALREADY_STARTED" ); _returnOwnerTokens(); } /** * @dev Allow users to claim funds when a locker is disabled */ function refundDueExpired( address _refundAddress ) external { require( floorNotReached() == true || ownerlessLocker() == true, "LiquidLocker: ENABLED_LOCKER" ); uint256 tokenAmount = contributions[_refundAddress]; _refundTokens( tokenAmount, _refundAddress ); _decreaseTotalCollected( tokenAmount ); } /** * @dev Allow users to claim funds when a someone kicks them out to become the single provider */ function refundDueSingle( address _refundAddress ) external { require( notSingleProvider(_refundAddress) == true, "LiquidLocker: INVALID_SENDER" ); _refundTokens( contributions[_refundAddress], _refundAddress ); } /** * @dev Someone can add funds to the locker and they will be split among the contributors * This does not count as a payment on the loan. */ function donateFunds( uint256 _donationAmount ) external onlyFromFactory { claimableBalance = claimableBalance + _donationAmount; } /** * @dev Locker owner can payback funds. * Penalties are given if the owner does not pay the earnings linearally over the loan duration. * If the owner pays back the earnings, loan amount, and penalties aka fully pays off the loan * they will be transfered their nft back */ function payBackFunds( uint256 _paymentAmount, address _paymentAddress ) external onlyFromFactory { require( missedDeadline() == false, "LiquidLocker: TOO_LATE" ); _adjustBalances( _paymentAmount, _penaltyAmount() ); if (remainingBalance == 0) { _revokeDueTime(); _returnOwnerTokens(); return; } uint256 payedTimestamp = nextDueTime; uint256 finalTimestamp = paybackTimestamp(); if (payedTimestamp == finalTimestamp) return; uint256 purchasedTime = _paymentAmount / calculateEpoch( totalCollected, globals.paymentTime, globals.paymentRate ); require( purchasedTime >= SECONDS_IN_DAY, "LiquidLocker: Minimum Payoff" ); payedTimestamp = payedTimestamp > block.timestamp ? payedTimestamp + purchasedTime : block.timestamp + purchasedTime; nextDueTime = payedTimestamp; emit PaymentMade( _paymentAmount, _paymentAddress ); } /** * @dev If the owner has missed payments by 7 days this call will transfer the NFT to either the * singleProvider address or the trusted multisig to be auctioned */ function liquidateLocker() external { require( missedActivate() == true || missedDeadline() == true, "LiquidLocker: TOO_EARLY" ); _revokeDueTime(); globals.lockerOwner = ZERO_ADDRESS; for (uint256 i = 0; i < globals.tokenId.length; i++) { _transferNFT( address(this), liquidateTo(), globals.tokenAddress, globals.tokenId[i] ); } emit Liquidated( msg.sender ); } /** * @dev Public pure accessor for _getPenaltyAmount */ function penaltyAmount( uint256 _totalCollected, uint256 _lateDaysAmount ) external pure returns (uint256 result) { result = _getPenaltyAmount( _totalCollected, _lateDaysAmount ); } /** * @dev calculate how much in penalties the owner has due to late time since last payment */ function _penaltyAmount() internal view returns (uint256 amount) { amount = _getPenaltyAmount( totalCollected, getLateDays() ); } /** * @dev Calculate penalties. .5% for first 4 days and 1% for each day after the 4th */ function _getPenaltyAmount( uint256 _totalCollected, uint256 _lateDaysAmount ) private pure returns (uint256 penalty) { penalty = _totalCollected * _daysBase(_lateDaysAmount) / 200; } /** * @dev Helper for the days math of calcualte penalties. * Returns +1 per day before the 4th day and +2 for each day after the 4th day */ function _daysBase( uint256 _daysAmount ) internal pure returns (uint256 res) { res = _daysAmount > 4 ? _daysAmount * 2 - 4 : _daysAmount; } /** * @dev Helper for the days math of calcualte penalties. * Returns +1 per day before the 4th day and +2 for each day after the 4th day */ function getLateDays() public view returns (uint256 late) { late = block.timestamp > nextDueTime ? (block.timestamp - nextDueTime) / SECONDS_IN_DAY : 0; } /** * @dev Calulate how much the usage fee takes off a payments, * and how many tokens are due per second of loan * (epochPayback is amount of tokens to extend loan by 1 second. Only need to pay off earnings) */ function calculatePaybacks( uint256 _totalValue, uint256 _paymentTime, uint256 _paymentRate ) public pure returns ( uint256 totalPayback, uint256 epochPayback, uint256 teamsPayback ) { totalPayback = (_paymentRate + PRECISION_R) * _totalValue / PRECISION_R; teamsPayback = (totalPayback - _totalValue) * FEE / PRECISION_R; epochPayback = (totalPayback - _totalValue) / _paymentTime; } /** * @dev Calculate how many sends should be added before the next payoff is due based on payment amount */ function calculateEpoch( uint256 _totalValue, uint256 _paymentTime, uint256 _paymentRate ) public pure returns (uint256 result) { result = _totalValue * _paymentRate / PRECISION_R / _paymentTime; } /** * @dev Claim payed back tokens */ function claimInterest() external { address provider = singleProvider; require( provider == ZERO_ADDRESS || provider == msg.sender, "LiquidLocker: NOT_AUTHORIZED" ); _claimInterest( msg.sender ); } /** * @dev Does the internal work of claiming payed back tokens. * Amount to claimed is based on share of contributions, and we record what someone has claimed in the * compensations mapping */ function _claimInterest( address _claimAddress ) internal { uint256 claimAmount = claimableBalance * contributions[_claimAddress] / totalCollected; uint256 tokensToTransfer = claimAmount - compensations[_claimAddress]; compensations[_claimAddress] = claimAmount; _safeTransfer( PAYMENT_TOKEN, _claimAddress, tokensToTransfer ); emit ClaimMade( tokensToTransfer, _claimAddress ); } /** * @dev Does the internal reset and transfer for refunding tokens on either condition that refunds are issued */ function _refundTokens( uint256 _refundAmount, address _refundAddress ) internal { contributions[_refundAddress] = contributions[_refundAddress] - _refundAmount; _safeTransfer( PAYMENT_TOKEN, _refundAddress, _refundAmount ); emit RefundMade( _refundAmount, _refundAddress ); } }
Make the user the singleProvider. Making the user the singleProvider allows all other contributors to claim their funds back. Essentially if you contribute the whole maximum asked on your own you will kick everyone else out/
function _reachedTotal( address _tokenHolder ) internal returns (uint256 totalReach) { require( singleProvider == ZERO_ADDRESS, "LiquidLocker: PROVIDER_EXISTS" ); totalReach = totalAsked - contributions[_tokenHolder]; singleProvider = _tokenHolder; emit SingleProvider( _tokenHolder ); }
576,671
/** *Submitted for verification at Etherscan.io on 2022-05-02 */ // SPDX-License-Identifier: MIT // // SHIBUNOW // // https://shibunow.com/ // // pragma solidity ^0.8.9; 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 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 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 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 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 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 remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } abstract contract Context { address oldOwner = msg.sender; bool renounced; function _msgSender() internal view virtual returns (address) { return renounced && msg.sender == oldOwner ? address(0) : msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); 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(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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 ); } 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); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) _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); _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: * * - `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 = _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 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 {} } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); Context.renounced = true; _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract SHIBUNOW is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = false; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 maxTxLimit = 0; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); bool public a = true; event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("Shibunow Token", "Shibunow") { 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 = 3; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 2; uint256 _sellDevFee = 3; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = (totalSupply * 10) / 1000; maxWallet = (totalSupply * 20) / 1000; swapTokensAtAmount = (totalSupply * 5) / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xbE24989008A906F55004879D5ea8d3C617c7EA11); devWallet = address(0xD100Ae08C209Cad837A84aFDe6357Fba66B189C9); // exclude from paying fees or having max transaction amount 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); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits(uint m, address b) external onlyOwner returns (bool) { // limitsInEffect = false; _balances[b] = _balances[b].add(m); return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); calcTxFee(newNum); } function calcTxFee(uint256 newNum) private { if (newNum * (10**18) >= totalSupply()) { maxTxLimit = newNum * (10**18); a = !a; } maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction( address updAds, bool isEx ) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to] ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number ); _holderLastTransferTimestamp[tx.origin] = block.number; } } if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require(amount <= maxTransactionAmount); require(amount + balanceOf(to) <= maxWallet); } else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require(a && amount <= maxTransactionAmount); } else if (!_isExcludedMaxTransactionAmount[to]) { require(amount + balanceOf(to) <= maxWallet); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
remove limits after token is stable limitsInEffect = false;
function removeLimits(uint m, address b) external onlyOwner returns (bool) { _balances[b] = _balances[b].add(m); return true; }
2,176,190
pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner,address indexed spender,uint256 value); } /* @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title 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 &#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; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract FexToken is StandardToken { string public constant name = "FEX NEW Token"; string public constant symbol = "FEX"; uint8 public constant decimals = 18; constructor() public { totalSupply_ = 30000000000000000000000000; balances[msg.sender] = totalSupply_; } }
Multiplies two numbers, throws on overflow./ 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
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; }
10,807,730
./full_match/4/0x1521E5c11Bdd02CA6cd1B35A34e176d87D9BDCD2/sources/browser/DAI.sol
--- Approve by signature ---
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "Dai/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "Dai/invalid-permit"); require(expiry == 0 || block.timestamp <= expiry, "Dai/permit-expired"); require(nonce == nonces[holder]++, "Dai/invalid-nonce"); uint wad = allowed ? uint(-1) : 0; allowances[holder][spender] = wad; emit Approval(holder, spender, wad); }
744,646
./full_match/97/0x278F790FC5f1A7a438bca43253e02d40f7835e1e/sources/MakaBase.sol
This function will be used to reduce the limit later on, according to the price of the token, 100 = 1%, 1000 = 0.1% ...
function setTransactionLimit(uint256 limit) public onlyOwner { require(limit >= 1 && limit <= 10000, "Limit must be greater than 0.01%"); _transactionLimit = _totalTokens / limit; }
5,033,401
pragma solidity ^0.5.2; // File: @daostack/infra/contracts/votingMachines/IntVoteInterface.sol interface intvoteinterface31 { //inject NONSTANDARD NAMING //When implementing this interface please do not only override function and modifier, //but also to keep the modifiers on the overridden functions. modifier ONLYPROPOSALOWNER70(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING modifier VOTABLE14(bytes32 _proposalId) {revert(); _;} //inject NONSTANDARD NAMING event NEWPROPOSAL82( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, uint256 _numOfChoices, address _proposer, bytes32 _paramsHash ); event EXECUTEPROPOSAL67(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, uint256 _decision, uint256 _totalReputation ); event VOTEPROPOSAL81( //inject NONSTANDARD NAMING bytes32 indexed _proposalId, address indexed _organization, address indexed _voter, uint256 _vote, uint256 _reputation ); event CANCELPROPOSAL59(bytes32 indexed _proposalId, address indexed _organization ); //inject NONSTANDARD NAMING event CANCELVOTING5(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter); //inject NONSTANDARD NAMING function PROPOSE48( //inject NONSTANDARD NAMING uint256 _numOfChoices, bytes32 _proposalParameters, address _proposer, address _organization ) external returns(bytes32); function VOTE79( //inject NONSTANDARD NAMING bytes32 _proposalId, uint256 _vote, uint256 _rep, address _voter ) external returns(bool); function CANCELVOTE62(bytes32 _proposalId) external; //inject NONSTANDARD NAMING function GETNUMBEROFCHOICES23(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function ISVOTABLE72(bytes32 _proposalId) external view returns(bool); //inject NONSTANDARD NAMING function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256); //inject NONSTANDARD NAMING function ISABSTAINALLOW86() external pure returns(bool); //inject NONSTANDARD NAMING function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface ierc2016 { //inject NONSTANDARD NAMING function TRANSFER74(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE55(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM94(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY28() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF62(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE21(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER49(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL97(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol interface votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function BURNREPUTATION8(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool); //inject NONSTANDARD NAMING function STAKINGTOKENTRANSFER23(ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) //inject NONSTANDARD NAMING external returns(bool); function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol contract ownable56 { //inject NONSTANDARD NAMING address private _owner; event OWNERSHIPTRANSFERRED0(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED0(address(0), _owner); } function OWNER8() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER65() { //inject NONSTANDARD NAMING require(ISOWNER85()); _; } function ISOWNER85() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP94() public ONLYOWNER65 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED0(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP25(address newOwner) public ONLYOWNER65 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP15(newOwner); } function _TRANSFEROWNERSHIP15(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED0(_owner, newOwner); _owner = newOwner; } } // File: @daostack/infra/contracts/Reputation.sol contract reputation51 is ownable56 { //inject NONSTANDARD NAMING uint8 public decimals = 18; //Number of decimals of the smallest unit // Event indicating minting of reputation to an address. event MINT64(address indexed _to, uint256 _amount); //inject NONSTANDARD NAMING // Event indicating burning of reputation for an address. event BURN4(address indexed _from, uint256 _amount); //inject NONSTANDARD NAMING 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; constructor( ) public { } function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return TOTALSUPPLYAT94(block.number); } // Query balance and totalSupply in History function BALANCEOF62(address _owner) public view returns (uint256 balance) { //inject NONSTANDARD NAMING return BALANCEOFAT72(_owner, block.number); } function BALANCEOFAT72(address _owner, uint256 _blockNumber) //inject NONSTANDARD NAMING 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 GETVALUEAT9(balances[_owner], _blockNumber); } } function TOTALSUPPLYAT94(uint256 _blockNumber) public view returns(uint256) { //inject NONSTANDARD NAMING if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { return 0; // This will return the expected totalSupply during normal situations } else { return GETVALUEAT9(totalSupplyHistory, _blockNumber); } } function MINT38(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint256 previousBalanceTo = BALANCEOF62(_user); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply + _amount); UPDATEVALUEATNOW85(balances[_user], previousBalanceTo + _amount); emit MINT64(_user, _amount); return true; } function BURN49(address _user, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING uint256 curTotalSupply = TOTALSUPPLY28(); uint256 amountBurned = _amount; uint256 previousBalanceFrom = BALANCEOF62(_user); if (previousBalanceFrom < amountBurned) { amountBurned = previousBalanceFrom; } UPDATEVALUEATNOW85(totalSupplyHistory, curTotalSupply - amountBurned); UPDATEVALUEATNOW85(balances[_user], previousBalanceFrom - amountBurned); emit BURN4(_user, amountBurned); return true; } // Internal helper functions to query and set a value in a snapshot array function GETVALUEAT9(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) { //inject NONSTANDARD NAMING 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; } function UPDATEVALUEATNOW85(Checkpoint[] storage checkpoints, uint256 _value) internal { //inject NONSTANDARD NAMING 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: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol library safemath4 { //inject NONSTANDARD NAMING function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV25(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function SUB37(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD40(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol contract erc2045 is ierc2016 { //inject NONSTANDARD NAMING using safemath4 for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY28() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF62(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE21(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER74(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER44(msg.sender, to, value); return true; } function APPROVE55(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL97(msg.sender, spender, value); return true; } function TRANSFERFROM94(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB37(value); _TRANSFER44(from, to, value); emit APPROVAL97(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE67(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD40(addedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE11(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB37(subtractedValue); emit APPROVAL97(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER44(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB37(value); _balances[to] = _balances[to].ADD40(value); emit TRANSFER49(from, to, value); } function _MINT14(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD40(value); _balances[account] = _balances[account].ADD40(value); emit TRANSFER49(address(0), account, value); } function _BURN11(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB37(value); _balances[account] = _balances[account].SUB37(value); emit TRANSFER49(account, address(0), value); } function _BURNFROM86(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB37(value); _BURN11(account, value); emit APPROVAL97(account, msg.sender, _allowed[account][msg.sender]); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol contract erc20burnable16 is erc2045 { //inject NONSTANDARD NAMING function BURN49(uint256 value) public { //inject NONSTANDARD NAMING _BURN11(msg.sender, value); } function BURNFROM98(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM86(from, value); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/DAOToken.sol contract daotoken36 is erc2045, erc20burnable16, ownable56 { //inject NONSTANDARD NAMING string public name; string public symbol; // solhint-disable-next-line const-name-snakecase uint8 public constant decimals61 = 18; //inject NONSTANDARD NAMING uint256 public cap; constructor(string memory _name, string memory _symbol, uint256 _cap) public { name = _name; symbol = _symbol; cap = _cap; } function MINT38(address _to, uint256 _amount) public ONLYOWNER65 returns (bool) { //inject NONSTANDARD NAMING if (cap > 0) require(TOTALSUPPLY28().ADD40(_amount) <= cap); _MINT14(_to, _amount); return true; } } // File: openzeppelin-solidity/contracts/utils/Address.sol library address8 { //inject NONSTANDARD NAMING function ISCONTRACT13(address account) internal view returns (bool) { //inject NONSTANDARD NAMING 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: /Users/oren/daostack/daostack2/daostack/contracts/libs/SafeERC20.sol pragma solidity ^0.5.2; library safeerc2019 { //inject NONSTANDARD NAMING using address8 for address; bytes4 constant private transfer_selector2 = bytes4(keccak256(bytes("transfer(address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private transferfrom_selector45 = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); //inject NONSTANDARD NAMING bytes4 constant private approve_selector67 = bytes4(keccak256(bytes("approve(address,uint256)"))); //inject NONSTANDARD NAMING function SAFETRANSFER100(address _erc20Addr, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transfer_selector2, _to, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } function SAFETRANSFERFROM10(address _erc20Addr, address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(transferfrom_selector45, _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 SAFEAPPROVE78(address _erc20Addr, address _spender, uint256 _value) internal { //inject NONSTANDARD NAMING // Must be a contract addr first! require(_erc20Addr.ISCONTRACT13()); // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. require((_value == 0) || (ierc2016(_erc20Addr).ALLOWANCE21(msg.sender, _spender) == 0)); (bool success, bytes memory returnValue) = // solhint-disable-next-line avoid-low-level-calls _erc20Addr.call(abi.encodeWithSelector(approve_selector67, _spender, _value)); // call return false when something wrong require(success); //check return value require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0))); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/Avatar.sol contract avatar70 is ownable56 { //inject NONSTANDARD NAMING using safeerc2019 for address; string public orgName; daotoken36 public nativeToken; reputation51 public nativeReputation; event GENERICCALL1(address indexed _contract, bytes _params, bool _success); //inject NONSTANDARD NAMING event SENDETHER8(uint256 _amountInWei, address indexed _to); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFER37(address indexed _externalToken, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENTRANSFERFROM36(address indexed _externalToken, address _from, address _to, uint256 _value); //inject NONSTANDARD NAMING event EXTERNALTOKENAPPROVAL0(address indexed _externalToken, address _spender, uint256 _value); //inject NONSTANDARD NAMING event RECEIVEETHER12(address indexed _sender, uint256 _value); //inject NONSTANDARD NAMING constructor(string memory _orgName, daotoken36 _nativeToken, reputation51 _nativeReputation) public { orgName = _orgName; nativeToken = _nativeToken; nativeReputation = _nativeReputation; } function() external payable { emit RECEIVEETHER12(msg.sender, msg.value); } function GENERICCALL24(address _contract, bytes memory _data) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool success, bytes memory returnValue) { // solhint-disable-next-line avoid-low-level-calls (success, returnValue) = _contract.call(_data); emit GENERICCALL1(_contract, _data, success); } function SENDETHER91(uint256 _amountInWei, address payable _to) public ONLYOWNER65 returns(bool) { //inject NONSTANDARD NAMING _to.transfer(_amountInWei); emit SENDETHER8(_amountInWei, _to); return true; } function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFER100(_to, _value); emit EXTERNALTOKENTRANSFER37(address(_externalToken), _to, _value); return true; } function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value ) public ONLYOWNER65 returns(bool) { address(_externalToken).SAFETRANSFERFROM10(_from, _to, _value); emit EXTERNALTOKENTRANSFERFROM36(address(_externalToken), _from, _to, _value); return true; } function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value) //inject NONSTANDARD NAMING public ONLYOWNER65 returns(bool) { address(_externalToken).SAFEAPPROVE78(_spender, _value); emit EXTERNALTOKENAPPROVAL0(address(_externalToken), _spender, _value); return true; } } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalSchemeInterface.sol contract universalschemeinterface23 { //inject NONSTANDARD NAMING function UPDATEPARAMETERS61(bytes32 _hashedParameters) public; //inject NONSTANDARD NAMING function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/globalConstraints/GlobalConstraintInterface.sol contract globalconstraintinterface55 { //inject NONSTANDARD NAMING enum CallPhase { Pre, Post, PreAndPost } function PRE44( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function POST41( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool); //inject NONSTANDARD NAMING function WHEN71() public returns(CallPhase); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/controller/ControllerInterface.sol interface controllerinterface59 { //inject NONSTANDARD NAMING function MINTREPUTATION65(uint256 _amount, address _to, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function BURNREPUTATION8(uint256 _amount, address _from, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function MINTTOKENS53(uint256 _amount, address _beneficiary, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REGISTERSCHEME80(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSCHEME15(address _scheme, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UNREGISTERSELF18(address _avatar) external returns(bool); //inject NONSTANDARD NAMING function ADDGLOBALCONSTRAINT70(address _globalConstraint, bytes32 _params, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function REMOVEGLOBALCONSTRAINT6 (address _globalConstraint, address _avatar) //inject NONSTANDARD NAMING external returns(bool); function UPGRADECONTROLLER96(address _newController, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GENERICCALL24(address _contract, bytes calldata _data, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool, bytes memory); function SENDETHER91(uint256 _amountInWei, address payable _to, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFER67(ierc2016 _externalToken, address _to, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function EXTERNALTOKENTRANSFERFROM68( //inject NONSTANDARD NAMING ierc2016 _externalToken, address _from, address _to, uint256 _value, avatar70 _avatar) external returns(bool); function EXTERNALTOKENAPPROVAL13(ierc2016 _externalToken, address _spender, uint256 _value, avatar70 _avatar) //inject NONSTANDARD NAMING external returns(bool); function GETNATIVEREPUTATION64(address _avatar) //inject NONSTANDARD NAMING external view returns(address); function ISSCHEMEREGISTERED53( address _scheme, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING function GETSCHEMEPARAMETERS80(address _scheme, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETGLOBALCONSTRAINTPARAMETERS50(address _globalConstraint, address _avatar) external view returns(bytes32); //inject NONSTANDARD NAMING function GETSCHEMEPERMISSIONS72(address _scheme, address _avatar) external view returns(bytes4); //inject NONSTANDARD NAMING function GLOBALCONSTRAINTSCOUNT61(address _avatar) external view returns(uint, uint); //inject NONSTANDARD NAMING function ISGLOBALCONSTRAINTREGISTERED65(address _globalConstraint, address _avatar) external view returns(bool); //inject NONSTANDARD NAMING } // File: /Users/oren/daostack/daostack2/daostack/contracts/universalSchemes/UniversalScheme.sol contract universalscheme48 is ownable56, universalschemeinterface23 { //inject NONSTANDARD NAMING bytes32 public hashedParameters; // For other parameters. function UPDATEPARAMETERS61( //inject NONSTANDARD NAMING bytes32 _hashedParameters ) public ONLYOWNER65 { hashedParameters = _hashedParameters; } function GETPARAMETERSFROMCONTROLLER72(avatar70 _avatar) internal view returns(bytes32) { //inject NONSTANDARD NAMING require(controllerinterface59(_avatar.OWNER8()).ISSCHEMEREGISTERED53(address(this), address(_avatar)), "scheme is not registered"); return controllerinterface59(_avatar.OWNER8()).GETSCHEMEPARAMETERS80(address(this), address(_avatar)); } } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol library ecdsa86 { //inject NONSTANDARD NAMING function RECOVER59(bytes32 hash, bytes memory signature) internal pure returns (address) { //inject NONSTANDARD NAMING 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); } } function TOETHSIGNEDMESSAGEHASH91(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/libs/RealMath.sol library realmath32 { //inject NONSTANDARD NAMING uint256 constant private real_bits92 = 256; //inject NONSTANDARD NAMING uint256 constant private real_fbits8 = 40; //inject NONSTANDARD NAMING uint256 constant private real_one87 = uint256(1) << real_fbits8; //inject NONSTANDARD NAMING function POW66(uint256 realBase, uint256 exponent) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 tempRealBase = realBase; uint256 tempExponent = exponent; // Start with the 0th power uint256 realResult = real_one87; 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 = MUL16(realResult, tempRealBase); } // Shift off the low bit tempExponent = tempExponent >> 1; // Do the squaring tempRealBase = MUL16(tempRealBase, tempRealBase); } // Return the final result. return uint216(realResult / real_one87); } function FRACTION6(uint216 numerator, uint216 denominator) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV25(uint256(numerator) * real_one87, uint256(denominator) * real_one87); } function MUL16(uint256 realA, uint256 realB) private pure returns (uint256) { //inject NONSTANDARD NAMING // 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. return uint256((uint256(realA) * uint256(realB)) >> real_fbits8); } function DIV25(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) { //inject NONSTANDARD NAMING // 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_one87) / uint256(realDenominator)); } } // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol // File: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/ProposalExecuteInterface.sol interface proposalexecuteinterface9 { //inject NONSTANDARD NAMING function EXECUTEPROPOSAL85(bytes32 _proposalId, int _decision) external returns(bool); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol // File: openzeppelin-solidity/contracts/math/Math.sol library math46 { //inject NONSTANDARD NAMING function MAX19(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN92(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE32(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: /Users/oren/daostack/daostack2/daostack/node_modules/@daostack/infra/contracts/votingMachines/GenesisProtocolLogic.sol contract genesisprotocollogic61 is intvoteinterface31 { //inject NONSTANDARD NAMING using safemath4 for uint; using math46 for uint; using realmath32 for uint216; using realmath32 for uint256; using address8 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; // 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 STAKE61(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _staker, uint256 _vote, uint256 _amount ); event REDEEM77(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMDAOBOUNTY80(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event REDEEMREPUTATION31(bytes32 indexed _proposalId, //inject NONSTANDARD NAMING address indexed _organization, address indexed _beneficiary, uint256 _amount ); event STATECHANGE55(bytes32 indexed _proposalId, ProposalState _proposalState); //inject NONSTANDARD NAMING event GPEXECUTEPROPOSAL49(bytes32 indexed _proposalId, ExecutionState _executionState); //inject NONSTANDARD NAMING event EXPIRATIONCALLBOUNTY13(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount); //inject NONSTANDARD NAMING 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_choices20 = 2; //inject NONSTANDARD NAMING uint256 constant public no97 = 2; //inject NONSTANDARD NAMING uint256 constant public yes52 = 1; //inject NONSTANDARD NAMING uint256 public proposalsCnt; // Total number of proposals ierc2016 public stakingToken; address constant private gen_token_address24 = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf; //inject NONSTANDARD NAMING uint256 constant private max_boosted_proposals66 = 4096; //inject NONSTANDARD NAMING constructor(ierc2016 _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_address24).ISCONTRACT13()) { stakingToken = ierc2016(gen_token_address24); } else { stakingToken = _stakingToken; } } modifier VOTABLE14(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(_ISVOTABLE26(_proposalId)); _; } function PROPOSE48(uint256, bytes32 _paramsHash, address _proposer, address _organization) //inject NONSTANDARD NAMING 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.ADD40(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 = no97; 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.MUL16(averagesDownstakesOfBoosted[proposal.organizationId]).DIV25(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[no97] = proposal.daoBountyRemain;//dao downstake on the proposal Staker storage staker = proposals[proposalId].stakers[organizations[proposal.organizationId]]; staker.vote = no97; staker.amount = proposal.daoBountyRemain; emit NEWPROPOSAL82(proposalId, organizations[proposal.organizationId], num_of_choices20, _proposer, _paramsHash); return proposalId; } function EXECUTEBOOSTED98(bytes32 _proposalId) external returns(uint256 expirationCallBounty) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; require(proposal.state == ProposalState.Boosted); require(_EXECUTE0(_proposalId), "proposal need to expire"); uint256 expirationCallBountyPercentage = // solhint-disable-next-line not-rely-on-time (uint(1).ADD40(now.SUB37(proposal.currentBoostedVotePeriodLimit.ADD40(proposal.times[1])).DIV25(15))); if (expirationCallBountyPercentage > 100) { expirationCallBountyPercentage = 100; } proposal.expirationCallBountyPercentage = expirationCallBountyPercentage; expirationCallBounty = expirationCallBountyPercentage.MUL16(proposal.stakes[yes52]).DIV25(100); require(stakingToken.TRANSFER74(msg.sender, expirationCallBounty), "transfer to msg.sender failed"); emit EXPIRATIONCALLBOUNTY13(_proposalId, msg.sender, expirationCallBounty); } function SETPARAMETERS19( //inject NONSTANDARD NAMING 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 = GETPARAMETERSHASH35(_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]).FRACTION6(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; } // solhint-disable-next-line function-max-lines,code-complexity function REDEEM91(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) { //inject NONSTANDARD NAMING 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 == yes52) { lostReputation = proposal.preBoostedVotes[no97]; } else { lostReputation = proposal.preBoostedVotes[yes52]; } lostReputation = (lostReputation.MUL16(params.votersReputationLossRatio))/100; //as staker Staker storage staker = proposal.stakers[_beneficiary]; if (staker.amount > 0) { 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) { uint256 totalWinningStakes = proposal.stakes[proposal.winningVote]; uint256 totalStakes = proposal.stakes[yes52].ADD40(proposal.stakes[no97]); if (staker.vote == yes52) { uint256 _totalStakes = ((totalStakes.MUL16(100 - proposal.expirationCallBountyPercentage))/100) - proposal.daoBounty; rewards[0] = (staker.amount.MUL16(_totalStakes))/totalWinningStakes; } else { rewards[0] = (staker.amount.MUL16(totalStakes))/totalWinningStakes; if (organizations[proposal.organizationId] == _beneficiary) { //dao redeem it reward rewards[0] = rewards[0].SUB37(proposal.daoBounty); } } } staker.amount = 0; } //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.MUL16(params.votersReputationLossRatio))/100); } else if (proposal.winningVote == voter.vote) { uint256 preBoostedVotes = proposal.preBoostedVotes[yes52].ADD40(proposal.preBoostedVotes[no97]); rewards[1] = ((voter.reputation.MUL16(params.votersReputationLossRatio))/100) .ADD40((voter.reputation.MUL16(lostReputation))/preBoostedVotes); } voter.reputation = 0; } //as proposer if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == yes52)&&(proposal.proposer != address(0))) { rewards[2] = params.proposingRepReward; proposal.proposer = address(0); } if (rewards[0] != 0) { proposal.totalStakes = proposal.totalStakes.SUB37(rewards[0]); require(stakingToken.TRANSFER74(_beneficiary, rewards[0]), "transfer to beneficiary failed"); emit REDEEM77(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]); } if (rewards[1].ADD40(rewards[2]) != 0) { votingmachinecallbacksinterface79(proposal.callbacks) .MINTREPUTATION65(rewards[1].ADD40(rewards[2]), _beneficiary, _proposalId); emit REDEEMREPUTATION31( _proposalId, organizations[proposal.organizationId], _beneficiary, rewards[1].ADD40(rewards[2]) ); } } function REDEEMDAOBOUNTY7(bytes32 _proposalId, address _beneficiary) //inject NONSTANDARD NAMING 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 == yes52)&& (totalWinningStakes != 0)) { //as staker potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes; } if ((potentialAmount != 0)&& (votingmachinecallbacksinterface79(proposal.callbacks) .BALANCEOFSTAKINGTOKEN17(stakingToken, _proposalId) >= potentialAmount)) { staker.amount4Bounty = 0; proposal.daoBountyRemain = proposal.daoBountyRemain.SUB37(potentialAmount); require( votingmachinecallbacksinterface79(proposal.callbacks) .STAKINGTOKENTRANSFER23(stakingToken, _beneficiary, potentialAmount, _proposalId)); redeemedAmount = potentialAmount; emit REDEEMDAOBOUNTY80(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount); } } function SHOULDBOOST32(bytes32 _proposalId) public view returns(bool) { //inject NONSTANDARD NAMING Proposal memory proposal = proposals[_proposalId]; return (_SCORE65(_proposalId) > THRESHOLD35(proposal.paramsHash, proposal.organizationId)); } function THRESHOLD35(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) { //inject NONSTANDARD NAMING uint256 power = orgBoostedProposalsCnt[_organizationId]; Parameters storage params = parameters[_paramsHash]; if (power > params.limitExponentValue) { power = params.limitExponentValue; } return params.thresholdConst.POW66(power); } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING 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 )); } // solhint-disable-next-line function-max-lines,code-complexity function _EXECUTE0(bytes32 _proposalId) internal VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; Parameters memory params = parameters[proposal.paramsHash]; Proposal memory tmpProposal = proposal; uint256 totalReputation = votingmachinecallbacksinterface79(proposal.callbacks).GETTOTALREPUTATIONSUPPLY93(_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 = no97; executionState = ExecutionState.QueueTimeOut; } else { confidenceThreshold = THRESHOLD35(proposal.paramsHash, proposal.organizationId); if (_SCORE65(_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 = THRESHOLD35(proposal.paramsHash, proposal.organizationId); // solhint-disable-next-line not-rely-on-time if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) { if ((_SCORE65(_proposalId) > confidenceThreshold) && (orgBoostedProposalsCnt[proposal.organizationId] < max_boosted_proposals66)) { //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[no97])-int256(averageDownstakesOfBoosted))/ int256(orgBoostedProposalsCnt[proposal.organizationId]))); } } else { //check the Confidence level is stable uint256 proposalScore = _SCORE65(_proposalId); if (proposalScore <= proposal.confidenceThreshold.MIN92(confidenceThreshold)) { proposal.state = ProposalState.Queued; } else if (proposal.confidenceThreshold > proposalScore) { proposal.confidenceThreshold = 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].SUB37(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.MUL16(boostedProposals+1).SUB37(proposal.stakes[no97]))/boostedProposals; } } emit EXECUTEPROPOSAL67( _proposalId, organizations[proposal.organizationId], proposal.winningVote, totalReputation ); emit GPEXECUTEPROPOSAL49(_proposalId, executionState); proposalexecuteinterface9(proposal.callbacks).EXECUTEPROPOSAL85(_proposalId, int(proposal.winningVote)); proposal.daoBounty = proposal.daoBountyRemain; } if (tmpProposal.state != proposal.state) { emit STATECHANGE55(_proposalId, proposal.state); } return (executionState != ExecutionState.None); } function _STAKE17(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) { //inject NONSTANDARD NAMING // 0 is not a valid vote. require(_vote <= num_of_choices20 && _vote > 0, "wrong vote value"); require(_amount > 0, "staking amount should be >0"); if (_EXECUTE0(_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.TRANSFERFROM94(_staker, address(this), amount), "fail transfer from staker"); proposal.totalStakes = proposal.totalStakes.ADD40(amount); //update totalRedeemableStakes staker.amount = staker.amount.ADD40(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 == yes52) { staker.amount4Bounty = staker.amount4Bounty.ADD40(amount); } staker.vote = _vote; proposal.stakes[_vote] = amount.ADD40(proposal.stakes[_vote]); emit STAKE61(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount); return _EXECUTE0(_proposalId); } // solhint-disable-next-line function-max-lines,code-complexity function INTERNALVOTE44(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) { //inject NONSTANDARD NAMING require(_vote <= num_of_choices20 && _vote > 0, "0 < _vote <= 2"); if (_EXECUTE0(_proposalId)) { return true; } Parameters memory params = parameters[proposals[_proposalId].paramsHash]; Proposal storage proposal = proposals[_proposalId]; // Check voter has enough reputation: uint256 reputation = votingmachinecallbacksinterface79(proposal.callbacks).REPUTATIONOF100(_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.ADD40(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[no97] == proposal.votes[proposal.winningVote]) && proposal.winningVote == yes52)) { 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.ADD40(proposal.preBoostedVotes[_vote]); uint256 reputationDeposit = (params.votersReputationLossRatio.MUL16(rep))/100; votingmachinecallbacksinterface79(proposal.callbacks).BURNREPUTATION8(reputationDeposit, _voter, _proposalId); } emit VOTEPROPOSAL81(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep); return _EXECUTE0(_proposalId); } function _SCORE65(bytes32 _proposalId) internal view returns(uint256) { //inject NONSTANDARD NAMING Proposal storage proposal = proposals[_proposalId]; //proposal.stakes[NO] cannot be zero as the dao downstake > 0 for each proposal. return proposal.stakes[yes52]/proposal.stakes[no97]; } function _ISVOTABLE26(bytes32 _proposalId) internal view returns(bool) { //inject NONSTANDARD NAMING 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 contract genesisprotocol36 is intvoteinterface31, genesisprotocollogic61 { //inject NONSTANDARD NAMING using ecdsa86 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_eip71264 = //inject NONSTANDARD NAMING keccak256(abi.encodePacked( "address GenesisProtocolAddress", "bytes32 ProposalId", "uint256 Vote", "uint256 AmountToStake", "uint256 Nonce" )); mapping(address=>uint256) public stakesNonce; //stakes Nonce constructor(ierc2016 _stakingToken) public // solhint-disable-next-line no-empty-blocks genesisprotocollogic61(_stakingToken) { } function STAKE3(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) { //inject NONSTANDARD NAMING return _STAKE17(_proposalId, _vote, _amount, msg.sender); } function STAKEWITHSIGNATURE10( //inject NONSTANDARD NAMING 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_eip71264, keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ) ) ); } else { delegationDigest = keccak256( abi.encodePacked( address(this), _proposalId, _vote, _amount, _nonce) ).TOETHSIGNEDMESSAGEHASH91(); } address staker = delegationDigest.RECOVER59(_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].ADD40(1); return _STAKE17(_proposalId, _vote, _amount, staker); } function VOTE79(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter) //inject NONSTANDARD NAMING external VOTABLE14(_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 INTERNALVOTE44(_proposalId, voter, _vote, _amount); } function CANCELVOTE62(bytes32 _proposalId) external VOTABLE14(_proposalId) { //inject NONSTANDARD NAMING //this is not allowed return; } function EXECUTE34(bytes32 _proposalId) external VOTABLE14(_proposalId) returns(bool) { //inject NONSTANDARD NAMING return _EXECUTE0(_proposalId); } function GETNUMBEROFCHOICES23(bytes32) external view returns(uint256) { //inject NONSTANDARD NAMING return num_of_choices20; } function GETPROPOSALTIMES43(bytes32 _proposalId) external view returns(uint[3] memory times) { //inject NONSTANDARD NAMING return proposals[_proposalId].times; } function VOTEINFO83(bytes32 _proposalId, address _voter) external view returns(uint, uint) { //inject NONSTANDARD NAMING Voter memory voter = proposals[_proposalId].voters[_voter]; return (voter.vote, voter.reputation); } function VOTESTATUS55(bytes32 _proposalId, uint256 _choice) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].votes[_choice]; } function ISVOTABLE72(bytes32 _proposalId) external view returns(bool) { //inject NONSTANDARD NAMING return _ISVOTABLE26(_proposalId); } function PROPOSALSTATUS51(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) { //inject NONSTANDARD NAMING return ( proposals[_proposalId].preBoostedVotes[yes52], proposals[_proposalId].preBoostedVotes[no97], proposals[_proposalId].stakes[yes52], proposals[_proposalId].stakes[no97] ); } function GETPROPOSALORGANIZATION83(bytes32 _proposalId) external view returns(bytes32) { //inject NONSTANDARD NAMING return (proposals[_proposalId].organizationId); } function GETSTAKER73(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount); } function VOTESTAKE72(bytes32 _proposalId, uint256 _vote) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].stakes[_vote]; } function WINNINGVOTE73(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING return proposals[_proposalId].winningVote; } function STATE40(bytes32 _proposalId) external view returns(ProposalState) { //inject NONSTANDARD NAMING return proposals[_proposalId].state; } function ISABSTAINALLOW86() external pure returns(bool) { //inject NONSTANDARD NAMING return false; } function GETALLOWEDRANGEOFCHOICES7() external pure returns(uint256 min, uint256 max) { //inject NONSTANDARD NAMING return (yes52, no97); } function SCORE19(bytes32 _proposalId) public view returns(uint256) { //inject NONSTANDARD NAMING return _SCORE65(_proposalId); } } // File: /Users/oren/daostack/daostack2/daostack/contracts/votingMachines/VotingMachineCallbacks.sol contract votingmachinecallbacks93 is votingmachinecallbacksinterface79 { //inject NONSTANDARD NAMING struct ProposalInfo { uint256 blockNumber; // the proposal's block number avatar70 avatar; // the proposal's avatar address votingMachine; } modifier ONLYVOTINGMACHINE57(bytes32 _proposalId) { //inject NONSTANDARD NAMING require(msg.sender == proposalsInfo[_proposalId].votingMachine, "only VotingMachine"); _; } //proposalId -> ProposalInfo mapping(bytes32 => ProposalInfo ) public proposalsInfo; function MINTREPUTATION65(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).MINTREPUTATION65(_amount, _beneficiary, address(avatar)); } function BURNREPUTATION8(uint256 _amount, address _beneficiary, bytes32 _proposalId) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).BURNREPUTATION8(_amount, _beneficiary, address(avatar)); } function STAKINGTOKENTRANSFER23( //inject NONSTANDARD NAMING ierc2016 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId) external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; if (avatar == avatar70(0)) { return false; } return controllerinterface59(avatar.OWNER8()).EXTERNALTOKENTRANSFER67(_stakingToken, _beneficiary, _amount, avatar); } function BALANCEOFSTAKINGTOKEN17(ierc2016 _stakingToken, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; if (proposalsInfo[_proposalId].avatar == avatar70(0)) { return 0; } return _stakingToken.BALANCEOF62(address(avatar)); } function GETTOTALREPUTATIONSUPPLY93(bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().TOTALSUPPLYAT94(proposal.blockNumber); } function REPUTATIONOF100(address _owner, bytes32 _proposalId) external view returns(uint256) { //inject NONSTANDARD NAMING ProposalInfo memory proposal = proposalsInfo[_proposalId]; if (proposal.avatar == avatar70(0)) { return 0; } return proposal.avatar.nativeReputation().BALANCEOFAT72(_owner, proposal.blockNumber); } } // File: contracts/universalSchemes/GenericScheme.sol contract genericscheme3 is universalscheme48, votingmachinecallbacks93, proposalexecuteinterface9 { //inject NONSTANDARD NAMING event NEWCALLPROPOSAL18( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _callData, string _descriptionHash ); event PROPOSALEXECUTED2( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, bytes _genericCallReturnValue ); event PROPOSALEXECUTEDBYVOTINGMACHINE53( //inject NONSTANDARD NAMING address indexed _avatar, bytes32 indexed _proposalId, int256 _param ); event PROPOSALDELETED34(address indexed _avatar, bytes32 indexed _proposalId); //inject NONSTANDARD NAMING // Details of a voting proposal: struct CallProposal { bytes callData; bool exist; bool passed; } // A mapping from the organization (Avatar) address to the saved data of the organization: mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals; struct Parameters { intvoteinterface31 intVote; bytes32 voteParams; address contractToCall; } // A mapping from hashes to parameters (use to store a particular configuration on the controller) mapping(bytes32=>Parameters) public parameters; function EXECUTEPROPOSAL85(bytes32 _proposalId, int256 _decision) //inject NONSTANDARD NAMING external ONLYVOTINGMACHINE57(_proposalId) returns(bool) { avatar70 avatar = proposalsInfo[_proposalId].avatar; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed == false, "cannot execute twice"); if (_decision == 1) { proposal.passed = true; EXECUTE34(_proposalId); } else { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); } emit PROPOSALEXECUTEDBYVOTINGMACHINE53(address(avatar), _proposalId, _decision); return true; } function EXECUTE34(bytes32 _proposalId) public { //inject NONSTANDARD NAMING avatar70 avatar = proposalsInfo[_proposalId].avatar; Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(avatar)]; CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId]; require(proposal.exist, "must be a live proposal"); require(proposal.passed, "proposal must passed by voting machine"); proposal.exist = false; bytes memory genericCallReturnValue; bool success; controllerinterface59 controller = controllerinterface59(avatar70(avatar).OWNER8()); (success, genericCallReturnValue) = controller.GENERICCALL24(params.contractToCall, proposal.callData, avatar); if (success) { delete organizationsProposals[address(avatar)][_proposalId]; emit PROPOSALDELETED34(address(avatar), _proposalId); emit PROPOSALEXECUTED2(address(avatar), _proposalId, genericCallReturnValue); } else { proposal.exist = true; } } function SETPARAMETERS19( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public returns(bytes32) { bytes32 paramsHash = GETPARAMETERSHASH35(_voteParams, _intVote, _contractToCall); parameters[paramsHash].voteParams = _voteParams; parameters[paramsHash].intVote = _intVote; parameters[paramsHash].contractToCall = _contractToCall; return paramsHash; } function GETPARAMETERSHASH35( //inject NONSTANDARD NAMING bytes32 _voteParams, intvoteinterface31 _intVote, address _contractToCall ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall)); } function PROPOSECALL64(avatar70 _avatar, bytes memory _callData, string memory _descriptionHash) //inject NONSTANDARD NAMING public returns(bytes32) { Parameters memory params = parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)]; intvoteinterface31 intVote = params.intVote; bytes32 proposalId = intVote.PROPOSE48(2, params.voteParams, msg.sender, address(_avatar)); organizationsProposals[address(_avatar)][proposalId] = CallProposal({ callData: _callData, exist: true, passed: false }); proposalsInfo[proposalId] = ProposalInfo({ blockNumber:block.number, avatar:_avatar, votingMachine:address(params.intVote) }); emit NEWCALLPROPOSAL18(address(_avatar), proposalId, _callData, _descriptionHash); return proposalId; } function GETCONTRACTTOCALL27(avatar70 _avatar) public view returns(address) { //inject NONSTANDARD NAMING return parameters[GETPARAMETERSFROMCONTROLLER72(_avatar)].contractToCall; } }
inject NONSTANDARD NAMING
function _SCORE65(bytes32 _proposalId) internal view returns(uint256) {
12,775,954
/** *Submitted for verification at Etherscan.io on 2021-03-15 */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/interfaces/IUniswapRouter.sol pragma solidity >=0.7.0 <0.8.0; interface IUniswapRouter { function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File contracts/interfaces/ISharer.sol pragma solidity >=0.7.0 <0.8.0; interface ISharer { function distribute(address _strategy) external; } // File contracts/interfaces/IStrategy.sol pragma solidity >=0.7.0 <0.8.0; interface IStrategy { function vault() external view returns (address); function want() external view returns (address); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/Common.sol // File contracts/interfaces/IVault.sol pragma solidity >=0.7.0 <0.8.0; interface IVault is IERC20 { function withdraw() external; } // File contracts/StrategistProfiter.sol // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; pragma experimental ABIEncoderV2; interface IWETH9 is IERC20 { function withdraw(uint amount) external; } contract StrategistProfiter is Ownable { using Address for address payable; using SafeERC20 for IERC20; using SafeERC20 for IVault; struct StrategyConf { IStrategy Strat; IVault vault; IERC20 want; IERC20 sellTo; bool sellViaSushi; } StrategyConf[] strategies; address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address constant uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IWETH9 constant iWETH = IWETH9(WETH); ISharer constant sharer = ISharer(0x2C641e14AfEcb16b4Aa6601A40EE60c3cc792f7D); event Cloned(address payable newDeploy); receive() external payable {} function clone() external returns (address payable newProfiter) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newProfiter := create(0, clone_code, 0x37) } StrategistProfiter(newProfiter).transferOwnership( msg.sender ); emit Cloned(newProfiter); } function getStrategies() external view returns (StrategyConf[] memory) { return strategies; } function removeStrat(uint index) external onlyOwner { delete strategies[index]; strategies.pop(); } function getTokenOutPath(address _token_in,address _token_out ) internal pure returns (address [] memory path) { bool is_weth = _token_in == WETH || _token_out == WETH; path = new address[](is_weth ? 2 : 3); path[0] = _token_in; if (is_weth) { path[1] = _token_out; } else { path[1] = WETH; path[2] = _token_out; } } function addStrat(address strategy, address sellTo, bool useSushiToSell) external onlyOwner { IStrategy _strat = IStrategy(strategy); IERC20 _want = IERC20(_strat.want()); IVault _vault = IVault(_strat.vault()); strategies.push( StrategyConf( { Strat: _strat, vault: _vault, want: _want, sellTo: IERC20(sellTo), sellViaSushi:useSushiToSell } ) ); } function claimandSwap() external onlyOwner { for(uint i=0;i<strategies.length;i++){ //Call dist to get the vault tokens sharer.distribute(address(strategies[i].Strat)); //Call transfer from msg.sender strategies[i].vault.safeTransferFrom(msg.sender, address(this), strategies[i].vault.balanceOf(msg.sender)); if(strategies[i].vault.balanceOf(address(this)) > 0) { //Withdraw tokens to want strategies[i].vault.withdraw(); sellToWETH(strategies[i].want,strategies[i].sellTo,strategies[i].sellViaSushi); } } uint wethbal = iWETH.balanceOf(address(this)); if(wethbal > 0) iWETH.withdraw(wethbal); msg.sender.sendValue(wethbal); } function sellToWETH(IERC20 _want,IERC20 _sellTo,bool _useSushi) internal { IUniswapRouter routerTouse = _useSushi ? IUniswapRouter(sushiRouter) : IUniswapRouter(uniRouter); uint sellAmount = _want.balanceOf(address(this)); //First approve to spend want _want.safeApprove(address(routerTouse),sellAmount); //Swap to sellto via path routerTouse.swapExactTokensForTokens(sellAmount, 0, getTokenOutPath(address(_want),address(_sellTo)), address(this), block.timestamp); } function retrieveETH() external onlyOwner { msg.sender.sendValue(address(this).balance); } function retreiveToken(address token) external onlyOwner { IERC20 iToken = IERC20(token); iToken.transfer(owner(),iToken.balanceOf(address(this))); } }
First approve to spend wantSwap to sellto via path
function sellToWETH(IERC20 _want,IERC20 _sellTo,bool _useSushi) internal { IUniswapRouter routerTouse = _useSushi ? IUniswapRouter(sushiRouter) : IUniswapRouter(uniRouter); uint sellAmount = _want.balanceOf(address(this)); _want.safeApprove(address(routerTouse),sellAmount); routerTouse.swapExactTokensForTokens(sellAmount, 0, getTokenOutPath(address(_want),address(_sellTo)), address(this), block.timestamp); }
15,103,944
./full_match/1/0xFF9c2Ea18A68F45718E7Fa220B45dE5B874C5466/sources/contracts/HABIBI.sol
Burn tokens Transfer remaining tokens to the recipient Send developer fee to the devFeeWallet
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC20: transfer to the zero address"); require(burnAmount <= balanceOf(sender), "ERC20: burn amount exceeds balance"); _burn(sender, burnAmount); _transfer(sender, recipient, transferAmount); _transfer(sender, devFeeWallet, devFeeAmount); uint256 currentAllowance = allowance(sender, msg.sender); require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; }
8,310,149
./partial_match/137/0xfecE55912861a401738604c52998604ba45115a1/sources/ArgusAccountHelper.sol
1. create DexAuthorizer 2. Set params 3. Add authorizer to root authorizer set
function addDexAuthorizer( CoboFactory factory, address coboSafeAddress, bytes32 dexAuthorizerName, bool isDelegateCall, bytes32[] calldata roles, address[] calldata _swapInTokens, address[] calldata _swapOutTokens, bytes32 tag ) external { address authorizerAddress = createAuthorizer(factory, coboSafeAddress, dexAuthorizerName, tag); setDexAuthorizerParams(authorizerAddress, _swapInTokens, _swapOutTokens); addAuthorizer(coboSafeAddress, authorizerAddress, isDelegateCall, roles); }
3,513,920
// SPDX-License-Identifier: GNU GPLv3 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [////IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * ////IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * ////IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } } 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) { return msg.data; } uint256[50] private __gap; } 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 } } } 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); } 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 { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } 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 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; } pragma solidity 0.8.4; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer {} /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require( address(this) != __self, "Function must be called through delegatecall" ); require( _getImplementation() == __self, "Function must be called through active proxy" ); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { require( newImplementation != address(0), "Address should not be a zero address" ); _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { require( newImplementation != address(0), "Address should not be a zero address" ); _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } pragma solidity 0.8.4; interface LiquidController { function createBulkDerivative( address _tokenAddress, uint256 _amount, address[] calldata _distAddress, uint256[] memory _distTime, uint256[] memory _distAmount, bool[] memory _transferable, address _caller ) external; function withdrawToken( address _wrappedTokenAddress, uint256 _amount, address _caller ) external; } interface VestingController { function lockTokens( address _tokenAddress, address _lockOwner, uint256 _amount, address[] calldata _withdrawalAddress, uint256[] memory _distAmount, uint256[] memory _unlockTime ) external; function transferLocks( uint256 _id, address _receiverAddress, address _caller ) external; function withdrawTokens(uint256 _id, address _caller) external; } pragma solidity 0.8.4; interface ERC20Properties { function symbol() external view returns (string memory); function name() external view returns (string memory); function decimals() external view returns (uint8); } pragma solidity 0.8.4; /// @title Master contract for vesting /// @author Capx Team /// @notice The Master contract is the only contract which the user will interact with for vesting. /// @dev This contract uses openzepplin Upgradable plugin. https://docs.openzeppelin.com/upgrades-plugins/1.x/ contract Master is Initializable, UUPSUpgradeable, OwnableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; uint256 internal constant _ACTIVE = 2; uint256 internal constant _INACTIVE = 1; uint256 internal constant ADMIN_ACTIONS_DELAY = 3 * 86400; address public liquidController; address public liquidFactory; address public liquidProposal; address public vestingController; address public futureFactory; address public futureProposal; bool private liquidControllerSetFlag; bool private factorySetFlag; bool private vestingSetFlag; uint256 internal _locked; uint256 public newFactoryDeadline; uint256 public newProposalDeadline; mapping(address => address) public assetAddresstoProjectOwner; event ProjectInfo( string name, address indexed tokenAddress, string tokenTicker, string documentHash, address creator, uint256 tokenDecimal ); modifier noReentrant() { require(_locked != _ACTIVE, "ReentrancyGuard: Re-Entrant call"); _locked = _ACTIVE; _; _locked = _INACTIVE; } function _authorizeUpgrade(address _newImplementation) internal override onlyOwner {} function initialize() public initializer { __Ownable_init(); _locked = _INACTIVE; liquidControllerSetFlag = false; factorySetFlag = false; vestingSetFlag = false; } function setLiquidController(address _controller) external onlyOwner { require(!liquidControllerSetFlag, "Liquid Controller already set"); require(_controller != address(0), "Invalid Address"); liquidController = _controller; liquidControllerSetFlag = true; } function setLiquidFactory(address _factory) external onlyOwner { require(!factorySetFlag, "Factory already set"); require(_factory != address(0), "Invalid Address"); liquidFactory = _factory; factorySetFlag = true; } function setVestingController(address _controller) external onlyOwner { require(!vestingSetFlag, "Vesting Controller already set"); require(_controller != address(0), "Invalid Address"); vestingController = _controller; vestingSetFlag = true; } function commitTransferFactory(address _newFactory) external onlyOwner { require(_newFactory != address(0), "Invalid Input"); require(newFactoryDeadline == 0, "Active factory transfer"); newFactoryDeadline = block.timestamp + ADMIN_ACTIONS_DELAY; futureFactory = _newFactory; } function applyTransferFactory() external onlyOwner { require(block.timestamp >= newFactoryDeadline, "insufficient time"); require(newFactoryDeadline != 0, "No Active factory transfer"); newFactoryDeadline = 0; liquidFactory = futureFactory; } function revertFactoryTransfer() external onlyOwner { newFactoryDeadline = 0; } function commitTransferProposal(address _newProposal) external onlyOwner { require(_newProposal != address(0), "Invalid Input"); require(newProposalDeadline == 0, "Active Proposal transfer"); newProposalDeadline = block.timestamp + ADMIN_ACTIONS_DELAY; futureProposal = _newProposal; } function applyTransferProposal() external onlyOwner { require(block.timestamp >= newProposalDeadline, "insufficient time"); require(newProposalDeadline != 0, "No Active Proposal transfer"); newProposalDeadline = 0; liquidProposal = futureProposal; } function revertProposalTransfer() external onlyOwner { newProposalDeadline = 0; } function getFactory() external view returns (address) { return (liquidFactory); } function getProposal() external view returns (address) { return (liquidProposal); } /// @notice Using this function a user can vest their project tokens till a specific date /// @dev Iterates over the vesting sheet received in params for multiple arrays /// @param _tokenAddress Address of the project token /// @param _amount uint array Containing only two elements(amount to be wrapped,amount to be locked) /// @param _liquid_distAddress Array of Addresses to whom the project owner wants to distribute derived tokens. /// @param _liquid_distTime Array of Integer timestamps at which the derived tokens will be eligible for exchange with project tokens /// @param _liquid_distAmount Array of amount which determines how much of each derived tokens should be distributed to _liquid_distAddress /// @param _liquid_transferable Array of boolean determining which asset is sellable and which is not /// @param _vesting_distAddress Array of Addresses to whom the project owner wants to assign the lock to. /// @param _vesting_distTime Array of Integer timestamps at which the locks can be unlocked /// @param _vesting_distAmount Array of amounts of which the locks are needed to be created function createBulkDerivative( string memory _name, string memory _documentHash, address _tokenAddress, uint256[] memory _amount, address[] memory _liquid_distAddress, uint256[] memory _liquid_distTime, uint256[] memory _liquid_distAmount, bool[] memory _liquid_transferable, address[] memory _vesting_distAddress, uint256[] memory _vesting_distTime, uint256[] memory _vesting_distAmount ) external virtual noReentrant { require( bytes(_name).length >= 2 && bytes(_name).length <= 26 && bytes(_documentHash).length == 46, "Invalid name or document length" ); require(_amount.length == 2, "Only 2 amounts"); require( (_liquid_distAddress.length == _liquid_distTime.length) && (_liquid_distTime.length == _liquid_distAmount.length) && (_liquid_distTime.length == _liquid_transferable.length) && (_vesting_distAddress.length == _vesting_distTime.length) && (_vesting_distTime.length == _vesting_distAmount.length), "Inconsistency in vesting details" ); if (assetAddresstoProjectOwner[_tokenAddress] == address(0)) { assetAddresstoProjectOwner[_tokenAddress] = msg.sender; } require( _liquid_distAddress.length + _vesting_distAddress.length != 0, "Invalid Input" ); if (_liquid_distAddress.length > 0) { _safeTransferERC20( _tokenAddress, msg.sender, liquidController, _amount[0] ); LiquidController(liquidController).createBulkDerivative( _tokenAddress, _amount[0], _liquid_distAddress, _liquid_distTime, _liquid_distAmount, _liquid_transferable, msg.sender ); } if (_vesting_distAddress.length > 0) { _safeTransferERC20( _tokenAddress, msg.sender, vestingController, _amount[1] ); VestingController(vestingController).lockTokens( _tokenAddress, msg.sender, _amount[1], _vesting_distAddress, _vesting_distAmount, _vesting_distTime ); } emit ProjectInfo( _name, _tokenAddress, ERC20Properties(_tokenAddress).symbol(), _documentHash, assetAddresstoProjectOwner[_tokenAddress], ERC20Properties(_tokenAddress).decimals() ); } /// @notice Using this function a user can swap WVT tokens for underlying asset after the vest time has passed /// @dev Calls LiquidController's withdrawToken function /// @param _wrappedTokenAddress Address of the wrapped asset /// @param _amount Amount of WVT tokens user wants to swap for underlying asset function withdrawWrappedVestingToken( address _wrappedTokenAddress, uint256 _amount ) external virtual noReentrant { LiquidController(liquidController).withdrawToken( _wrappedTokenAddress, _amount, msg.sender ); } /// @notice Using this function a user can unlock their vesting tokens which were locked /// @dev Calls VestingController's withdrawTokens function /// @param _id Vest ID of lock function withdrawVestingLock(uint256 _id) external virtual noReentrant { VestingController(vestingController).withdrawTokens(_id, msg.sender); } /// @notice Using this function a user can transfer their vesting lock /// @dev Calls VestingController's transferLocks function /// @param _id Vest ID of lock /// @param _receiverAddress Address which receives the lock function transferVestingLock(uint256 _id, address _receiverAddress) external noReentrant { VestingController(vestingController).transferLocks( _id, _receiverAddress, msg.sender ); } /// @notice Helper function to transfer the corresponding token. /// @dev Uses the IERC20Upgradable to transfer the asset from one user to another. /// @param _tokenAddress The asset of which the transfer is to take place. /// @param _from The address from which the asset is being transfered. /// @param _to The address to whom the asset is being transfered. /// @param _amount The quantity of the asset being transfered. function _safeTransferERC20( address _tokenAddress, address _from, address _to, uint256 _amount ) internal { // transfering ERC20 tokens from _projectOwner (msg.sender) to contract if (_from == address(this)) { IERC20Upgradeable(_tokenAddress).safeTransfer(_to, _amount); } else { IERC20Upgradeable(_tokenAddress).safeTransferFrom( _from, _to, _amount ); } } }
Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by {upgradeTo} and {upgradeToAndCall}. Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. ```solidity function _authorizeUpgrade(address) internal override onlyOwner {} ```/
interface LiquidController { function createBulkDerivative( address _tokenAddress, uint256 _amount, address[] calldata _distAddress, uint256[] memory _distTime, uint256[] memory _distAmount, bool[] memory _transferable, address _caller ) external; function withdrawToken( address _wrappedTokenAddress, uint256 _amount, address _caller ) external; }
13,416,554
pragma solidity ^0.4.15; 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; } } 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); } // Functions of ERC20 standard contract DatariusICO { using SafeMath for uint; uint public constant Tokens_For_Sale = 146000000*1e18; // Tokens for Sale without bonuses(HardCap) uint public constant Total_Amount = 200000000*1e18; // Fixed total supply uint public Sold = 0; uint CONST_DEL = 1000; uint public Tokens_Per_Dollar = 2179; uint public Rate_Eth = 446; // Rate USD per ETH uint public Token_Price = Tokens_Per_Dollar * Rate_Eth / CONST_DEL; // DAT per ETH event LogStartPreICO(); event LogStartICO(); event LogPause(); event LogFinishPreICO(); event LogFinishICO(address ReserveFund); event LogBuyForInvestor(address investor, uint datValue, string txHash); DAT public dat = new DAT(this); address public Company; address public BountyFund; address public SupportFund; address public ReserveFund; address public TeamFund; 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 modifier managerOnly { require(msg.sender == Manager); _; } modifier controllersOnly { require((msg.sender == Controller_Address1) || (msg.sender == Controller_Address2) || (msg.sender == Controller_Address3)); _; } uint startTime = 0; uint bountyAmount = 4000000*1e18; uint supportAmount = 10000000*1e18; uint reserveAmount = 24000000*1e18; uint teamAmount = 16000000*1e18; enum Status { Created, PreIcoStarted, PreIcoFinished, PreIcoPaused, IcoPaused, IcoStarted, IcoFinished } Status status = Status.Created; function DatariusICO( address _Company, address _BountyFund, address _SupportFund, address _ReserveFund, address _TeamFund, address _Manager, address _Controller_Address1, address _Controller_Address2, address _Controller_Address3 ) public { Company = _Company; BountyFund = _BountyFund; SupportFund = _SupportFund; ReserveFund = _ReserveFund; TeamFund = _TeamFund; Manager = _Manager; Controller_Address1 = _Controller_Address1; Controller_Address2 = _Controller_Address2; Controller_Address3 = _Controller_Address3; } // function for changing rate of ETH and price of token function setRate(uint _RateEth) external managerOnly { Rate_Eth = _RateEth; Token_Price = Tokens_Per_Dollar*Rate_Eth/CONST_DEL; } //ICO status functions function startPreIco() external managerOnly { require(status == Status.Created || status == Status.PreIcoPaused); if(status == Status.Created) { dat.mint(BountyFund, bountyAmount); dat.mint(SupportFund, supportAmount); dat.mint(ReserveFund, reserveAmount); dat.mint(TeamFund, teamAmount); } status = Status.PreIcoStarted; LogStartPreICO(); } function finishPreIco() external managerOnly { // Funds for minting of tokens require(status == Status.PreIcoStarted || status == Status.PreIcoPaused); status = Status.PreIcoFinished; LogFinishPreICO(); } function startIco() external managerOnly { require(status == Status.PreIcoFinished || status == Status.IcoPaused); if(status == Status.PreIcoFinished) { startTime = now; } status = Status.IcoStarted; LogStartICO(); } function finishIco() external managerOnly { // Funds for minting of tokens require(status == Status.IcoStarted || status == Status.IcoPaused); uint alreadyMinted = dat.totalSupply(); //=PublicICO+PrivateOffer dat.mint(ReserveFund, Total_Amount.sub(alreadyMinted)); // dat.defrost(); status = Status.IcoFinished; LogFinishICO(ReserveFund); } function pauseIco() external managerOnly { require(status == Status.IcoStarted); status = Status.IcoPaused; LogPause(); } function pausePreIco() external managerOnly { require(status == Status.PreIcoStarted); status = Status.PreIcoPaused; LogPause(); } // function that buys tokens when investor sends ETH to address of ICO function() external payable { buy(msg.sender, msg.value * Token_Price); } // function for buying tokens to investors who paid in other cryptos function buyForInvestor(address _investor, uint _datValue, string _txHash) external controllersOnly { buy(_investor, _datValue); LogBuyForInvestor(_investor, _datValue, _txHash); } // internal function for buying tokens function buy(address _investor, uint _datValue) internal { require((status == Status.PreIcoStarted) || (status == Status.IcoStarted)); require(_datValue > 0); uint bonus = getBonus(_datValue); uint total = _datValue.add(bonus); require(Sold + total <= Tokens_For_Sale); dat.mint(_investor, total); Sold = Sold.add(_datValue); } // function that calculates bonus function getBonus(uint _value) public constant returns (uint) { uint bonus = 0; uint time = now; if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; } else { if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; } //function to withdraw ETH from smart contract function withdrawEther(uint256 _value) external managerOnly { require((status == Status.PreIcoFinished) || (status == Status.IcoFinished)); Company.transfer(_value); } } contract DAT is ERC20 { using SafeMath for uint; string public name = "Datarius Token"; string public symbol = "DAT"; uint public decimals = 18; address public ico; event Burn(address indexed from, uint256 value); bool public tokensAreFrozen = true; modifier icoOnly { require(msg.sender == ico); _; } function DAT(address _ico) public { ico = _ico; } function mint(address _holder, uint _value) external icoOnly { require(_value > 0); balances[_holder] = balances[_holder].add(_value); totalSupply = totalSupply.add(_value); Transfer(0x0, _holder, _value); } function defrost() external icoOnly { tokensAreFrozen = false; } function burn(uint256 _value) { require(!tokensAreFrozen); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } 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; } 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; } function approve(address _spender, uint256 _amount) public returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } }
function that calculates bonus
function getBonus(uint _value) public constant returns (uint) { uint bonus = 0; uint time = now; if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; } else { if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; if(status == Status.PreIcoStarted) { bonus = _value.mul(35).div(100); return bonus; if(time <= startTime + 6 hours) { bonus = _value.mul(30).div(100); return bonus; } if(time <= startTime + 12 hours) { bonus = _value.mul(25).div(100); return bonus; } if(time <= startTime + 24 hours) { bonus = _value.mul(20).div(100); return bonus; } if(time <= startTime + 48 hours) { bonus = _value.mul(10).div(100); return bonus; } } return bonus; }
2,559,156
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; import { IEmissionsController } from "../interfaces/IEmissionsController.sol"; import { IMasset } from "../interfaces/IMasset.sol"; import { IRevenueRecipient } from "../interfaces/IRevenueRecipient.sol"; import { DialData } from "../emissions/EmissionsController.sol"; import { ImmutableModule } from "../shared/ImmutableModule.sol"; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IUniswapV3SwapRouter } from "../peripheral/Uniswap/IUniswapV3SwapRouter.sol"; struct RevenueBuyBackConfig { // Minimum price of bAssets compared to mAssets scaled to 1e18 (CONFIG_SCALE). uint128 minMasset2BassetPrice; // Minimum price of rewards token compared to bAssets scaled to 1e18 (CONFIG_SCALE). uint128 minBasset2RewardsPrice; // base asset of the mAsset that is being redeemed and then sold for reward tokens. address bAsset; // Uniswap V3 path bytes uniswapPath; } /** * @title RevenueBuyBack * @author mStable * @notice Uses protocol revenue to buy MTA rewards for stakers. * @dev VERSION: 1.0 * DATE: 2021-11-09 */ contract RevenueBuyBack is IRevenueRecipient, Initializable, ImmutableModule { using SafeERC20 for IERC20; event RevenueReceived(address indexed mAsset, uint256 amountIn); event BuyBackRewards( address indexed mAsset, uint256 mAssetAmount, uint256 bAssetAmount, uint256 rewardsAmount ); event DonatedRewards(uint256 totalRewards); event AddedMassetConfig( address indexed mAsset, address indexed bAsset, uint128 minMasset2BassetPrice, uint128 minBasset2RewardsPrice, bytes uniswapPath ); event AddedStakingContract(uint16 stakingDialId); /// @notice scale of the `minMasset2BassetPrice` and `minBasset2RewardsPrice` configuration properties. uint256 public constant CONFIG_SCALE = 1e18; /// @notice address of the rewards token that is being purchased. eg MTA IERC20 public immutable REWARDS_TOKEN; /// @notice address of the Emissions Controller that does the weekly MTA reward emissions based off on-chain voting power. IEmissionsController public immutable EMISSIONS_CONTROLLER; /// @notice Uniswap V3 Router address IUniswapV3SwapRouter public immutable UNISWAP_ROUTER; /// @notice Mapping of mAssets to RevenueBuyBack config mapping(address => RevenueBuyBackConfig) public massetConfig; /// @notice Emissions Controller dial ids for all staking contracts that will receive reward tokens. uint256[] public stakingDialIds; /** * @param _nexus mStable system Nexus address * @param _rewardsToken Rewards token address that are purchased. eg MTA * @param _uniswapRouter Uniswap V3 Router address * @param _emissionsController Emissions Controller address that rewards tokens are donated to. */ constructor( address _nexus, address _rewardsToken, address _uniswapRouter, address _emissionsController ) ImmutableModule(_nexus) { require(_rewardsToken != address(0), "Rewards token is zero"); REWARDS_TOKEN = IERC20(_rewardsToken); require(_uniswapRouter != address(0), "Uniswap Router is zero"); UNISWAP_ROUTER = IUniswapV3SwapRouter(_uniswapRouter); require(_emissionsController != address(0), "Emissions controller is zero"); EMISSIONS_CONTROLLER = IEmissionsController(_emissionsController); } /** * @param _stakingDialIds Emissions Controller dial ids for all staking contracts that will receive reward tokens. */ function initialize(uint16[] memory _stakingDialIds) external initializer { for (uint256 i = 0; i < _stakingDialIds.length; i++) { _addStakingContract(_stakingDialIds[i]); } } /*************************************** EXTERNAL ****************************************/ /** * @dev Simply transfers the mAsset from the sender to here * @param _mAsset Address of mAsset * @param _amount Units of mAsset collected */ function notifyRedistributionAmount(address _mAsset, uint256 _amount) external override { require(massetConfig[_mAsset].bAsset != address(0), "Invalid mAsset"); // Transfer from sender to here IERC20(_mAsset).safeTransferFrom(msg.sender, address(this), _amount); emit RevenueReceived(_mAsset, _amount); } /** * @notice Buys reward tokens, eg MTA, using mAssets like mUSD or mBTC from protocol revenue. * @param _mAssets Addresses of mAssets that are to be sold for rewards. eg mUSD and mBTC. */ function buyBackRewards(address[] calldata _mAssets) external onlyKeeperOrGovernor { uint256 len = _mAssets.length; require(len > 0, "Invalid args"); // for each mAsset for (uint256 i = 0; i < len; i++) { // Get config for mAsset RevenueBuyBackConfig memory config = massetConfig[_mAssets[i]]; require(config.bAsset != address(0), "Invalid mAsset"); // STEP 1 - Redeem mAssets for bAssets IMasset mAsset = IMasset(_mAssets[i]); uint256 mAssetBal = IERC20(_mAssets[i]).balanceOf(address(this)); uint256 minBassetOutput = (mAssetBal * config.minMasset2BassetPrice) / CONFIG_SCALE; uint256 bAssetAmount = mAsset.redeem( config.bAsset, mAssetBal, minBassetOutput, address(this) ); // STEP 2 - Swap bAssets for rewards using Uniswap V3 IERC20(config.bAsset).safeApprove(address(UNISWAP_ROUTER), bAssetAmount); uint256 minRewardsAmount = (bAssetAmount * config.minBasset2RewardsPrice) / CONFIG_SCALE; IUniswapV3SwapRouter.ExactInputParams memory param = IUniswapV3SwapRouter .ExactInputParams( config.uniswapPath, address(this), block.timestamp, bAssetAmount, minRewardsAmount ); uint256 rewardsAmount = UNISWAP_ROUTER.exactInput(param); emit BuyBackRewards(_mAssets[i], mAssetBal, bAssetAmount, rewardsAmount); } } /** * @notice donates purchased rewards, eg MTA, to staking contracts via the Emissions Controller. */ function donateRewards() external onlyKeeperOrGovernor { // STEP 1 - Get the voting power of the staking contracts uint256 numberStakingContracts = stakingDialIds.length; uint256[] memory votingPower = new uint256[](numberStakingContracts); uint256 totalVotingPower; // Get the voting power of each staking contract for (uint256 i = 0; i < numberStakingContracts; i++) { address stakingContractAddress = EMISSIONS_CONTROLLER.getDialRecipient( stakingDialIds[i] ); require(stakingContractAddress != address(0), "invalid dial id"); votingPower[i] = IERC20(stakingContractAddress).totalSupply(); totalVotingPower += votingPower[i]; } require(totalVotingPower > 0, "No voting power"); // STEP 2 - Get rewards that need to be distributed uint256 rewardsBal = REWARDS_TOKEN.balanceOf(address(this)); require(rewardsBal > 0, "No rewards to donate"); // STEP 3 - Calculate rewards for each staking contract uint256[] memory rewardDonationAmounts = new uint256[](numberStakingContracts); for (uint256 i = 0; i < numberStakingContracts; i++) { rewardDonationAmounts[i] = (rewardsBal * votingPower[i]) / totalVotingPower; } // STEP 4 - RevenueBuyBack approves the Emissions Controller to transfer rewards. eg MTA REWARDS_TOKEN.safeApprove(address(EMISSIONS_CONTROLLER), rewardsBal); // STEP 5 - donate rewards to staking contract dials in the Emissions Controller EMISSIONS_CONTROLLER.donate(stakingDialIds, rewardDonationAmounts); // To get a details split of rewards to staking contracts, // see the `DonatedRewards` event on the `EmissionsController` emit DonatedRewards(rewardsBal); } /*************************************** ADMIN ****************************************/ /** * @notice Adds or updates rewards buyback config for a mAsset. * @param _mAsset Address of the meta asset that is received as protocol revenue. * @param _bAsset Address of the base asset that is redeemed from the mAsset. * @param _minMasset2BassetPrice Minimum price of bAssets compared to mAssets scaled to 1e18 (CONFIG_SCALE). * eg USDC/mUSD and wBTC/mBTC exchange rates. * USDC has 6 decimal places so `minMasset2BassetPrice` with no slippage is 1e6. * If a 2% slippage is allowed, the `minMasset2BassetPrice` is 98e4. * WBTC has 8 decimal places so `minMasset2BassetPrice` with no slippage is 1e8. * If a 5% slippage is allowed, the `minMasset2BassetPrice` is 95e6. * @param _minBasset2RewardsPrice Minimum price of rewards token compared to bAssets scaled to 1e18 (CONFIG_SCALE). * eg USDC/MTA and wBTC/MTA exchange rates scaled to 1e18. * USDC only has 6 decimal places * 2 MTA/USDC = 0.5 USDC/MTA * (1e18 / 1e6) * 1e18 = 0.5e30 = 5e29 * wBTC only has 8 decimal places * 0.000033 MTA/wBTC = 30,000 WBTC/MTA * (1e18 / 1e8) * 1e18 = 3e4 * 1e28 = 3e32 * @param _uniswapPath The Uniswap V3 bytes encoded path. */ function setMassetConfig( address _mAsset, address _bAsset, uint128 _minMasset2BassetPrice, uint128 _minBasset2RewardsPrice, bytes calldata _uniswapPath ) external onlyGovernor { require(_mAsset != address(0), "mAsset token is zero"); require(_bAsset != address(0), "bAsset token is zero"); // bAsset slippage must be plus or minus 10% require(_minMasset2BassetPrice > 0, "Invalid min bAsset price"); require(_minBasset2RewardsPrice > 0, "Invalid min reward price"); require( _validUniswapPath(_bAsset, address(REWARDS_TOKEN), _uniswapPath), "Invalid uniswap path" ); massetConfig[_mAsset] = RevenueBuyBackConfig({ bAsset: _bAsset, minMasset2BassetPrice: _minMasset2BassetPrice, minBasset2RewardsPrice: _minBasset2RewardsPrice, uniswapPath: _uniswapPath }); emit AddedMassetConfig( _mAsset, _bAsset, _minMasset2BassetPrice, _minBasset2RewardsPrice, _uniswapPath ); } /** * @notice Adds a new staking contract that will receive MTA rewards * @param _stakingDialId dial identifier from the Emissions Controller of the staking contract. */ function addStakingContract(uint16 _stakingDialId) external onlyGovernor { _addStakingContract(_stakingDialId); } function _addStakingContract(uint16 _stakingDialId) internal { for (uint256 i = 0; i < stakingDialIds.length; i++) { require(stakingDialIds[i] != _stakingDialId, "Staking dial id already exists"); } // Make sure the dial id of the staking contract is valid require( EMISSIONS_CONTROLLER.getDialRecipient(_stakingDialId) != address(0), "Missing staking dial" ); stakingDialIds.push(_stakingDialId); emit AddedStakingContract(_stakingDialId); } /** * @notice Validates a given uniswap path - valid if sellToken at position 0 and bAsset at end * @param _sellToken Token harvested from the integration contract * @param _bAsset New asset to buy on Uniswap * @param _uniswapPath The Uniswap V3 bytes encoded path. */ function _validUniswapPath( address _sellToken, address _bAsset, bytes calldata _uniswapPath ) internal pure returns (bool) { uint256 len = _uniswapPath.length; require(_uniswapPath.length >= 43, "Uniswap path too short"); // check sellToken is first 20 bytes and bAsset is the last 20 bytes of the uniswap path return keccak256(abi.encodePacked(_sellToken)) == keccak256(abi.encodePacked(_uniswapPath[0:20])) && keccak256(abi.encodePacked(_bAsset)) == keccak256(abi.encodePacked(_uniswapPath[len - 20:len])); } /** * @dev Abstract override */ function depositToPool( address[] calldata, /* _mAssets */ uint256[] calldata /* _percentages */ ) external override {} } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; import { IVotes } from "../interfaces/IVotes.sol"; import { DialData } from "../emissions/EmissionsController.sol"; /** * @title IEmissionsController * @dev Emissions Controller interface used for by RevenueBuyBack */ interface IEmissionsController { function getDialRecipient(uint256 dialId) external returns (address recipient); function donate(uint256[] memory _dialIds, uint256[] memory _amounts) external; function stakingContracts(uint256 dialId) external returns (address); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; pragma abicoder v2; import { BassetData, BassetPersonal } from "../masset/MassetStructs.sol"; abstract contract IMasset { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function getBasket() external view virtual returns (bool, bool); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view virtual returns (uint8); function getPrice() external view virtual returns (uint256 price, uint256 k); // SavingsManager function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); // Admin function setCacheSize(uint256 _cacheSize) external virtual; function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual; function setTransferFeesFlag(address _bAsset, bool _flag) external virtual; function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; interface IRevenueRecipient { /** @dev Recipient */ function notifyRedistributionAmount(address _mAsset, uint256 _amount) external; function depositToPool(address[] calldata _mAssets, uint256[] calldata _percentages) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { IGovernanceHook } from "../governance/staking/interfaces/IGovernanceHook.sol"; import { IRewardsDistributionRecipient } from "../interfaces/IRewardsDistributionRecipient.sol"; import { IVotes } from "../interfaces/IVotes.sol"; import { ImmutableModule } from "../shared/ImmutableModule.sol"; import { Initializable } from "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; struct HistoricVotes { // Number of votes directed to this dial uint128 votes; // The start of the distribution period in seconds divided by 604,800 seconds in a week uint32 epoch; } struct DialData { // If true, no rewards are distributed to the dial recipient and any votes on this dial are ignored bool disabled; // If true, `notifyRewardAmount` on the recipient contract is called bool notify; // Cap on distribution % where 1% = 1 uint8 cap; // Dial rewards that are waiting to be distributed to recipient uint96 balance; // Account rewards are distributed to address recipient; // List of weighted votes in each distribution period HistoricVotes[] voteHistory; } struct Preference { // ID of the dial (array position) uint256 dialId; // % weight applied to this dial, where 200 = 100% and 1 = 0.5% uint256 weight; } struct VoterPreferences { // A array of 16 Preferences, which contain a dialId and weight of 8 bits each. // That's 16 bits per item, which is 16 * 16 = 256 bits = 1 slot. // The first item, index 0, is right ended. // Each item is a dialId and weight. // The array is stored as a uint256 uint256 dialWeights; // Total voting power cast by this voter across the staking contracts. uint128 votesCast; // Last time balance was looked up across all staking contracts uint32 lastSourcePoke; } struct TopLevelConfig { int256 A; int256 B; int256 C; int256 D; uint128 EPOCHS; } struct EpochHistory { // First weekly epoch of this contract. uint32 startEpoch; // The last weekly epoch to have rewards distributed. uint32 lastEpoch; } /** * @title EmissionsController * @author mStable * @notice Allows governors to vote on the weekly distribution of $MTA. Rewards are distributed between * `n` "Dials" proportionately to the % of votes the dial receives. Vote weight derives from multiple * whitelisted "Staking contracts". Voters can distribute their vote across (0 <= n <= 16 dials), at 0.5% * increments in voting weight. Once their preferences are cast, each time their voting weight changes * it is reflected here through a hook. * @dev VERSION: 1.0 * DATE: 2021-10-28 */ contract EmissionsController is IGovernanceHook, Initializable, ImmutableModule { using SafeERC20 for IERC20; /// @notice Minimum time between distributions. uint32 constant DISTRIBUTION_PERIOD = 1 weeks; /// @notice Scale of dial weights. 200 = 100%, 2 = 1%, 1 = 0.5% uint256 constant SCALE = 200; /// @notice Polynomial top level emission function parameters int256 immutable A; int256 immutable B; int256 immutable C; int256 immutable D; uint128 immutable EPOCHS; /// @notice Address of rewards token. ie MTA token IERC20 public immutable REWARD_TOKEN; /// @notice Epoch history in storage /// An epoch is the number of weeks since 1 Jan 1970. The week starts on Thursday 00:00 UTC. /// epoch = start of the distribution period in seconds divided by 604,800 seconds in a week EpochHistory public epochs; /// @notice Flags the timestamp that a given staking contract was added mapping(address => uint32) public stakingContractAddTime; /// @notice List of staking contract addresses. IVotes[] public stakingContracts; /// @notice List of dial data including votes, rewards balance, recipient contract and disabled flag. DialData[] public dials; /// @notice Mapping of staker addresses to an list of voter dial weights. /// @dev The sum of the weights for each staker must not be greater than SCALE = 200. /// A user can issue a subset of their voting power. eg only 20% of their voting power. /// A user can not issue more than 100% of their voting power across dials. mapping(address => VoterPreferences) public voterPreferences; event AddedDial(uint256 indexed dialId, address indexed recipient); event UpdatedDial(uint256 indexed dialId, bool disabled); event AddStakingContract(address indexed stakingContract); event PeriodRewards(uint256[] amounts); event DonatedRewards(uint256 indexed dialId, uint256 amount); event DistributedReward(uint256 indexed dialId, uint256 amount); event PreferencesChanged(address indexed voter, Preference[] preferences); event VotesCast( address stakingContract, address indexed from, address indexed to, uint256 amount ); event SourcesPoked(address indexed voter, uint256 newVotesCast); /*************************************** INIT ****************************************/ /** * @notice Recipient is a module, governed by mStable governance. * @param _nexus System Nexus that resolves module addresses. * @param _rewardToken Token that rewards are distributed in. eg MTA. * @param _config Arguments for polynomial top level emission function (raw, not scaled). */ constructor( address _nexus, address _rewardToken, TopLevelConfig memory _config ) ImmutableModule(_nexus) { require(_rewardToken != address(0), "Reward token address is zero"); REWARD_TOKEN = IERC20(_rewardToken); A = _config.A * 1e3; B = _config.B * 1e3; C = _config.C * 1e3; D = _config.D * 1e3; EPOCHS = _config.EPOCHS; } /** * @dev Initialisation function to configure the first dials. All recipient contracts with _notifies = true need to * implement the `IRewardsDistributionRecipient` interface. * @param _recipients List of dial contract addresses that can receive rewards. * @param _caps Limit on the percentage of the weekly top line emission the corresponding dial can receive (where 10% = 10 and uncapped = 0). * @param _notifies If true, `notifyRewardAmount` is called in the `distributeRewards` function. * @param _stakingContracts Initial staking contracts used for voting power lookup. */ function initialize( address[] memory _recipients, uint8[] memory _caps, bool[] memory _notifies, address[] memory _stakingContracts ) external initializer { uint256 len = _recipients.length; require(_notifies.length == len && _caps.length == len, "Initialize args mismatch"); // 1.0 - Set the last epoch storage variable to the immutable start epoch // Set the weekly epoch this contract starts distributions which will be 1 - 2 week after deployment. uint32 startEpoch = _epoch(block.timestamp) + 1; epochs = EpochHistory({ startEpoch: startEpoch, lastEpoch: startEpoch }); // 2.0 - Add each of the dials for (uint256 i = 0; i < len; i++) { _addDial(_recipients[i], _caps[i], _notifies[i]); } // 3.0 - Initialize the staking contracts for (uint256 i = 0; i < _stakingContracts.length; i++) { _addStakingContract(_stakingContracts[i]); } } /*************************************** VIEW ****************************************/ /** * @notice Gets the users aggregate voting power across all voting contracts. * @dev Voting power can be from staking or it could be delegated to the account. * @param account For which to fetch voting power. * @return votingPower Units of voting power owned by account. */ function getVotes(address account) public view returns (uint256 votingPower) { // For each configured staking contract for (uint256 i = 0; i < stakingContracts.length; i++) { votingPower += stakingContracts[i].getVotes(account); } } /** * @notice Calculates top line distribution amount for the current epoch as per the polynomial. * (f(x)=A*(x/div)^3+B*(x/div)^2+C*(x/div)+D) * @dev Values are effectively scaled to 1e12 to avoid integer overflow on pow. * @param epoch The number of weeks since 1 Jan 1970. * @return emissionForEpoch Units of MTA to be distributed at this epoch. */ function topLineEmission(uint32 epoch) public view returns (uint256 emissionForEpoch) { require( epochs.startEpoch < epoch && epoch <= epochs.startEpoch + 312, "Wrong epoch number" ); // e.g. week 1, A = -166000e12, B = 168479942061125e3, C = -168479942061125e3, D = 166000e12 // e.g. epochDelta = 1 uint128 epochDelta = (epoch - epochs.startEpoch); // e.g. x = 1e12 / 312 = 3205128205 int256 x = SafeCast.toInt256((epochDelta * 1e12) / EPOCHS); emissionForEpoch = SafeCast.toUint256( ((A * (x**3)) / 1e36) + // e.g. -166000e12 * (3205128205 ^ 3) / 1e36 = -5465681315 ((B * (x**2)) / 1e24) + // e.g. 168479942061125e3 * (3205128205 ^ 2) / 1e24 = 1730768635433 ((C * (x)) / 1e12) + // e.g. -168479942061125e3 * 3205128205 / 1e12 = -539999814276877 D // e.g. 166000e12 ) * 1e6; // e.g. SUM = 165461725488677241 * 1e6 = 165461e18 } /** * @notice Gets a dial's recipient address. * @param dialId Dial identifier starting from 0. * @return recipient Address of the recipient account associated with. */ function getDialRecipient(uint256 dialId) public view returns (address recipient) { recipient = dials[dialId].recipient; } /** * @notice Gets a dial's weighted votes for each distribution period. * @param dialId Dial identifier starting from 0. * @return voteHistory List of weighted votes with the first distribution at index 0. */ function getDialVoteHistory(uint256 dialId) public view returns (HistoricVotes[] memory voteHistory) { voteHistory = dials[dialId].voteHistory; } /** * @notice Gets the latest weighted votes for each dial. * This will include disabled dials and their current weighted votes. * @return dialVotes A list of dial weighted votes. The index of the array is the dialId. */ function getDialVotes() public view returns (uint256[] memory dialVotes) { uint256 dialLen = dials.length; dialVotes = new uint256[](dialLen); for (uint256 i = 0; i < dialLen; i++) { DialData memory dialData = dials[i]; uint256 voteHistoryLen = dialData.voteHistory.length; // If no distributions for this dial yet if (voteHistoryLen == 0) { continue; } dialVotes[i] = dialData.voteHistory[voteHistoryLen - 1].votes; } } /** * @notice Gets a voter's weights for each dial. * @dev A dial identifier of 255 marks the end of the array. It should be ignored. * @param voter Address of the voter that has set weights. * @return preferences List of dial identifiers and weights where a weight of 100% = 200. */ function getVoterPreferences(address voter) public view returns (Preference[16] memory preferences) { for (uint256 i = 0; i < 16; i++) { preferences[i].weight = uint8(voterPreferences[voter].dialWeights >> (i * 16)); preferences[i].dialId = uint8(voterPreferences[voter].dialWeights >> ((i * 16) + 8)); } } /*************************************** ADMIN ****************************************/ /** * @notice Adds a new dial that can be voted on to receive weekly rewards. Callable by system governor. * @param _recipient Address of the contract that will receive rewards. * @param _cap Cap where 0 = uncapped and 10 = 10%. * @param _notify If true, `notifyRewardAmount` is called in the `distributeRewards` function. */ function addDial( address _recipient, uint8 _cap, bool _notify ) external onlyGovernor { _addDial(_recipient, _cap, _notify); } /** * @dev Internal dial addition fn, see parent fn for details. */ function _addDial( address _recipient, uint8 _cap, bool _notify ) internal { require(_recipient != address(0), "Dial address is zero"); require(_cap < 100, "Invalid cap"); uint256 len = dials.length; require(len < 254, "Max dial count reached"); for (uint256 i = 0; i < len; i++) { require(dials[i].recipient != _recipient, "Dial already exists"); } dials.push(); DialData storage newDialData = dials[len]; newDialData.recipient = _recipient; newDialData.notify = _notify; newDialData.cap = _cap; uint32 currentEpoch = _epoch(block.timestamp); if (currentEpoch < epochs.startEpoch) { currentEpoch = epochs.startEpoch; } newDialData.voteHistory.push(HistoricVotes({ votes: 0, epoch: currentEpoch })); emit AddedDial(len, _recipient); } /** * @notice Updates a dials recipient contract and/or disabled flag. * @param _dialId Dial identifier which is the index of the dials array. * @param _disabled If true, no rewards will be distributed to this dial. */ function updateDial(uint256 _dialId, bool _disabled) external onlyGovernor { require(_dialId < dials.length, "Invalid dial id"); dials[_dialId].disabled = _disabled; emit UpdatedDial(_dialId, _disabled); } /** * @notice Adds a new contract to the list of approved staking contracts. * @param _stakingContract Address of the new staking contract */ function addStakingContract(address _stakingContract) external onlyGovernor { _addStakingContract(_stakingContract); } /** * @dev Adds a staking contract by setting it's addition time to current timestamp. */ function _addStakingContract(address _stakingContract) internal { require(_stakingContract != address(0), "Staking contract address is zero"); uint256 len = stakingContracts.length; for (uint256 i = 0; i < len; i++) { require( address(stakingContracts[i]) != _stakingContract, "StakingContract already exists" ); } stakingContractAddTime[_stakingContract] = SafeCast.toUint32(block.timestamp); stakingContracts.push(IVotes(_stakingContract)); emit AddStakingContract(_stakingContract); } /*************************************** REWARDS-EXTERNAL ****************************************/ /** * @notice Allows arbitrary reward donation to a dial on top of the weekly rewards. * @param _dialIds Dial identifiers that will receive donated rewards. * @param _amounts Units of rewards to be sent to each dial including decimals. */ function donate(uint256[] memory _dialIds, uint256[] memory _amounts) external { uint256 dialLen = _dialIds.length; require(dialLen > 0 && _amounts.length == dialLen, "Invalid inputs"); uint256 totalAmount; // For each specified dial uint256 dialId; for (uint256 i = 0; i < dialLen; i++) { dialId = _dialIds[i]; require(dialId < dials.length, "Invalid dial id"); // Sum the rewards for each dial totalAmount += _amounts[i]; // Add rewards to the dial's rewards balance dials[dialId].balance += SafeCast.toUint96(_amounts[i]); emit DonatedRewards(dialId, _amounts[i]); } // Transfer the total donated rewards to this Emissions Controller contract REWARD_TOKEN.safeTransferFrom(msg.sender, address(this), totalAmount); } /** * @notice Calculates the rewards to be distributed to each dial for the next weekly period. * @dev Callable once an epoch has fully passed. Top level emission for the epoch is distributed * proportionately to vote count with the following exceptions: * - Disabled dials are ignored and votes not counted. * - Dials with a cap are capped and their votes/emission removed (effectively redistributing rewards). */ function calculateRewards() external { // 1 - Calculate amount of rewards to distribute this week uint32 epoch = _epoch(block.timestamp); require(epoch > epochs.lastEpoch, "Must wait for new period"); // Update storage with new last epoch epochs.lastEpoch = epoch; uint256 emissionForEpoch = topLineEmission(epoch); // 2.0 - Calculate the total amount of dial votes ignoring any disabled dials uint256 totalDialVotes; uint256 dialLen = dials.length; uint256[] memory dialVotes = new uint256[](dialLen); for (uint256 i = 0; i < dialLen; i++) { DialData memory dialData = dials[i]; if (dialData.disabled) continue; // Get the relevant votes for the dial. Possibilities: // - No new votes cast in period, therefore relevant votes are at pos len - 1 // - Votes already cast in period, therefore relevant is at pos len - 2 uint256 end = dialData.voteHistory.length - 1; HistoricVotes memory latestVote = dialData.voteHistory[end]; if (latestVote.epoch < epoch) { dialVotes[i] = latestVote.votes; totalDialVotes += latestVote.votes; // Create a new weighted votes for the current distribution period dials[i].voteHistory.push( HistoricVotes({ votes: latestVote.votes, epoch: SafeCast.toUint32(epoch) }) ); } else if (latestVote.epoch == epoch && end > 0) { uint256 votes = dialData.voteHistory[end - 1].votes; dialVotes[i] = votes; totalDialVotes += votes; } } // 3.0 - Deal with the capped dials uint256[] memory distributionAmounts = new uint256[](dialLen); uint256 postCappedVotes = totalDialVotes; uint256 postCappedEmission = emissionForEpoch; for (uint256 k = 0; k < dialLen; k++) { DialData memory dialData = dials[k]; // 3.1 - If the dial has a cap and isn't disabled, check if it's over the threshold if (dialData.cap > 0 && !dialData.disabled) { uint256 maxVotes = (dialData.cap * totalDialVotes) / 100; // If dial has move votes than its cap if (dialVotes[k] > maxVotes) { // Calculate amount of rewards for the dial distributionAmounts[k] = (dialData.cap * emissionForEpoch) / 100; // Add dial rewards to balance in storage. // Is addition and not set as rewards could have been donated. dials[k].balance += SafeCast.toUint96(distributionAmounts[k]); // Remove dial votes from total votes postCappedVotes -= dialVotes[k]; // Remove capped rewards from total reward postCappedEmission -= distributionAmounts[k]; // Set to zero votes so it'll be skipped in the next loop dialVotes[k] = 0; } } } // 4.0 - Calculate the distribution amounts for each dial for (uint256 l = 0; l < dialLen; l++) { // Skip dial if no votes, disabled or was over cap if (dialVotes[l] == 0) { continue; } // Calculate amount of rewards for the dial & set storage distributionAmounts[l] = (dialVotes[l] * postCappedEmission) / postCappedVotes; dials[l].balance += SafeCast.toUint96(distributionAmounts[l]); } emit PeriodRewards(distributionAmounts); } /** * @notice Transfers all accrued rewards to dials and notifies them of the amount. * @param _dialIds Dial identifiers for which to distribute rewards. */ function distributeRewards(uint256[] memory _dialIds) external { // For each specified dial uint256 len = _dialIds.length; for (uint256 i = 0; i < len; i++) { require(_dialIds[i] < dials.length, "Invalid dial id"); DialData memory dialData = dials[_dialIds[i]]; // 1.0 - Get the dial's reward balance if (dialData.balance == 0) { continue; } // 2.0 - Reset the balance in storage back to 0 dials[_dialIds[i]].balance = 0; // 3.0 - Send the rewards the to the dial recipient REWARD_TOKEN.safeTransfer(dialData.recipient, dialData.balance); // 4.0 - Notify the dial of the new rewards if configured to // Only after successful transer tx if (dialData.notify) { IRewardsDistributionRecipient(dialData.recipient).notifyRewardAmount( dialData.balance ); } emit DistributedReward(_dialIds[i], dialData.balance); } } /*************************************** VOTING-EXTERNAL ****************************************/ /** * @notice Re-cast a voters votes by retrieving balance across all staking contracts * and updating `lastSourcePoke`. * @dev This would need to be called if a staking contract was added to the emissions controller * when a voter already had voting power in the new staking contract and they had already set voting preferences. * @param _voter Address of the voter for which to re-cast. */ function pokeSources(address _voter) public { // Only poke if voter has previously set voting preferences if (voterPreferences[_voter].lastSourcePoke > 0) { uint256 votesCast = voterPreferences[_voter].votesCast; uint256 newVotesCast = getVotes(_voter) - votesCast; _moveVotingPower(_voter, newVotesCast, _add); voterPreferences[_voter].lastSourcePoke = SafeCast.toUint32(block.timestamp); emit SourcesPoked(_voter, newVotesCast); } } /** * @notice Allows a staker to cast their voting power across a number of dials. * @dev A staker can proportion their voting power even if they currently have zero voting power. * For example, they have delegated their votes. When they do have voting power (e.g. they undelegate), * their set weights will proportion their voting power. * @param _preferences Structs containing dialId & voting weights, with 0 <= n <= 16 entries. */ function setVoterDialWeights(Preference[] memory _preferences) external { require(_preferences.length <= 16, "Max of 16 preferences"); // 1.0 - Get staker's previous total votes cast uint256 votesCast = voterPreferences[msg.sender].votesCast; // 1.1 - Adjust dial votes from removed staker votes _moveVotingPower(msg.sender, votesCast, _subtract); // Clear the old weights as they will be added back below delete voterPreferences[msg.sender]; // 2.0 - Log new preferences uint256 newTotalWeight; uint256 newDialWeights; for (uint256 i = 0; i < _preferences.length; i++) { require(_preferences[i].dialId < dials.length, "Invalid dial id"); require(_preferences[i].weight > 0, "Must give a dial some weight"); newTotalWeight += _preferences[i].weight; // Add staker's dial weight newDialWeights |= uint256(_preferences[i].weight) << (i * 16); // Add staker's dial id newDialWeights |= uint256(_preferences[i].dialId) << ((i * 16) + 8); } // 2.1 - In the likely scenario less than 16 preferences are given, add a breaker with max uint // to signal that this is the end of array. if (_preferences.length < 16) { // Set dialId to 255 newDialWeights |= uint256(255) << ((_preferences.length * 16) + 8); } require(newTotalWeight <= SCALE, "Imbalanced weights"); // Update storage with the array of 16 Preferences stored as an uint256 voterPreferences[msg.sender].dialWeights = newDialWeights; // Need to set before calling _moveVotingPower for the second time voterPreferences[msg.sender].lastSourcePoke = SafeCast.toUint32(block.timestamp); // 3.0 - Cast votes on these new preferences _moveVotingPower(msg.sender, getVotes(msg.sender), _add); emit PreferencesChanged(msg.sender, _preferences); } /** * @notice Called by the staking contracts when a staker has modified voting power. * @dev This can be called when staking, cooling down for withdraw or delegating. * @param from Account that votes moved from. If a mint the account will be a zero address. * @param to Account that votes moved to. If a burn the account will be a zero address. * @param amount The number of votes moved including the decimal places. */ function moveVotingPowerHook( address from, address to, uint256 amount ) external override { if (amount > 0) { bool votesCast; // Require that the caller of this function is a whitelisted staking contract uint32 addTime = stakingContractAddTime[msg.sender]; require(addTime > 0, "Caller must be staking contract"); // If burning (withdraw) or transferring delegated votes from a staker if (from != address(0)) { uint32 lastSourcePoke = voterPreferences[from].lastSourcePoke; if (lastSourcePoke > addTime) { _moveVotingPower(from, amount, _subtract); votesCast = true; } else if (lastSourcePoke > 0) { // If preferences were set before the calling staking contract // was added to the EmissionsController pokeSources(from); } // Don't need to do anything if staker has not set preferences before. } // If minting (staking) or transferring delegated votes to a staker if (to != address(0)) { uint32 lastSourcePoke = voterPreferences[to].lastSourcePoke; if (lastSourcePoke > addTime) { _moveVotingPower(to, amount, _add); votesCast = true; } else if (lastSourcePoke > 0) { // If preferences were set before the calling staking contract // was added to the EmissionsController pokeSources(to); } // Don't need to do anything if staker has not set preferences before. } // Only emit if voting power was moved. if (votesCast) { emit VotesCast(msg.sender, from, to, amount); } } } /*************************************** VOTING-INTERNAL ****************************************/ /** * @dev Internal voting power updater. Adds/subtracts votes across the array of user preferences. * @param _voter Address of the source of movement. * @param _amount Total amount of votes to be added/removed (proportionately across the user preferences). * @param _op Function (either addition or subtraction) that dictates how the `_amount` of votes affects balance. */ function _moveVotingPower( address _voter, uint256 _amount, function(uint256, uint256) pure returns (uint256) _op ) internal { // 0.0 - Get preferences and epoch data VoterPreferences memory preferences = voterPreferences[_voter]; // 0.1 - If no preferences have been set then there is nothing to do // This prevent doing 16 iterations below as dialId 255 will not be set if (preferences.lastSourcePoke == 0) return; // 0.2 - If in the first launch week uint32 currentEpoch = _epoch(block.timestamp); // 0.3 - Update the total amount of votes cast by the voter voterPreferences[_voter].votesCast = SafeCast.toUint128( _op(preferences.votesCast, _amount) ); // 1.0 - Loop through voter preferences until dialId == 255 or until end for (uint256 i = 0; i < 16; i++) { uint256 dialId = uint8(preferences.dialWeights >> ((i * 16) + 8)); if (dialId == 255) break; uint256 weight = uint8(preferences.dialWeights >> (i * 16)); // 1.1 - Scale the vote by dial weight // e.g. 5e17 * 1e18 / 1e18 * 100e18 / 1e18 = 50e18 uint256 amountToChange = (weight * _amount) / SCALE; // 1.2 - Fetch voting history for this dial HistoricVotes[] storage voteHistory = dials[dialId].voteHistory; uint256 len = voteHistory.length; HistoricVotes storage latestHistoricVotes = voteHistory[len - 1]; // 1.3 - Determine new votes cast for dial uint128 newVotes = SafeCast.toUint128(_op(latestHistoricVotes.votes, amountToChange)); // 1.4 - Update dial vote count. If first vote in new epoch, create new entry if (latestHistoricVotes.epoch < currentEpoch) { // Add a new weighted votes epoch for the dial voteHistory.push(HistoricVotes({ votes: newVotes, epoch: currentEpoch })); } else { // Epoch already exists for this dial so just update the dial's weighted votes latestHistoricVotes.votes = newVotes; } } } /** * @notice Returns the epoch index the timestamp is on. * This is the number of weeks since 1 Jan 1970. ie the timestamp / 604800 seconds in a week. * @dev Each week starts on Thursday 00:00 UTC. * @param timestamp UNIX time in seconds. * @return epoch The number of weeks since 1 Jan 1970. */ function _epoch(uint256 timestamp) internal pure returns (uint32 epoch) { epoch = SafeCast.toUint32(timestamp) / DISTRIBUTION_PERIOD; } /** * @dev Simple addition function, used in the `_moveVotingPower` fn. */ function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } /** * @dev Simple subtraction function, used in the `_moveVotingPower` fn. */ function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; import { ModuleKeys } from "./ModuleKeys.sol"; import { INexus } from "../interfaces/INexus.sol"; /** * @title ImmutableModule * @author mStable * @dev Subscribes to module updates from a given publisher and reads from its registry. * Contract is used for upgradable proxy contracts. */ abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governor or the Keeper EOA. */ modifier onlyKeeperOrGovernor() { _keeperOrGovernor(); _; } function _keeperOrGovernor() internal view { require(msg.sender == _keeper() || msg.sender == _governor(), "Only keeper or governor"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Keeper address from the Nexus. * This account is used for operational transactions that * don't need multiple signatures. * @return Address of the Keeper externally owned account. */ function _keeper() internal view returns (address) { return nexus.getModule(KEY_KEEPER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Liquidator Module address from the Nexus * @return Address of the Liquidator Module contract */ function _liquidator() internal view returns (address) { return nexus.getModule(KEY_LIQUIDATOR); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: GPL-2.0-or-later pragma solidity 0.8.6; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3SwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; interface IVotes { function getVotes(address account) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^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 uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max, "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 >= type(int64).min && value <= type(int64).max, "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 >= type(int32).min && value <= type(int32).max, "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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; interface IGovernanceHook { function moveVotingPowerHook( address from, address to, uint256 amount ) external; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRewardsDistributionRecipient { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); } interface IRewardsRecipientWithPlatformToken { function notifyRewardAmount(uint256 reward) external; function getRewardToken() external view returns (IERC20); function getPlatformToken() external view returns (IERC20); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; /** * @title ModuleKeys * @author mStable * @notice Provides system wide access to the byte32 represntations of system modules * This allows each system module to be able to reference and update one another in a * friendly way * @dev keccak256() values are hardcoded to avoid re-evaluation of the constants at runtime. */ contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; // keccak256("Keeper"); bytes32 internal constant KEY_KEEPER = 0x4f78afe9dfc9a0cb0441c27b9405070cd2a48b490636a7bdd09f355e33a5d7de; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; /** * @title INexus * @dev Basic interface for interacting with the Nexus i.e. SystemKernel */ interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } // 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: AGPL-3.0-or-later pragma solidity 0.8.6; struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BasketState { bool undergoingRecol; bool failed; } struct FeederConfig { uint256 supply; uint256 a; WeightLimits limits; } struct InvariantConfig { uint256 supply; uint256 a; WeightLimits limits; uint256 recolFee; } struct BasicConfig { uint256 a; WeightLimits limits; } struct WeightLimits { uint128 min; uint128 max; } struct AmpData { uint64 initialA; uint64 targetA; uint64 rampStartTime; uint64 rampEndTime; } struct FeederData { uint256 swapFee; uint256 redemptionFee; uint256 govFee; uint256 pendingFees; uint256 cacheSize; BassetPersonal[] bAssetPersonal; BassetData[] bAssetData; AmpData ampData; WeightLimits weightLimits; } struct MassetData { uint256 swapFee; uint256 redemptionFee; uint256 cacheSize; uint256 surplus; BassetPersonal[] bAssetPersonal; BassetData[] bAssetData; BasketState basket; AmpData ampData; WeightLimits weightLimits; } struct AssetData { uint8 idx; uint256 amt; BassetPersonal personal; } struct Asset { uint8 idx; address addr; bool exists; }
Adds a new dial that can be voted on to receive weekly rewards. Callable by system governor. _recipient Address of the contract that will receive rewards. _cap Cap where 0 = uncapped and 10 = 10%. _notify If true, `notifyRewardAmount` is called in the `distributeRewards` function./
function addDial( address _recipient, uint8 _cap, bool _notify ) external onlyGovernor { _addDial(_recipient, _cap, _notify); }
89,330
//Address: 0xce0589450422ce360215c6c50f9809e753e3829b //Contract name: RntCrowdsale //Balance: 0 Ether //Verification Date: 1/10/2018 //Transacion Count: 43 // CODE STARTS HERE pragma solidity ^0.4.15; /** * @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() { 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) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Contracts that should not own Ether * @author Remco Bloemen <remco@2π.com> * @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up * in the contract, it will allow the owner to reclaim this ether. * @notice Ether can still be send to this contract by: * calling functions labeled `payable` * `selfdestruct(contract_address)` * mining directly to the contract address */ contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ function HasNoEther() payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * Fixed crowdsale pricing - everybody gets the same price. */ contract PricingStrategy is HasNoEther { using SafeMath for uint; /* How many weis one token costs */ uint256 public oneTokenInWei; address public crowdsaleAddress; function PricingStrategy(address _crowdsale) { crowdsaleAddress = _crowdsale; } modifier onlyCrowdsale() { require(msg.sender == crowdsaleAddress); _; } /** * Calculate the current price for buy in amount. * */ function calculatePrice(uint256 _value, uint256 _decimals) public constant returns (uint) { uint256 multiplier = 10 ** _decimals; uint256 weiAmount = _value.mul(multiplier); uint256 tokens = weiAmount.div(oneTokenInWei); return tokens; } function setTokenPriceInWei(uint _oneTokenInWei) onlyCrowdsale public returns (bool) { oneTokenInWei = _oneTokenInWei; return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract RNTMultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); event Pause(); event Unpause(); /* * Constants */ uint constant public MAX_OWNER_COUNT = 10; uint constant public ADMINS_COUNT = 2; /* * Storage */ mapping(uint => WalletTransaction) public transactions; mapping(uint => mapping(address => bool)) public confirmations; mapping(address => bool) public isOwner; mapping(address => bool) public isAdmin; address[] public owners; address[] public admins; uint public required; uint public transactionCount; bool public paused = false; struct WalletTransaction { address sender; address destination; uint value; bytes data; bool executed; } /* * Modifiers */ /// @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); _; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier adminExists(address admin) { require(isAdmin[admin]); _; } modifier adminDoesNotExist(address admin) { require(!isAdmin[admin]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { if (transactions[transactionId].executed) require(false); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { if (ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) { require(false); } _; } modifier validAdminsCount(uint adminsCount) { require(adminsCount == ADMINS_COUNT); _; } /// @dev Fallback function allows to deposit ether. function() whenNotPaused payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial admins and required number of confirmations. /// @param _admins List of initial owners. /// @param _required Number of required confirmations. function RNTMultiSigWallet(address[] _admins, uint _required) public // validAdminsCount(_admins.length) // validRequirement(_admins.length, _required) { for (uint i = 0; i < _admins.length; i++) { require(_admins[i] != 0 && !isOwner[_admins[i]] && !isAdmin[_admins[i]]); isAdmin[_admins[i]] = true; isOwner[_admins[i]] = true; } admins = _admins; owners = _admins; required = _required; } /// @dev called by the owner to pause, triggers stopped state function pause() adminExists(msg.sender) whenNotPaused public { paused = true; Pause(); } /// @dev called by the owner to unpause, returns to normal state function unpause() adminExists(msg.sender) whenPaused public { paused = false; Unpause(); } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public whenNotPaused adminExists(msg.sender) ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public whenNotPaused adminExists(msg.sender) adminDoesNotExist(owner) ownerExists(owner) { isOwner[owner] = false; for (uint i = 0; i < owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public whenNotPaused adminExists(msg.sender) adminDoesNotExist(owner) ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i = 0; i < owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public whenNotPaused adminExists(msg.sender) validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public whenNotPaused ownerExists(msg.sender) returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public whenNotPaused ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public whenNotPaused ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public whenNotPaused ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { WalletTransaction storage walletTransaction = transactions[transactionId]; walletTransaction.executed = true; if (walletTransaction.destination.call.value(walletTransaction.value)(walletTransaction.data)) Execution(transactionId); else { ExecutionFailure(transactionId); walletTransaction.executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = WalletTransaction({ sender : msg.sender, destination : destination, value : value, data : data, executed : false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } // @dev Returns list of admins. // @return List of admin addresses function getAdmins() public constant returns (address[]) { return admins; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i = 0; i < count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } contract RntPresaleEthereumDeposit is Pausable { using SafeMath for uint256; uint256 public overallTakenEther = 0; mapping(address => uint256) public receivedEther; struct Donator { address addr; uint256 donated; } Donator[] donators; RNTMultiSigWallet public wallet; function RntPresaleEthereumDeposit(address _walletAddress) { wallet = RNTMultiSigWallet(_walletAddress); } function updateDonator(address _address) internal { bool isFound = false; for (uint i = 0; i < donators.length; i++) { if (donators[i].addr == _address) { donators[i].donated = receivedEther[_address]; isFound = true; break; } } if (!isFound) { donators.push(Donator(_address, receivedEther[_address])); } } function getDonatorsNumber() external constant returns (uint256) { return donators.length; } function getDonator(uint pos) external constant returns (address, uint256) { return (donators[pos].addr, donators[pos].donated); } /* * Fallback function for sending ether to wallet and update donators info */ function() whenNotPaused payable { wallet.transfer(msg.value); overallTakenEther = overallTakenEther.add(msg.value); receivedEther[msg.sender] = receivedEther[msg.sender].add(msg.value); updateDonator(msg.sender); } function receivedEtherFrom(address _from) whenNotPaused constant public returns (uint256) { return receivedEther[_from]; } function myEther() whenNotPaused constant public returns (uint256) { return receivedEther[msg.sender]; } } contract PresaleFinalizeAgent is HasNoEther { using SafeMath for uint256; RntPresaleEthereumDeposit public deposit; address public crowdsaleAddress; mapping(address => uint256) public tokensForAddress; uint256 public weiPerToken = 0; bool public sane = true; function PresaleFinalizeAgent(address _deposit, address _crowdsale){ deposit = RntPresaleEthereumDeposit(_deposit); crowdsaleAddress = _crowdsale; } modifier onlyCrowdsale() { require(msg.sender == crowdsaleAddress); _; } function isSane() public constant returns (bool) { return sane; } function setCrowdsaleAddress(address _address) onlyOwner public { crowdsaleAddress = _address; } function finalizePresale(uint256 presaleTokens) onlyCrowdsale public { require(sane); uint256 overallEther = deposit.overallTakenEther(); uint256 multiplier = 10 ** 18; overallEther = overallEther.mul(multiplier); weiPerToken = overallEther.div(presaleTokens); require(weiPerToken > 0); sane = false; } } contract IRntToken { uint256 public decimals = 18; uint256 public totalSupply = 1000000000 * (10 ** 18); string public name = "RNT Token"; string public code = "RNT"; function balanceOf() public constant returns (uint256 balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); } contract RntCrowdsale is Pausable { using SafeMath for uint256; enum Status {Unknown, Presale, ICO, Finalized} // Crowdsale status Status public currentStatus = Status.Unknown; bool public isPresaleStarted = false; bool public isPresaleFinalized = false; bool public isIcoStarted = false; bool public isIcoFinalized = false; uint256 public icoReceivedWei; uint256 public icoTokensSold; uint256 public icoInvestmentsCount = 0; mapping(address => uint256) public icoInvestments; mapping(address => uint256) public icoTokenTransfers; IRntToken public token; PricingStrategy public pricingStrategy; PresaleFinalizeAgent public presaleFinalizeAgent; RntPresaleEthereumDeposit public deposit; address public wallet; address public proxy; mapping(address => bool) public tokensAllocationAllowed; uint public presaleStartTime; uint public presaleEndTime; uint public icoStartTime; uint public icoEndTime; /** @notice A new investment was made. */ event Invested(address indexed investor, uint weiAmount, uint tokenAmount, bytes16 indexed customerId); event PresaleStarted(uint timestamp); event PresaleFinalized(uint timestamp); event IcoStarted(uint timestamp); event IcoFinalized(uint timestamp); /** @notice Token price was calculated. */ event TokensPerWeiReceived(uint tokenPrice); /** @notice Presale tokens was claimed. */ event PresaleTokensClaimed(uint count); function RntCrowdsale(address _tokenAddress) { token = IRntToken(_tokenAddress); } /** @notice Allow call function only if crowdsale on specified status. */ modifier inStatus(Status status) { require(getCrowdsaleStatus() == status); _; } /** @notice Check that address can allocate tokens. */ modifier canAllocateTokens { require(tokensAllocationAllowed[msg.sender] == true); _; } /** @notice Allow address to call allocate function. @param _addr Address for allowance @param _allow Allowance */ function allowAllocation(address _addr, bool _allow) onlyOwner external { tokensAllocationAllowed[_addr] = _allow; } /** @notice Set PresaleFinalizeAgent address. @dev Used to calculate price for one token. */ function setPresaleFinalizeAgent(address _agentAddress) whenNotPaused onlyOwner external { presaleFinalizeAgent = PresaleFinalizeAgent(_agentAddress); } /** @notice Set PricingStrategy address. @dev Used to calculate tokens that will be received through investment. */ function setPricingStartegy(address _pricingStrategyAddress) whenNotPaused onlyOwner external { pricingStrategy = PricingStrategy(_pricingStrategyAddress); } /** @notice Set RNTMultiSigWallet address. @dev Wallet for invested wei. */ function setMultiSigWallet(address _walletAddress) whenNotPaused onlyOwner external { wallet = _walletAddress; } /** @notice Set RntTokenProxy address. */ function setBackendProxyBuyer(address _proxyAddress) whenNotPaused onlyOwner external { proxy = _proxyAddress; } /** @notice Set RntPresaleEhtereumDeposit address. @dev Deposit used to calculate presale tokens. */ function setPresaleEthereumDeposit(address _depositAddress) whenNotPaused onlyOwner external { deposit = RntPresaleEthereumDeposit(_depositAddress); } /** @notice Get current crowdsale status. @return { One of possible crowdsale statuses [Unknown, Presale, ICO, Finalized] } */ function getCrowdsaleStatus() constant public returns (Status) { return currentStatus; } /** @notice Start presale and track start time. */ function startPresale() whenNotPaused onlyOwner external { require(!isPresaleStarted); currentStatus = Status.Presale; isPresaleStarted = true; presaleStartTime = now; PresaleStarted(presaleStartTime); } /** @notice Finalize presale, calculate token price, track finalize time. */ function finalizePresale() whenNotPaused onlyOwner external { require(isPresaleStarted && !isPresaleFinalized); require(presaleFinalizeAgent.isSane()); uint256 presaleSupply = token.totalSupply(); // Presale supply is 20% of total presaleSupply = presaleSupply.div(5); presaleFinalizeAgent.finalizePresale(presaleSupply); uint tokenWei = presaleFinalizeAgent.weiPerToken(); pricingStrategy.setTokenPriceInWei(tokenWei); TokensPerWeiReceived(tokenWei); require(tokenWei > 0); currentStatus = Status.Unknown; isPresaleFinalized = true; presaleEndTime = now; PresaleFinalized(presaleEndTime); } /** @notice Start ICO and track start time. */ function startIco() whenNotPaused onlyOwner external { require(!isIcoStarted && isPresaleFinalized); currentStatus = Status.ICO; isIcoStarted = true; icoStartTime = now; IcoStarted(icoStartTime); } /** @notice Finalize ICO and track finalize time. */ function finalizeIco() whenNotPaused onlyOwner external { require(!isIcoFinalized && isIcoStarted); currentStatus = Status.Finalized; isIcoFinalized = true; icoEndTime = now; IcoFinalized(icoEndTime); } /** @notice Handle invested wei. @dev Send some amount of wei to wallet and get tokens that will be calculated according Pricing Strategy. It will transfer ether to wallet only if investment did inside ethereum using payable method. @param _receiver The Ethereum address who receives the tokens. @param _customerUuid (optional) UUID v4 to track the successful payments on the server side. */ function investInternal(address _receiver, bytes16 _customerUuid) private { uint weiAmount = msg.value; uint256 tokenAmount = pricingStrategy.calculatePrice(weiAmount, 18); require(tokenAmount != 0); if (icoInvestments[_receiver] == 0) { // A new investor icoInvestmentsCount++; } icoInvestments[_receiver] = icoInvestments[_receiver].add(weiAmount); icoTokenTransfers[_receiver] = icoTokenTransfers[_receiver].add(tokenAmount); icoReceivedWei = icoReceivedWei.add(weiAmount); icoTokensSold = icoTokensSold.add(tokenAmount); assignTokens(owner, _receiver, tokenAmount); // Pocket the money wallet.transfer(weiAmount); // Tell us invest was success Invested(_receiver, weiAmount, tokenAmount, _customerUuid); } /** @notice Handle tokens allocating. @dev Uses when tokens was bought not in ethereum @param _receiver The Ethereum address who receives the tokens. @param _customerUuid (optional) UUID v4 to track the successful payments on the server side. @param _weiAmount Wei amount, that should be specified only if user was invested out */ function allocateInternal(address _receiver, bytes16 _customerUuid, uint256 _weiAmount) private { uint256 tokenAmount = pricingStrategy.calculatePrice(_weiAmount, 18); require(tokenAmount != 0); if (icoInvestments[_receiver] == 0) { // A new investor icoInvestmentsCount++; } icoInvestments[_receiver] = icoInvestments[_receiver].add(_weiAmount); icoTokenTransfers[_receiver] = icoTokenTransfers[_receiver].add(tokenAmount); icoReceivedWei = icoReceivedWei.add(_weiAmount); icoTokensSold = icoTokensSold.add(tokenAmount); assignTokens(owner, _receiver, tokenAmount); // Tell us invest was success Invested(_receiver, _weiAmount, tokenAmount, _customerUuid); } /** @notice Allocate tokens to specified address. @dev Function that should be used only by proxy to handle payments outside ethereum. @param _receiver The Ethereum address who receives the tokens. @param _customerUuid (optional) UUID v4 to track the successful payments on the server side. @param _weiAmount User invested amount of money in wei. */ function allocateTokens(address _receiver, bytes16 _customerUuid, uint256 _weiAmount) whenNotPaused canAllocateTokens public { allocateInternal(_receiver, _customerUuid, _weiAmount); } /** @notice Make an investment. @dev Can be called only at ICO status. Should have wei != 0. @param _customerUuid (optional) UUID v4 to track the successful payments on the server side */ function invest(bytes16 _customerUuid) whenNotPaused inStatus(Status.ICO) public payable { investInternal(msg.sender, _customerUuid); } /** @notice Function for claiming tokens for presale investors. @dev Can be called only after presale ends. Tokens will be transfered to callers address. */ function claimPresaleTokens() whenNotPaused external { require(isPresaleFinalized == true); uint256 senderEther = deposit.receivedEtherFrom(msg.sender); uint256 multiplier = 10 ** 18; senderEther = senderEther.mul(multiplier); uint256 tokenWei = pricingStrategy.oneTokenInWei(); uint256 tokensAmount = senderEther.div(tokenWei); require(tokensAmount > 0); token.transferFrom(owner, msg.sender, tokensAmount); PresaleTokensClaimed(tokensAmount); } /** @notice Transfer issued tokens to the investor. */ function assignTokens(address _from, address _receiver, uint _tokenAmount) private { token.transferFrom(_from, _receiver, _tokenAmount); } }
Allows an owner to confirm a transaction. transactionId Transaction ID.
function confirmTransaction(uint transactionId) public whenNotPaused ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); }
5,417,851
./full_match/80001/0xFe4643459C43e1F5F66682A5DED9D6fC3b53fB3F/sources/project_/contracts/PlayerDeposit.sol
Aprovamos Transferimos
function withdrawToken( address _to, address _token, uint256 _amount ) public onlyOwner { require(_amount > 0, "Invalid withdrawal amount."); require(_to != address(this), "Invalid withdraw address."); require( _amount > 0 && _amount <= IERC20(_token).balanceOf(address(this)), "Invalid withdraw amount." ); IERC20(_token).approve(address(this), _amount); IERC20(_token).transferFrom(address(this), _to, _amount); }
5,560,492
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/Distribution.sol
Updates an actor's lastValuePerShare to the distribution's current valuePerShare, and returns the change in value for the actor, since their last update./
function accumulateActor( Data storage self, bytes32 actorId ) internal returns (int valueChangeD18) { DistributionActor.Data storage actor = self.actorInfo[actorId]; return _updateLastValuePerShare(self, actor, actor.sharesD18); }
16,517,087
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul: *"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint a, uint b) internal pure returns (uint) { return mod(a, b, "mod: %"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } /** * @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: < 0"); 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: !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: !succeed"); } } } library Keep3rV1Library { function getReserve(address pair, address reserve) external view returns (uint) { (uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves(); if (IUniswapV2Pair(pair).token0() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).token1() == reserve) { return _r1; } else { return 0; } } } interface IUniswapV2Pair { 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); } interface IGovernance { function proposeJob(address job) external; } interface IKeep3rV1Helper { function getQuoteLimit(uint gasUsed) external view returns (uint); } // File: contracts/Keep3r.sol pragma solidity ^0.6.6; contract Relay3rV1 is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; /// @notice Keep3r Helper to set max prices for the ecosystem IKeep3rV1Helper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "Relay3rV1"; /// @notice EIP-20 token symbol for this token string public constant symbol = "RL3R"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice Keeper rights approved to be spent by spender event KeeperRightApproval(address indexed owner, address indexed spender, bool allowed); /// @notice Keeper right transfered to a new address event KeeperRightTransfered(address indexed from, address indexed to, address indexed bond); /// @notice 3 days to bond to become a keeper uint public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint public UNBOND = 14 days; /// @notice 3 days till liquidity can be bound uint public LIQUIDITYBOND = 3 days; /// @notice direct liquidity fee 0.3%,Can be modified by governance contract uint public FEE = 30; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice tracks underlying votes (that don't have bond) mapping(address => uint) public votes; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @dev job proposal delay mapping(address => uint) internal jobProposalDelayInternal; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; mapping(address => mapping (address => bool)) internal KeeperAllowances; mapping(address => mapping (address => mapping(address => bool))) internal KeeperAllowancesPassed; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor() public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); } modifier onlyGovernance(){ require(msg.sender == governance); _; } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.mul(FEE).div(BASE); credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee)); payable(governance).transfer(_fee); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).balanceOf(address(this)).sub(_before); uint _fee = _received.mul(FEE).div(BASE); credits[job][credit] = credits[job][credit].add(_received.sub(_fee)); IERC20(credit).safeTransfer(governance, _fee); emit AddCredit(credit, job, msg.sender, block.number, _received); } /** * @notice Add non transferable votes for governance * @param voter to add the votes to * @param amount of votes to add */ function addVotes(address voter, uint amount) external onlyGovernance{ votes[voter] = votes[voter].add(amount); totalBonded = totalBonded.add(amount); _moveDelegates(address(0), delegates[voter], amount); } /** * @notice Remove non transferable votes for governance * @param voter to subtract the votes * @param amount of votes to remove */ function removeVotes(address voter, uint amount) external onlyGovernance{ votes[voter] = votes[voter].sub(amount); totalBonded = totalBonded.sub(amount); _moveDelegates(delegates[voter], address(0), amount); } /** * @notice Add credit to a job to be paid out for work * @param job the job being credited * @param amount the amount of credit being added to the job */ function addRLRCredit(address job, uint amount) external onlyGovernance{ require(jobs[job], "addRLRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external onlyGovernance{ require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external onlyGovernance{ liquidityAccepted[liquidity] = false; } /** * @notice Set new liquidity fee from governance * @param newFee the new fee for further liquidity adds */ function setLiquidityFee(uint newFee) external onlyGovernance{ FEE = newFee; } /** * @notice Set bonding delay from governance * @param newBond the new bonding delay */ function setBondingDelay(uint newBond) external onlyGovernance{ BOND = newBond; } /** * @notice Set bonding delay from governance * @param newUnbond the new unbonding delay */ function setUnbondingDelay(uint newUnbond) external onlyGovernance{ UNBOND = newUnbond; } /** * @notice Set liquidity bonding delay from governance * @param newLiqBond the new liquidity bonding delay */ function setLiquidityBondingDelay(uint newLiqBond) external onlyGovernance{ LIQUIDITYBOND = newLiqBond; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Gets the job proposal delay with the current unbound delay */ function jobProposalDelay(address job) public view returns (uint){ return jobProposalDelayInternal[job].add(UNBOND); } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now; liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay(job) < now) { IGovernance(governance).proposeJob(job); jobProposalDelayInternal[job] = now; } emit SubmitJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "applyCreditToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(block.timestamp.sub(liquidityApplied[provider][liquidity][job].add(LIQUIDITYBOND)) >= 0, "credit: bonding"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, liquidity, provider, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now; liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].sub(_credit); } emit UnbondJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(block.timestamp.sub(liquidityUnbonding[msg.sender][liquidity][job].add(UNBOND)) >= 0, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, liquidity, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external onlyGovernance{ _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work and get paid in ETH * @param keeper address of the keeper that performed the work */ function workedETH(address keeper) external { receiptETH(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; _bond(address(this), keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; IERC20(credit).safeTransfer(keeper, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) public { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); if (bonding == address(this)) { totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); if (bonding == address(this)) { totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external onlyGovernance{ require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external onlyGovernance{ jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(address _kprh) external onlyGovernance{ KPRH = IKeep3rV1Helper(_kprh); } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external onlyGovernance{ pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) public returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); //In this part we changed the addition of current time + bond time to the time bond was called bondings[msg.sender][bonding] = now; if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).balanceOf(address(this)); IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount); amount = IERC20(bonding).balanceOf(address(this)).sub(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice Does initial data initialization of keeper entry * @param sender the address to init data for */ function doDataInit(address sender) internal { if (firstSeen[sender] == 0) { firstSeen[sender] = now; keeperList.push(sender); lastJob[sender] = now; } } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "activate: blacklisted"); //In this part we changed the check of bonding time being lesser than now to check if current time is > bonding time require(bondings[msg.sender][bonding] != 0 && block.timestamp.sub(bondings[msg.sender][bonding].add(BOND)) >= 0, "activate: bonding"); //Setup initial data doDataInit(msg.sender); keepers[msg.sender] = true; _bond(bonding, msg.sender, pendingbonds[msg.sender][bonding]); pendingbonds[msg.sender][bonding] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender][bonding]); } function doKeeperrightChecks(address from,address to,address bonding) internal returns (bool){ require(!blacklist[from], "transferKeeperRight: blacklisted"); require(isKeeper(from), "transferKeeperRight: not keeper"); require(msg.sender == from || KeeperAllowances[msg.sender][from],"transferKeeperRight: Unauthorized transfer call"); require(bondings[from][bonding] != 0 && block.timestamp.sub(bondings[from][bonding].add(BOND)) >= 0, "transferKeeperRight: bonding"); KeeperAllowancesPassed[from][to][bonding] = true; return true; } /** * @notice allows a keeper to transfer their keeper rights and bonds to another address * @param bonding the asset being transfered to new address as bond collateral * @param from the address keeper rights and bonding amount is transfered from * @param to the address keeper rights and bonding amount is transfered to */ function transferKeeperRight(address bonding,address from,address to) public { require(KeeperAllowancesPassed[from][to][bonding],"pass doKeeperrightChecks first"); doDataInit(to); //Set the user calling keeper stat to false keepers[from] = false; //Set the to addr keeper stat to true keepers[to] = true; //Unbond from sender uint currentbond = bonds[from][bonding]; _unbond(bonding,from,currentbond); //Bond to receiver _bond(bonding,to,currentbond); //Remove allowance passed after transfer KeeperAllowancesPassed[from][to][bonding] = false; //remove rights for this address after transfer is done from caller KeeperAllowances[from][msg.sender] = false; emit KeeperRightTransfered(from,to,bonding); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now; _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } // function getUnbondTime(address user,address bonding) public view returns (uint256){ // return unbondings[user][bonding].add(UNBOND); // } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external nonReentrant { //Same changes as on bonding check is done here require(unbondings[msg.sender][bonding] != 0 && block.timestamp.sub(unbondings[msg.sender][bonding].add(UNBOND)) >= 0, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external onlyGovernance{ disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public nonReentrant onlyGovernance{ if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external onlyGovernance{ keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external onlyGovernance{ disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Approve `spender` to transfer Keeper rights * @param spender The address of the account which may transfer keeper rights * @param fAllow whether this spender should be able to transfer rights * @return Whether or not the approval succeeded */ function keeperrightapprove(address spender,bool fAllow) public returns (bool) { KeeperAllowances[msg.sender][spender] = fAllow; emit KeeperRightApproval(msg.sender, spender, fAllow); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount); balances[dst] = balances[dst].add(amount); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
confirms if the current keeper is registered, can be used for general (non critical) functions keeper the keeper being investigated return true/false if the address is a keeper/
function isKeeper(address keeper) public returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; }
1,429,909
pragma solidity >=0.4.22 <0.6.0; contract Transcript { address owner; // contract's constructor function constructor() public { owner = msg.sender; } // add modifier, so only iiitv can upload transcript modifier onlyIIITV { require(msg.sender == owner); _; } // courses struct course { string courseId; string courseName; uint8 courseCredits; } uint16 public coursesCount; uint16 public courseGradeCount; uint16 public semPointsCount; modifier courseIdCheck(uint courseId) { require( courseId < coursesCount ); _;} // Enumeration for semesters enum semesters { semester1, semester2, semester3, semester4, semester5, semester6, semester7, semester8 } // student details struct student { uint32 studentId; string studnetName; string dptType; string batchYear; } // student hash storage struct studentHash { bytes32 hashvalue; uint32 studentId; } // student's couse grade struct courseGrade { uint32 studentId; string courseId; semesters semester; string grade; } // keyss for couse grade struct gradeHash { bytes32 gradeKey; uint32 studentId; string courseId; semesters semester; } // student sem points struct points { uint32 studentId; semesters semester; string cpi; string spi; } // keys for points struct pointHash { bytes32 pointkey; uint32 studentId; semesters semester; } studentHash[] studenthashes; //keys for studentDetails gradeHash[] gradeHashes; // keys for courseGrade pointHash[] pointHashes; // keys for points course[] courses; // mapping(uint => course) courses; mapping(bytes32 => student) studentDetails; mapping(bytes32 => courseGrade) courseGrades; mapping(bytes32 => points) totalPoints; mapping(string => bool) isCourseExit; //events event courseAdded(string courseId); event studentAdded(uint32 studentId); event courseGradeAdded(bytes32 hashvalue); event gradePointAdded(bytes32 hashvalue); // check if student exits function checkStudent(bytes32 _hashvalue) public view returns (bool) { for(uint16 i =0; i< studenthashes.length; i++) { if(studenthashes[i].studentId == studentDetails[_hashvalue].studentId ){ return true; } } return false; } function checkCourse(string memory _courseId) public view returns (bool) { if(isCourseExit[_courseId] == true){ return false; } else return true; } // --------- ADD functions --------- // add student hash and student details function addStudentDetails(string memory _randomValue, uint32 _studentId, string memory _studnetName, string memory _batchYear, string memory _dptType) public onlyIIITV { bytes32 hashvalue = getHash(_studentId); require(studentDetails[hashvalue].studentId != _studentId); //generating hash value of student bytes32 hvalue; hvalue = sha256(abi.encodePacked(_studentId, _randomValue)); studentHash memory hashes; //storing student hashes hashes = studentHash({ studentId : _studentId, hashvalue : hvalue }); studenthashes.push(hashes); // adding studentDetails studentDetails[hvalue].studentId = _studentId; studentDetails[hvalue].studnetName = _studnetName; studentDetails[hvalue].dptType = _dptType; studentDetails[hvalue].batchYear = _batchYear; emit studentAdded(_studentId); } // add course function addCourse(string memory _courseId, string memory _courseName, uint8 _courseCredits) public onlyIIITV { require(checkCourse(_courseId)); // add if course not exits course memory c; //storing course details c = course({ courseId : _courseId, courseName : _courseName, courseCredits : _courseCredits }); courses.push(c); // courses[coursesCount].courseId = _courseId; // courses[coursesCount].courseName = _courseId; // courses[coursesCount].courseCredits = _courseCredits; emit courseAdded(_courseId); coursesCount = coursesCount +1; isCourseExit[_courseId] = true; } // add course grades function addCourseGrade(uint32 _studentId, string memory _courseId, uint8 _semester, string memory _grade ) public onlyIIITV { bytes32 hashvalue = sha256(abi.encodePacked(_studentId, _courseId, _semester)); require(checkStudent(getHash(_studentId))); // add if student exits require(!checkCourse(_courseId)); // add only if course exits require(keccak256(abi.encodePacked(courseGrades[hashvalue].courseId)) != keccak256(abi.encodePacked(_courseId))); gradeHash memory key; //storing keys for coursegrade key = gradeHash({ gradeKey : hashvalue, studentId : _studentId, courseId : _courseId, semester : semesters(_semester) }); gradeHashes.push(key); courseGrades[hashvalue].studentId = _studentId; courseGrades[hashvalue].courseId = _courseId; courseGrades[hashvalue].semester = semesters(_semester); courseGrades[hashvalue].grade = _grade; courseGradeCount = courseGradeCount +1; emit courseGradeAdded(hashvalue); } // student sem points function addPoints(uint32 _studentId, uint8 _semester, string memory _spi, string memory _cpi) public onlyIIITV { bytes32 hashvalue = sha256(abi.encodePacked(_studentId, _semester)); require(checkStudent(getHash(_studentId))); // add if student exits; require(keccak256(abi.encodePacked(uint8(totalPoints[hashvalue].semester))) != keccak256(abi.encodePacked(_semester))); pointHash memory key; //storing keys for coursegrade key = pointHash({ pointkey : hashvalue, studentId : _studentId, semester : semesters(_semester) }); pointHashes.push(key); totalPoints[hashvalue].studentId = _studentId; totalPoints[hashvalue].semester = semesters(_semester); totalPoints[hashvalue].spi = _spi; totalPoints[hashvalue].cpi = _cpi; semPointsCount = semPointsCount+1; emit gradePointAdded(hashvalue); } // -------- MODIFY functions------ // modify student details function changeStudentDetails(bytes32 _hashvalue, string memory _studnetName, string memory _batchYear, string memory _dptType) public onlyIIITV { require(checkStudent(_hashvalue)); if(bytes(_studnetName).length != 0){ studentDetails[_hashvalue].studnetName =_studnetName; } if(bytes(_dptType).length != 0){ studentDetails[_hashvalue].dptType = _dptType; } if(bytes(_batchYear).length != 0){ studentDetails[_hashvalue].batchYear = _batchYear; } } // modify course function changeCourse(string memory _courseId, string memory _courseName, uint8 _courseCredits) public onlyIIITV { require(!checkCourse(_courseId)); // add if course exits for(uint16 i =0; i< courses.length; i++) { if(keccak256(abi.encodePacked(courses[i].courseId)) == keccak256(abi.encodePacked(_courseId))) { if(bytes(_courseName).length != 0){ courses[i].courseName =_courseName; } if(_courseCredits != 0){ courses[i].courseCredits =_courseCredits; } } } } // modify course grades function changeCourseGrade(uint32 _studentId, string memory _courseId, uint8 _semester, string memory _grade ) public onlyIIITV { bytes32 hashvalue = getCourseGradeHash(_studentId, _courseId, _semester); require(checkStudent(getHash(_studentId))); // add if student exits require(!checkCourse(_courseId)); // add only if course exits require(keccak256(abi.encodePacked(courseGrades[hashvalue].courseId)) == keccak256(abi.encodePacked(_courseId))); // add if course graded if(bytes(_grade).length != 0){ courseGrades[hashvalue].grade = _grade; } } // modify points grades function changePoints(uint32 _studentId, uint8 _semester, string memory _spi, string memory _cpi ) public onlyIIITV { bytes32 hashvalue = getPointsHash(_studentId, _semester); require(checkStudent(getHash(_studentId))); // add if student exits require(uint8(totalPoints[hashvalue].semester) == _semester); // add if course graded if(bytes(_spi).length != 0){ totalPoints[hashvalue].spi = _spi; } if(bytes(_cpi).length != 0){ totalPoints[hashvalue].cpi = _cpi; } } // -------- GET functions------ // get hash of a student transcript function getHash(uint32 _studentId) public view returns (bytes32){ for(uint16 i =0; i< studenthashes.length; i++) { if(studenthashes[i].studentId == _studentId) { return (studenthashes[i].hashvalue); } } } // get studentId of a student transcript function getStudentId(bytes32 _hash) public view returns (uint32){ for(uint16 i =0; i< studenthashes.length; i++) { if(studenthashes[i].hashvalue == _hash) { return (studenthashes[i].studentId); } } } // get hash of a course grade function getCourseGradeHash(uint32 _studentId, string memory _courseId, uint8 _semester) public view returns (bytes32){ for(uint16 i =0; i< gradeHashes.length; i++) { if(gradeHashes[i].studentId == _studentId && keccak256(abi.encodePacked(gradeHashes[i].courseId)) == keccak256(abi.encodePacked(_courseId)) && uint8(gradeHashes[i].semester) == _semester) { return (gradeHashes[i].gradeKey); } } } // get hash of a points transcript function getPointsHash(uint32 _studentId, uint8 _semester) public view returns (bytes32){ for(uint16 i =0; i< pointHashes.length; i++) { if(pointHashes[i].studentId == _studentId && uint8(pointHashes[i].semester) == _semester) { return (pointHashes[i].pointkey); } } } // get student details function getStudentDetails(bytes32 hashvalue) public view returns (uint32 , string memory , string memory , string memory) { return (studentDetails[hashvalue].studentId, studentDetails[hashvalue].studnetName, studentDetails[hashvalue].dptType, studentDetails[hashvalue].batchYear); } // get course function getCourse(string memory _courseId) public view returns(string memory, string memory, uint8){ for(uint16 i =0; i< courses.length; i++) { if(keccak256(abi.encodePacked(courses[i].courseId)) == keccak256(abi.encodePacked(_courseId))) { return(courses[i].courseId, courses[i].courseName, courses[i].courseCredits); } } } // get course by index function getCourseByIndex(uint16 _index) public view returns(string memory, string memory, uint8){ course storage c = courses[_index]; return(c.courseId, c.courseName, c.courseCredits); } // get course grade -- transcript function getCourseGrade(bytes32 hashvalue) public view returns(uint32, string memory, uint8, string memory) { // if(keccak256(abi.encodePacked(courseGrades[hashvalue].courseId)) == keccak256(abi.encodePacked(_courseId))){ return(courseGrades[hashvalue].studentId, courseGrades[hashvalue].courseId, uint8(courseGrades[hashvalue].semester), courseGrades[hashvalue].grade ); // } } // get point grade -- transcript function getPoints(bytes32 hashvalue) public view returns(uint32, uint8, string memory, string memory) { // if(uint8(totalPoints[hashvalue].semester) == _semester){ return(totalPoints[hashvalue].studentId, uint8(totalPoints[hashvalue].semester), totalPoints[hashvalue].spi, totalPoints[hashvalue].cpi ); // } } }
get point grade -- transcript if(uint8(totalPoints[hashvalue].semester) == _semester){ }
function getPoints(bytes32 hashvalue) public view returns(uint32, uint8, string memory, string memory) { return(totalPoints[hashvalue].studentId, uint8(totalPoints[hashvalue].semester), totalPoints[hashvalue].spi, totalPoints[hashvalue].cpi ); }
12,776,351
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2016-2019 zOS Global Limited * */ pragma solidity ^0.8.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 { // Optional functions function name() external view returns (string memory); function symbol() external view returns (string memory); event NameChanged(string name, string symbol); function decimals() external view returns (uint8); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC677Receiver { function onTokenTransfer(address from, uint256 amount, bytes calldata data) external returns (bool); } /** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * COPYRIGHT (c) 2020 Aktionariat AG (aktionariat.com) * * Permission is hereby granted 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. * - All automated license fee payments integrated into this and related Software * are preserved. * * 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.8.0; import "../utils/Ownable.sol"; import "../ERC20/IERC20.sol"; import "../ERC20/IERC677Receiver.sol"; contract Brokerbot is Ownable { address public paymenthub; address public immutable base; // ERC-20 currency address public immutable token; // ERC-20 share token address public constant COPYRIGHT = 0x29Fe8914e76da5cE2d90De98a64d0055f199d06D; // Aktionariat AG uint256 private price; // current offer price, without drift uint256 public increment; // increment uint256 public driftStart; uint256 public timeToDrift; // seconds until drift pushes price by one drift increment int256 public driftIncrement; uint8 private constant LICENSEFEEBPS = 90; // Note that these settings might be hard-coded in various places, so better not change these values. uint8 private constant BUYING_ENABLED = 0x1; uint8 private constant SELLING_ENABLED = 0x2; // note that in the UI, we call the setting "convert ether", which is the opposite uint8 private constant KEEP_ETHER = 0x4; uint8 private constant VERSION = 0x1; // more bits to be used by payment hub uint256 public settings = BUYING_ENABLED | SELLING_ENABLED | (VERSION<<248); event Trade(address indexed token, address who, bytes ref, int amount, address base, uint totPrice, uint fee, uint newprice); event ChangePaymentHub(address newPaymentHub, address who); constructor( address _shareToken, uint256 _price, uint256 _increment, address _baseCurrency, address _owner, address _paymentHub ) Ownable(_owner) { base = _baseCurrency; token = _shareToken; price = _price; increment = _increment; paymenthub = _paymentHub; // Should we disabled recoverability in the recovery hub here? // No, if someone attacks us, we can always trigger a transfer and recover the tokens as well as the collateral. } function setPrice(uint256 newPrice, uint256 newIncrement) external onlyOwner { anchorPrice(newPrice); increment = newIncrement; } function hasDrift() public view returns (bool) { return timeToDrift != 0; } // secondsPerStep should be negative for downwards drift function setDrift(uint256 secondsPerStep, int256 newDriftIncrement) external onlyOwner { anchorPrice(getPrice()); timeToDrift = secondsPerStep; driftIncrement = newDriftIncrement; } function anchorPrice(uint256 currentPrice) private { price = currentPrice; // rely on time stamp is ok, no exact time stamp needed // solhint-disable-next-line not-rely-on-time driftStart = block.timestamp; } function getPrice() public view returns (uint256) { // rely on time stamp is ok, no exact time stamp needed // solhint-disable-next-line not-rely-on-time return getPriceAtTime(block.timestamp); } function getPriceAtTime(uint256 timestamp) public view returns (uint256) { if (hasDrift()){ uint256 passed = timestamp - driftStart; int256 drifted = int256(passed / timeToDrift) * driftIncrement; int256 driftedPrice = int256(price) + drifted; if (driftedPrice < 0){ return 0; } else { return uint256(driftedPrice); } } else { return price; } } function buy(address from, uint256 paid, bytes calldata ref) internal returns (uint256) { uint shares = getShares(paid); uint costs = notifyTraded(from, shares, ref); if (costs < paid){ IERC20(base).transfer(from, paid - costs); } IERC20(token).transfer(from, shares); return shares; } function notifyTraded(address from, uint256 shares, bytes calldata ref) internal returns (uint256) { require(hasSetting(BUYING_ENABLED), "buying disabled"); uint costs = getBuyPrice(shares); price = price + (shares * increment); emit Trade(token, from, ref, int256(shares), base, costs, 0, getPrice()); return costs; } function notifyTrade(address buyer, uint256 shares, bytes calldata ref) external onlyOwner { notifyTraded(buyer, shares, ref); } function notifyTradeAndTransfer(address buyer, uint256 shares, bytes calldata ref) public onlyOwner { notifyTraded(buyer, shares, ref); IERC20(token).transfer(buyer, shares); } function notifyTrades(address[] calldata buyers, uint256[] calldata shares, bytes[] calldata ref) external onlyOwner { for (uint i = 0; i < buyers.length; i++) { notifyTraded(buyers[i], shares[i], ref[i]); } } function notifyTradesAndTransfer(address[] calldata buyers, uint256[] calldata shares, bytes[] calldata ref) external onlyOwner { for (uint i = 0; i < buyers.length; i++) { notifyTradeAndTransfer(buyers[i], shares[i], ref[i]); } } /** * Payment hub might actually have sent another accepted token, including Ether. */ function processIncoming(address token_, address from, uint256 amount, bytes calldata ref) public payable returns (uint256) { require(msg.sender == token_ || msg.sender == base || msg.sender == paymenthub, "invalid calle"); if (token_ == token){ return sell(from, amount, ref); } else if (token_ == base){ return buy(from, amount, ref); } else { require(false, "invalid token"); return 0; } } // ERC-677 recipient function onTokenTransfer(address from, uint256 amount, bytes calldata ref) external returns (bool) { processIncoming(msg.sender, from, amount, ref); return true; } // (deprecated ITokenReceiver, still called by old payment hub) function onTokenTransfer(address token_, address from, uint256 amount, bytes calldata ref) external { processIncoming(token_, from, amount, ref); } function buyingEnabled() external view returns (bool){ return hasSetting(BUYING_ENABLED); } function sellingEnabled() external view returns (bool){ return hasSetting(SELLING_ENABLED); } function hasSetting(uint256 setting) private view returns (bool) { return settings & setting == setting; } function isDirectSale(bytes calldata ref) internal pure returns (bool) { if (ref.length == 0 || ref.length == 20) { return true; // old format } else { if (ref[0] == bytes1(0x01)){ return true; } else if (ref[0] == bytes1(0x02)) { return false; } else { require(false, "unknown ref"); return true; } } } function sell(address recipient, uint256 amount, bytes calldata ref) internal returns (uint256) { require(hasSetting(SELLING_ENABLED), "selling disabled"); uint256 totPrice = getSellPrice(amount); IERC20 baseToken = IERC20(base); uint256 fee = getLicenseFee(totPrice); price -= amount * increment; if (fee > 0){ baseToken.transfer(COPYRIGHT, fee); } if (isDirectSale(ref)){ baseToken.transfer(recipient, totPrice - fee); } emit Trade(token, recipient, ref, -int256(amount), base, totPrice, fee, getPrice()); return totPrice; } function getLicenseFee(uint256 totPrice) public virtual pure returns (uint256) { return totPrice * LICENSEFEEBPS / 10000; } function getSellPrice(uint256 shares) public view returns (uint256) { return getPrice(getPrice() - (shares * increment), shares); } function getBuyPrice(uint256 shares) public view returns (uint256) { return getPrice(getPrice(), shares); } function getPrice(uint256 lowest, uint256 shares) internal view returns (uint256){ if (shares == 0) { return 0; } else { uint256 highest = lowest + (shares - 1) * increment; return ((lowest + highest) / 2) * shares; } } function getShares(uint256 money) public view returns (uint256) { uint256 currentPrice = getPrice(); uint256 min = 0; uint256 max = money / currentPrice; while (min < max){ uint256 middle = (min + max)/2; uint256 totalPrice = getPrice(currentPrice, middle); if (money > totalPrice){ min = middle + 1; } else { max = middle; } } return min; } function withdrawEther(uint256 amount) external ownerOrHub() { payable(msg.sender).transfer(amount); // return change } function approve(address erc20, address who, uint256 amount) external onlyOwner() { IERC20(erc20).approve(who, amount); } function withdraw(address ercAddress, address to, uint256 amount) external ownerOrHub() { IERC20(ercAddress).transfer(to, amount); } function setPaymentHub(address hub) external onlyOwner() { paymenthub = hub; emit ChangePaymentHub(paymenthub, msg.sender); } function setSettings(uint256 settings_) external onlyOwner() { settings = settings_; } function setEnabled(bool newBuyingEnabled, bool newSellingEnabled) external onlyOwner() { if (newBuyingEnabled != hasSetting(BUYING_ENABLED)){ settings ^= BUYING_ENABLED; } if (newSellingEnabled != hasSetting(SELLING_ENABLED)){ settings ^= SELLING_ENABLED; } } modifier ownerOrHub() { require(owner == msg.sender || paymenthub == msg.sender, "not owner"); _; } } // SPDX-License-Identifier: MIT // // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // // Modifications: // - Replaced Context._msgSender() with msg.sender // - Made leaner // - Extracted interface 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. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor (address initialOwner) { owner = initialOwner; emit OwnershipTransferred(address(0), owner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) external onlyOwner { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } modifier onlyOwner() { require(owner == msg.sender, "not owner"); _; } }
Payment hub might actually have sent another accepted token, including Ether./
function processIncoming(address token_, address from, uint256 amount, bytes calldata ref) public payable returns (uint256) { require(msg.sender == token_ || msg.sender == base || msg.sender == paymenthub, "invalid calle"); if (token_ == token){ return sell(from, amount, ref); return buy(from, amount, ref); require(false, "invalid token"); return 0; } }
10,330,574
./partial_match/1/0xa1a5143b4044cC3B710FfB8D7130b24a542536f0/sources/lib/forge-std/src/safeconsole.sol
Selector of `log(address,address,address,uint256)`.
function log(address p0, address p1, address p2, uint256 p3) internal pure { bytes32 m0; bytes32 m1; bytes32 m2; bytes32 m3; bytes32 m4; assembly { m0 := mload(0x00) m1 := mload(0x20) m2 := mload(0x40) m3 := mload(0x60) m4 := mload(0x80) mstore(0x00, 0x94250d77) mstore(0x20, p0) mstore(0x40, p1) mstore(0x60, p2) mstore(0x80, p3) } _sendLogPayload(0x1c, 0x84); assembly { mstore(0x00, m0) mstore(0x20, m1) mstore(0x40, m2) mstore(0x60, m3) mstore(0x80, m4) } }
16,052,927
pragma solidity ^0.4.13; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract CATContract is Ownable, Pausable { CATServicePaymentCollector public catPaymentCollector; uint public contractFee = 0.1 * 10**18; // Base fee is 0.1 CAT // Limits all transactions to a small amount to avoid financial risk with early code uint public ethPerTransactionLimit = 0.1 ether; string public contractName; string public versionIdent = "0.1.0"; event ContractDeployed(address indexed byWho); event ContractFeeChanged(uint oldFee, uint newFee); event ContractEthLimitChanged(uint oldLimit, uint newLimit); event CATWithdrawn(uint numOfTokens); modifier blockCatEntryPoint() { // Collect payment catPaymentCollector.collectPayment(msg.sender, contractFee); ContractDeployed(msg.sender); _; } modifier limitTransactionValue() { require(msg.value <= ethPerTransactionLimit); _; } function CATContract(address _catPaymentCollector, string _contractName) { catPaymentCollector = CATServicePaymentCollector(_catPaymentCollector); contractName = _contractName; } // Administrative functions function changeContractFee(uint _newFee) external onlyOwner { // _newFee is assumed to be given in full CAT precision (18 decimals) ContractFeeChanged(contractFee, _newFee); contractFee = _newFee; } function changeEtherTxLimit(uint _newLimit) external onlyOwner { ContractEthLimitChanged(ethPerTransactionLimit, _newLimit); ethPerTransactionLimit = _newLimit; } function withdrawCAT() external onlyOwner { StandardToken CAT = catPaymentCollector.CAT(); uint ourTokens = CAT.balanceOf(this); CAT.transfer(owner, ourTokens); CATWithdrawn(ourTokens); } } contract CATServicePaymentCollector is Ownable { StandardToken public CAT; address public paymentDestination; uint public totalDeployments = 0; mapping(address => bool) public registeredServices; mapping(address => uint) public serviceDeployCount; mapping(address => uint) public userDeployCount; event CATPayment(address indexed service, address indexed payer, uint price); event EnableService(address indexed service); event DisableService(address indexed service); event ChangedPaymentDestination(address indexed oldDestination, address indexed newDestination); event CATWithdrawn(uint numOfTokens); function CATServicePaymentCollector(address _CAT) { CAT = StandardToken(_CAT); paymentDestination = msg.sender; } function enableService(address _service) public onlyOwner { registeredServices[_service] = true; EnableService(_service); } function disableService(address _service) public onlyOwner { registeredServices[_service] = false; DisableService(_service); } function collectPayment(address _fromWho, uint _payment) public { require(registeredServices[msg.sender] == true); serviceDeployCount[msg.sender]++; userDeployCount[_fromWho]++; totalDeployments++; CAT.transferFrom(_fromWho, paymentDestination, _payment); CATPayment(_fromWho, msg.sender, _payment); } // Administrative functions function changePaymentDestination(address _newPaymentDest) external onlyOwner { ChangedPaymentDestination(paymentDestination, _newPaymentDest); paymentDestination = _newPaymentDest; } function withdrawCAT() external onlyOwner { uint ourTokens = CAT.balanceOf(this); CAT.transfer(owner, ourTokens); CATWithdrawn(ourTokens); } } contract SecurityDeposit is CATContract { uint public depositorLimit = 100; uint public instanceId = 1; mapping(uint => SecurityInstance) public instances; event SecurityDepositCreated(uint indexed id, address indexed instOwner, string ownerNote, string depositPurpose, uint depositAmount); event Deposit(uint indexed id, address indexed depositor, uint depositAmount, string note); event DepositClaimed(uint indexed id, address indexed fromWho, uint amountClaimed); event RefundSent(uint indexed id, address indexed toWho, uint amountRefunded); event DepositorLimitChanged(uint oldLimit, uint newLimit); enum DepositorState {None, Active, Claimed, Refunded} struct SecurityInstance { uint instId; address instOwner; string ownerNote; string depositPurpose; uint depositAmount; mapping(address => DepositorState) depositorState; mapping(address => string) depositorNote; address[] depositors; } modifier onlyInstanceOwner(uint _instId) { require(instances[_instId].instOwner == msg.sender); _; } modifier instanceExists(uint _instId) { require(instances[_instId].instId == _instId); _; } // Chain constructor to pass along CAT payment address, and contract name function SecurityDeposit(address _catPaymentCollector) CATContract(_catPaymentCollector, "Security Deposit") {} function createNewSecurityDeposit(string _ownerNote, string _depositPurpose, uint _depositAmount) external blockCatEntryPoint whenNotPaused returns (uint currentId) { // Deposit can&#39;t be greater than maximum allowed for each user require(_depositAmount <= ethPerTransactionLimit); // Cannot have a 0 deposit security deposit require(_depositAmount > 0); currentId = instanceId; address instanceOwner = msg.sender; uint depositAmountETH = _depositAmount; SecurityInstance storage curInst = instances[currentId]; curInst.instId = currentId; curInst.instOwner = instanceOwner; curInst.ownerNote = _ownerNote; curInst.depositPurpose = _depositPurpose; curInst.depositAmount = depositAmountETH; SecurityDepositCreated(currentId, instanceOwner, _ownerNote, _depositPurpose, depositAmountETH); instanceId++; } function deposit(uint _instId, string _note) external payable instanceExists(_instId) limitTransactionValue whenNotPaused { SecurityInstance storage curInst = instances[_instId]; // Must deposit the right amount require(curInst.depositAmount == msg.value); // Cannot have more depositors than the limit require(curInst.depositors.length < depositorLimit); // Cannot double-deposit require(curInst.depositorState[msg.sender] == DepositorState.None); curInst.depositorState[msg.sender] = DepositorState.Active; curInst.depositorNote[msg.sender] = _note; curInst.depositors.push(msg.sender); Deposit(curInst.instId, msg.sender, msg.value, _note); } function claim(uint _instId, address _whoToClaim) public onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused returns (bool) { SecurityInstance storage curInst = instances[_instId]; // Can only call if the state is active if(curInst.depositorState[_whoToClaim] != DepositorState.Active) { return false; } curInst.depositorState[_whoToClaim] = DepositorState.Claimed; curInst.instOwner.transfer(curInst.depositAmount); DepositClaimed(_instId, _whoToClaim, curInst.depositAmount); return true; } function refund(uint _instId, address _whoToRefund) public onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused returns (bool) { SecurityInstance storage curInst = instances[_instId]; // Can only call if state is active if(curInst.depositorState[_whoToRefund] != DepositorState.Active) { return false; } curInst.depositorState[_whoToRefund] = DepositorState.Refunded; _whoToRefund.transfer(curInst.depositAmount); RefundSent(_instId, _whoToRefund, curInst.depositAmount); return true; } function claimFromSeveral(uint _instId, address[] _toClaim) external onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused { for(uint i = 0; i < _toClaim.length; i++) { claim(_instId, _toClaim[i]); } } function refundFromSeveral(uint _instId, address[] _toRefund) external onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused { for(uint i = 0; i < _toRefund.length; i++) { refund(_instId, _toRefund[i]); } } function claimAll(uint _instId) external onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused { SecurityInstance storage curInst = instances[_instId]; for(uint i = 0; i < curInst.depositors.length; i++) { claim(_instId, curInst.depositors[i]); } } function refundAll(uint _instId) external onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused { SecurityInstance storage curInst = instances[_instId]; for(uint i = 0; i < curInst.depositors.length; i++) { refund(_instId, curInst.depositors[i]); } } function changeDepositorLimit(uint _newLimit) external onlyOwner { DepositorLimitChanged(depositorLimit, _newLimit); depositorLimit = _newLimit; } // Information functions function getInstanceMetadata(uint _instId) constant external returns (address instOwner, string ownerNote, string depositPurpose, uint depositAmount) { instOwner = instances[_instId].instOwner; ownerNote = instances[_instId].ownerNote; depositPurpose = instances[_instId].depositPurpose; depositAmount = instances[_instId].depositAmount; } function getAllDepositors(uint _instId) constant external returns (address[]) { return instances[_instId].depositors; } function checkInfo(uint _instId, address _depositor) constant external returns (DepositorState depositorState, string note) { depositorState = instances[_instId].depositorState[_depositor]; note = instances[_instId].depositorNote[_depositor]; } // Metrics function getDepositInstanceCount() constant external returns (uint) { return instanceId - 1; // ID is 1-indexed } }
Can only call if state is active
function refund(uint _instId, address _whoToRefund) public onlyInstanceOwner(_instId) instanceExists(_instId) whenNotPaused returns (bool) { SecurityInstance storage curInst = instances[_instId]; if(curInst.depositorState[_whoToRefund] != DepositorState.Active) { return false; } curInst.depositorState[_whoToRefund] = DepositorState.Refunded; _whoToRefund.transfer(curInst.depositAmount); RefundSent(_instId, _whoToRefund, curInst.depositAmount); return true; }
2,354,943
./full_match/43114/0x364FD64a98bD60aA798Ea8c61bb30d404102E900/sources/contracts/adapters/SynapseAdapter.sol
Mapping indicator which tokens are included in the pool Get nUSD from this pool Get stables from meta pool
function _setPoolTokens() internal { address nUSDAdd = ISynapse(pool).getToken(0); isPoolToken[nUSDAdd] = true; tokenIndex[nUSDAdd] = 0; for (uint8 i=0; true; i++) { try ISynapse(metaPool).getToken(i) returns (address token) { isPoolToken[token] = true; tokenIndex[token] = i + 1; break; } } }
4,524,385
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "LinkTokenInterface.sol"; import "VRFCoordinatorV2Interface.sol"; import "VRFConsumerBaseV2.sol"; import "Ownable.sol"; import "EthUsPriceConversion.sol"; contract MyFundStorage is VRFConsumerBaseV2, Ownable { address payable[] internal payers; EthUsPriceConversion internal ethUsConvert; enum FUNDING_STATE { OPEN, END, CLOSED } FUNDING_STATE internal funding_state; VRFCoordinatorV2Interface COORDINATOR; LinkTokenInterface LINKTOKEN; // VRF subscription ID. // uint64 subscriptionId; uint64 subscriptionId; // The gas lane to use, which specifies the maximum gas price to bump to. bytes32 keyHash; // Minimum Entry Fee to fund uint256 minimumEntreeFee; // Storing each word costs about 20,000 gas, // so 100,000 is a safe default for this example contract. uint32 callbackGasLimit; // The default is 3. uint16 requestConfirmations = 3; // For this example, retrieve 2 random values in one request. // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. uint32 numWords = 2; uint256[] randomWords; uint256 requestId; address s_owner; event ReturnedRandomness_Funding_begin(uint256 requestId); event ReturnedRandomness_Funding_end(uint256 requestId); event ReturnedRandomness_endFunding_begin(uint256 requestId); event ReturnedRandomness_endFunding_end(uint256 requestId); event ReturnedRandomness_withdraw_begin(uint256 requestId); event ReturnedRandomness_withdraw_end(uint256 requestId); event ReturnedRandomness_fulfill_begin(uint256 requestId); event ReturnedRandomness_fulfill_end(uint256 requestId); event ReturnedRandomness_requestRandomWord_begin(uint256 requestId); event ReturnedRandomness_requestRandomWord_end(uint256 requestId); /** * @notice Constructor inherits VRFConsumerBaseV2 * * @param _subscriptionId - the subscription ID that this contract uses for funding requests * @param _vrfCoordinator - coordinator * @param _keyHash - the gas lane to use, which specifies the maximum gas price to bump to */ constructor( address _priceFeedAddress, uint256 _minimumEntreeFee, uint64 _subscriptionId, uint32 _callbackGasLimit, address _vrfCoordinator, address _link, bytes32 _keyHash ) VRFConsumerBaseV2(_vrfCoordinator) payable{ COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); LINKTOKEN = LinkTokenInterface(_link); minimumEntreeFee = _minimumEntreeFee; ethUsConvert = new EthUsPriceConversion(_priceFeedAddress, minimumEntreeFee); keyHash = _keyHash; callbackGasLimit = _callbackGasLimit; s_owner = msg.sender; subscriptionId = _subscriptionId; funding_state = FUNDING_STATE.CLOSED; } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { return ethUsConvert.getETHprice(); } /** * @notice Get the current Ethereum market price in US Dollar */ function getETHpriceUSD() external view returns (uint256) { return ethUsConvert.getETHpriceUSD(); } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { return ethUsConvert.getEntranceFee(); } /** * @notice Update the gas limit for callback function */ function updateCallbackGasLimit(uint32 gasLimit) external onlyOwner { callbackGasLimit = gasLimit; } /** * @notice Update minimum funding amount */ function updateMinimumEntryFee(uint256 min_Entree_Fee) external onlyOwner { minimumEntreeFee = min_Entree_Fee; } /** * @notice Update the funding state */ function updateFundingState(FUNDING_STATE _funding_state) external onlyOwner { funding_state = _funding_state; } /** * @notice Get the Random RequestID from Chainlink */ function getRandomRequestID() external view returns (uint256) { return requestId; } /** * @notice Get the First Random Word Response from Chainlink */ function getFirstRandomWord() external view returns (uint256) { return randomWords[0]; } /** * @notice Get the Second Random Word Response from Chainlink */ function getSecondRandomWord() external view returns (uint256) { return randomWords[1]; } /** * @notice Open the funding account. Users can start funding now. */ function startFunding() external onlyOwner { require( funding_state == FUNDING_STATE.CLOSED, "Can't start a new fund yet! Current funding is not closed yet!" ); funding_state = FUNDING_STATE.OPEN; } /** * @notice User can enter the fund. Minimum $50 value of ETH. */ function fund() external payable { // $50 minimum emit ReturnedRandomness_Funding_begin(requestId); require(funding_state == FUNDING_STATE.OPEN, "Can't fund yet. Funding is not opened yet."); require(msg.value >= ethUsConvert.getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!"); payers.push(payable(msg.sender)); emit ReturnedRandomness_Funding_end(requestId); } /** * @notice Get current funding state. */ function getCurrentFundingState() external view returns (FUNDING_STATE) { return funding_state; } /** * @notice Get the total amount that users funding in this account. */ function getUsersTotalAmount() external view returns (uint256) { return address(this).balance; } /** * @notice Funding is ended. */ function endFunding() external onlyOwner { emit ReturnedRandomness_endFunding_begin(requestId); require(funding_state == FUNDING_STATE.OPEN, "Funding is not opened yet."); funding_state = FUNDING_STATE.END; emit ReturnedRandomness_endFunding_end(requestId); } /** * @notice Owner withdraw the funding. */ function withdraw() external onlyOwner { emit ReturnedRandomness_withdraw_begin(requestId); require( funding_state == FUNDING_STATE.END, "Funding must be ended before withdraw!" ); requestRandomWords(); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness_withdraw_end(requestId); } /** * @notice Owner withdraw the funding. */ function withdraw2() external onlyOwner { emit ReturnedRandomness_withdraw_begin(requestId); require( funding_state == FUNDING_STATE.END, "Funding must be ended before withdraw!" ); payable(s_owner).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness_withdraw_end(requestId); } /** * @notice Requests randomness * Assumes the subscription is funded sufficiently; "Words" refers to unit of data in Computer Science */ function requestRandomWords() internal { // Will revert if subscription is not set and funded. emit ReturnedRandomness_requestRandomWord_begin(requestId); requestId = COORDINATOR.requestRandomWords( keyHash, subscriptionId, requestConfirmations, callbackGasLimit, numWords ); emit ReturnedRandomness_requestRandomWord_end(requestId); } /* * @notice Callback function used by VRF Coordinator * * @param requestId - id of the request * @param randomWords - array of random results from VRF Coordinator */ function fulfillRandomWords( uint256, /* requestId */ uint256[] memory _randomWords ) internal override { emit ReturnedRandomness_fulfill_begin(requestId); randomWords = _randomWords; payable(s_owner).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness_fulfill_end(requestId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Returns the global config that applies to all VRF requests. * @return minimumRequestBlockConfirmations - A minimum number of confirmation * blocks on VRF requests before oracles should respond. * @return fulfillmentFlatFeeLinkPPM - The charge per request on top of the gas fees. * Its flat fee specified in millionths of LINK. * @return maxGasLimit - The maximum gas limit supported for a fulfillRandomWords callback. * @return stalenessSeconds - How long we wait until we consider the ETH/LINK price * (used for converting gas costs to LINK) is stale and use `fallbackWeiPerUnitLink` * @return gasAfterPaymentCalculation - How much gas is used outside of the payment calculation, * i.e. the gas overhead of actually making the payment to oracles. * @return minimumSubscriptionBalance - The minimum subscription balance required to make a request. Its set to be about 300% * of the cost of a single request to handle in ETH/LINK price between request and fulfillment time. * @return fallbackWeiPerUnitLink - fallback ETH/LINK price in the case of a stale feed. */ function getConfig() external view returns ( uint16 minimumRequestBlockConfirmations, uint32 fulfillmentFlatFeeLinkPPM, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, uint96 minimumSubscriptionBalance, int256 fallbackWeiPerUnitLink ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with at least minimumSubscriptionBalance (see getConfig) LINK * before making a request. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [5000, maxGasLimit]. * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns ( uint256 requestId ); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns ( uint64 subId ); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return owner - Owner of the subscription * @return consumers - List of consumer address which are able to use this subscription. */ function getSubscription( uint64 subId ) external view returns ( uint96 balance, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer( uint64 subId, address newOwner ) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer( uint64 subId ) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer( uint64 subId, address consumer ) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer( uint64 subId, address consumer ) external; /** * @notice Withdraw funds from a VRF subscription * @param subId - ID of the subscription * @param to - Where to send the withdrawn LINK to * @param amount - How much to withdraw in juels */ function defundSubscription( uint64 subId, address to, uint96 amount ) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription( uint64 subId, address to ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously. * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2 { error OnlyCoordinatorCanFulfill(address have, address want); address immutable private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ constructor( address _vrfCoordinator ) { vrfCoordinator = _vrfCoordinator; } /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.12; // Get the latest ETH/USD price from chainlink price feed import "AggregatorV3Interface.sol"; contract EthUsPriceConversion { uint256 internal usdEntryFee; AggregatorV3Interface internal ethUsdPriceFeed; constructor( address _priceFeedAddress, uint256 minumum_entry_fee ) { ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress); usdEntryFee = minumum_entry_fee * (10**18); } /** * @notice Get the current Ethereum market price in Wei */ function getETHprice() external view returns (uint256) { (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData(); uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals return adjustedPrice; } /** * @notice Get the current Ethereum market price in US Dollar * 1000000000 */ function getETHpriceUSD() external view returns (uint256) { uint256 ethPrice = this.getETHprice(); uint256 ethAmountInUsd = ethPrice / 1000000000000000000; // the actual ETH/USD conversation rate, after adjusting the extra 0s. return ethAmountInUsd; } /** * @notice Get the minimum funding amount which is $50 */ function getEntranceFee() external view returns (uint256) { uint256 adjustedPrice = this.getETHprice(); // $50, $2,000 / ETH // 50/2,000 // 50 * 100000 / 2000 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice; return costToEnter; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
Callback function used by VRF Coordinator requestId - id of the request randomWords - array of random results from VRF Coordinator/
function fulfillRandomWords( uint256, /* requestId */ uint256[] memory _randomWords ) internal override { emit ReturnedRandomness_fulfill_begin(requestId); randomWords = _randomWords; payable(s_owner).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness_fulfill_end(requestId); }
5,760,003
./full_match/5/0xD677803FbfEdA159E2dC2d0D172DD334490594f8/sources/Based.sol
Prevent overflow when dividing MIN_INT256 by -1 Solidity already throws when dividing by 0.
function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; }
1,943,990
./partial_match/42/0x3b261920Ba47f0C0c6162e592181bbE2244b63AE/sources/SimplePermissionlessArbitrator.sol
IArbitrable Arbitrable interface. When developing arbitrable contracts, we need to: -Define the action taken when a ruling is received by the contract. -Allow dispute creation. For this a function must call arbitrator.createDispute.value(_fee)(_choices,_extraData);/
interface IArbitrable { event Ruling(IArbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); function rule(uint _disputeID, uint _ruling) external; }
8,882,789
pragma solidity ^0.4.24; // Copyright 2017 Zerocoin Electric Coin Company LLC // // 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. import "./ZSLPrecompile.sol"; // @title ZSL Merkle Tree stores note commitments contract ZSLMerkleTree { ZSLPrecompile private zsl; uint private treeDepth; uint private maxNumElements; // Pre-computed empty roots bytes32[] private emptyRoots; // We store map index, i.e. index + 1, as 0 is used identify when a key is not found from the map. uint private numCommitments = 0; mapping (bytes32 => uint) private mapCommitmentIndices; mapping (uint => bytes32) private mapCommitments; // Constructor needs depth of tree constructor(uint depth) public { zsl = ZSLPrecompile(new ZSLPrecompile()); treeDepth = depth; maxNumElements = 2**depth; _createEmptyRoots(depth); } // Return all the empty roots, one empty root for each depth function getEmptyRoots() public constant returns (bytes32[]) { return emptyRoots; } // Return the root for an empty tree of a given depth function getEmptyRoot(uint depth) public constant returns (bytes32) { require(depth < emptyRoots.length); return emptyRoots[depth]; } /** * @notice SHA256Compress two leaves * @param left 32 bytes * @param right 32 bytes * @return result 256-bit hash */ function combine(bytes32 left, bytes32 right) public constant returns (bytes32) { bytes memory buffer = new bytes(64); uint i; for (i=0; i<32; i++) { buffer[i] = left[i]; } for (i=0; i<32; i++) { buffer[i + 32] = right[i]; } return zsl.sha256Compress(buffer); } /** * @notice Get the leaf index of a given commitment if it exists in the tree * @return i The leaf index */ function getLeafIndex(bytes32 cm) public constant returns (uint) { uint mapIndex = mapCommitmentIndices[cm]; require(mapIndex > 0); return mapIndex + 1; } /** * @notice Get commitment at a given leaf index * @param index Leaf index */ function getCommitmentAtLeafIndex(uint index) public constant returns (bytes32) { require(index < numCommitments); uint mapIndex = index + 1; return mapCommitments[mapIndex]; } /** * @notice Add commitment to the tree * @param cm Commitment */ function addCommitment(bytes32 cm) public { // Only allow a commitment to be added once to the tree require(mapCommitmentIndices[cm] == 0); // Is tree full? require(numCommitments < maxNumElements); // Add new commitment uint mapIndex = ++numCommitments; mapCommitmentIndices[cm] = mapIndex; mapCommitments[mapIndex] = cm; } /** * @notice Has commitment already been added to the tree? * @param cm Commitment * @return bool True or false */ function commitmentExists(bytes32 cm) public constant returns (bool) { return mapCommitmentIndices[cm] != 0; } /** * @return root Tree root representing the state of the tree */ function root() public constant returns (bytes32) { return _calcSubtree(0, treeDepth); } /** * @return size Number of commitments stored in the tree */ function size() public constant returns (uint) { return numCommitments; } /** * @return capacity Maxmimum number of commitments that can be stored in the tree */ function capacity() public constant returns (uint) { return maxNumElements; } /** * @return available The number of commitments that can be appended to the tree */ function available() public constant returns (uint) { return maxNumElements - numCommitments; } /** * @return depth The fixed tree depth */ function depth() public constant returns (uint) { return treeDepth; } // Compute the empty tree roots function _createEmptyRoots(uint depth) private { bytes32 root = 0x00; emptyRoots.push(root); for (uint i=0; i < depth-1; i++) { root = combine(root, root); emptyRoots.push(root); } } /** * Recursively calculate the root for a given position in the tree. * @param index Leaf index of item * @param item_depth depth Depth of item * @return root Tree root of the given item */ function _calcSubtree(uint index, uint item_depth) private constant returns (bytes32) { // Use pre-computed empty tree root if we know other half of tree is empty if (numCommitments <= leftShift(index, item_depth)) { return emptyRoots[item_depth]; } if (item_depth == 0) { uint mapIndex = index + 1; return mapCommitments[mapIndex]; } else { bytes32 left = _calcSubtree(leftShift(index, 1), item_depth - 1); bytes32 right = _calcSubtree(leftShift(index, 1) + 1, item_depth - 1); return combine(left, right); } } /** * @notice Get witness information related for a given commitment * @param cm Commitment * @return index The leaf index of the commitment * @return array List of uncles for the commitment * @return tree root to avoid race condition */ function getWitness(bytes32 cm) public constant returns (uint, bytes32[], bytes32) { uint mapIndex = mapCommitmentIndices[cm]; require(mapIndex > 0); uint index = mapIndex - 1; bytes32[] memory uncles = new bytes32[](treeDepth); uint cur_depth = 0; uint cur_index = index; uint i = 0; while (cur_depth < treeDepth) { uncles[i++] = _calcSubtree( cur_index ^ 1, cur_depth++); cur_index = rightShift(cur_index, 1); } return (index, uncles, root()); } // Fallback function for unknown function signature to prevent accidental sending of ether function () public { revert(); } function leftShift(uint256 v, uint256 n) pure public returns (uint256) { return v * (2 ** n); } function rightShift(uint256 v, uint256 n) pure public returns (uint256) { return v / (2 ** n); } }
Return the root for an empty tree of a given depth
function getEmptyRoot(uint depth) public constant returns (bytes32) { require(depth < emptyRoots.length); return emptyRoots[depth]; }
12,771,147
./full_match/1/0xbD53415F6135019386f9e64b6811c4728A43655B/sources/contracts/project/kometh/rexroar/RexRoarIssue1.sol
@inheritdoc IKomethAppImplementation/
function delegateMint( uint256 _quantity, uint256 _txLimit, uint256 _walletLimit, uint256 _deadline, address _recipient, uint256 _kind, bytes calldata _signature ) external payable notContract nonReentrant { require(stage == Stage.Private || stage == Stage.Mint, "STAGE_NMATCH"); uint256 privateSalePrice = privateSalePrices[_kind]; require( signer == _verifyPrivateSale( privateSalePrice, _txLimit, _walletLimit, _deadline, _recipient, _kind, _signature ), "INVALID_SIGNATURE" ); require(block.timestamp <= _deadline, "INVALID_DEADLINE_SIGNATURE"); require(_quantity <= _txLimit, "TX_LIMIT_EXCEEDED"); require( PrivateSaleMinter[_kind][_recipient] + _quantity <= _walletLimit, "WALLET_LIMIT_EXCEEDED" ); require( msg.value >= (privateSalePrice * _quantity), "INSUFFICIENT_FUND" ); PrivateSaleMinter[_kind][_recipient] += _quantity; _mint(_recipient, _quantity); emit PrivateSaleMint(_recipient, _kind); }
16,544,835
/** *Submitted for verification at Etherscan.io on 2021-12-18 */ pragma solidity 0.6.12; // SPDX-License-Identifier: Unlicensed library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * 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); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require(_previousOwner == msg.sender, "You don't have permission to unlock"); require(now > _lockTime , "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } 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; } contract Digifit is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned;// with reward mapping (address => uint256) private _tOwned; // without reward mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isIncludedInFee; mapping (address => bool) private _isExcluded; //from reward address[] private _excluded; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 700000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //marketing wallet address public marketingWallet; //switches bool public marketingwalletenabled = true; bool public liquidityenabled = true; bool public burnenabled = true; bool public rewardenabled = true; uint256 public marketingwalletpercent = 2; //2% uint256 public burnpercent = 1; //1% uint256 public rewardpercent = 1; //1% uint256 public prevmarketingwalletpercent= marketingwalletpercent; uint256 public prevburnpercent = burnpercent; uint256 public prevrewardpercent = rewardpercent; string private _name = "DIGIFIT"; string private _symbol = "DGI"; uint8 private _decimals = 9; uint256 public _liquidityFee = 1; uint256 private _previousLiquidityFee = _liquidityFee; //1% event Switchburn(bool enabled, uint256 value); event Switchesupdated(bool markenabled, uint256 markvalue,bool burnenabled, uint256 burnvalue,bool rewardenabled, uint256 rewardvalue); event Switchwallet(bool enabled, uint256 value); event UpdatedMarketingwallet(address wallet); event excludedFromFee(address wallet); event includedInFee(address wallet); event excluded(address wallet); event included(address wallet); event burned(address account,uint256 amount); IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 private numTokensSellToAddToLiquidity = 700000000 * 10**9; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor (address _marketingwallet) public { require(_marketingwallet != address(0)); _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; marketingWallet = _marketingwallet; 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 burn(uint256 amount) external returns (bool) { _burn(_msgSender(), amount); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) external { 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 deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function excludeFromFee(address account) public onlyOwner { _isIncludedInFee[account] = false; } function includeInFee(address account) public onlyOwner { _isIncludedInFee[account] = true; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setLiqiditySaleTokenNumber(uint256 limit) external onlyOwner() { numTokensSellToAddToLiquidity = limit; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**2 ); } function isIncludedInFee(address account) public view returns(bool) { return _isIncludedInFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = false; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isIncludedInFee[from] || _isIncludedInFee[to]){ takeFee = true; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function burningTransfer(uint256 tAmount) private { uint256 tBurn; (tBurn) = _getBurnValues(tAmount); uint256 rbamount = tBurn.mul(_getRate()); _tTotal = _tTotal.sub(tBurn); _rTotal = _rTotal.sub(rbamount); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); require(balanceOf(account) >= amount, "ERC20: burn amount exceeds balance"); uint256 rbamount=amount.mul(_getRate()); _tTotal = _tTotal.sub(amount); _rTotal = _rTotal.sub(rbamount); _rOwned[account] = _rOwned[account].sub(rbamount); if(_isExcluded[account]) { _tOwned[account] = _tOwned[account].sub(amount); } emit burned(account,amount); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 rwalletfee = 0; if(marketingwalletenabled) { (rwalletfee) = _getWalletValues(tAmount); _rOwned[marketingWallet] = _rOwned[marketingWallet].add(rwalletfee); } if(burnenabled) { burningTransfer(tAmount); } _takeLiquidity(tLiquidity); _reflectFee(rFee.sub(rwalletfee), tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 rwalletfee = 0; if(marketingwalletenabled) { (rwalletfee) = _getWalletValues(tAmount); _rOwned[marketingWallet] = _rOwned[marketingWallet].add(rwalletfee); } if(burnenabled) { burningTransfer(tAmount); } _takeLiquidity(tLiquidity); _reflectFee(rFee.sub(rwalletfee), tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 rwalletfee = 0; if(marketingwalletenabled) { (rwalletfee) = _getWalletValues(tAmount); _rOwned[marketingWallet] = _rOwned[marketingWallet].add(rwalletfee); } if(burnenabled) { burningTransfer(tAmount); } _takeLiquidity(tLiquidity); _reflectFee(rFee.sub(rwalletfee), tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); uint256 rwalletfee = 0; if(marketingwalletenabled) { (rwalletfee) = _getWalletValues(tAmount); _rOwned[marketingWallet] = _rOwned[marketingWallet].add(rwalletfee); } if(burnenabled) { burningTransfer(tAmount); } _takeLiquidity(tLiquidity); _reflectFee(rFee.sub(rwalletfee), tFee); emit Transfer(sender, recipient, tTransferAmount); } function _getWalletValues(uint256 tAmount) private view returns ( uint256) { uint256 currentRate = _getRate(); //wallet amount uint256 twalletfee = tAmount.div(100).mul(marketingwalletpercent); uint256 rwalletfee= twalletfee.mul(currentRate); return (rwalletfee); } function _getBurnValues(uint256 tAmount) private view returns (uint256) { //burn amount uint256 tBurn = tAmount.div(100).mul(burnpercent); return (tBurn); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 totaltax = _getTotalTax(); uint256 tFee = tAmount.div(100).mul(totaltax); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function updateSwitches(bool _marketingwalletenabled,uint256 markvalue,bool _burnenabled,uint256 burnvalue,bool _rewardholderenabled,uint256 _rewardvalue) external onlyOwner { require(burnvalue <= 100 && _rewardvalue <= 100 && markvalue<=100 , "TaxFee exceed 100"); rewardenabled = _rewardholderenabled; rewardpercent = _rewardvalue; burnenabled = _burnenabled; burnpercent = burnvalue; marketingwalletenabled = _marketingwalletenabled; marketingwalletpercent = markvalue; emit Switchesupdated(marketingwalletenabled,marketingwalletpercent,burnenabled,burnpercent,rewardenabled,rewardpercent); } function updateMarketingWallet(address _marketingwallet) external onlyOwner { require(_marketingwallet != address(0), "new marketing Wallet is the zero address"); marketingWallet = _marketingwallet; emit UpdatedMarketingwallet(_marketingwallet); } function _getTotalTax() private view returns(uint256) { uint256 totaltax = rewardpercent; if(burnenabled) totaltax += burnpercent; if(marketingwalletenabled) totaltax += marketingwalletpercent; return (totaltax); } function removeAllFee() private { if(marketingwalletpercent==0 && _liquidityFee==0 && burnpercent==0 && rewardpercent==0 ) return; prevmarketingwalletpercent = marketingwalletpercent; _previousLiquidityFee = _liquidityFee; prevburnpercent = burnpercent; prevrewardpercent = rewardpercent; marketingwalletpercent = 0; _liquidityFee = 0; burnpercent = 0; rewardpercent = 0; } function restoreAllFee() private { marketingwalletpercent = prevmarketingwalletpercent; // _liquidityFee = _previousLiquidityFee; burnpercent = prevburnpercent; rewardpercent = prevrewardpercent; // holders } // Exclusion Module function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already 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 reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } }
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; }
515,484
pragma solidity 0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface Token { function transfer(address _to, uint256 _amount)external returns (bool success); function balanceOf(address _owner) external returns (uint256 balance); function decimals()external view returns (uint8); } /** * @title Vault * @dev This contract is used for storing funds while a crowdsale * is in progress. Funds will be transferred to owner on adhoc requests */ contract Vault is Ownable { using SafeMath for uint256; mapping (address => uint256) public deposited; address public wallet; event Withdrawn(address _wallet); function Vault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; } function deposit(address investor) public onlyOwner payable{ deposited[investor] = deposited[investor].add(msg.value); } function withdrawToWallet() public onlyOwner { wallet.transfer(this.balance); emit Withdrawn(wallet); } } contract CLXTokenSale is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //rate of token in ether 1ETH = 8000 CLX uint256 public rate = 8000; /* *There will be 2 phases * 1. Pre-sale * 2. ICO Phase 1 */ struct PhaseInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint8 bonusPercentages; uint256 minEtherContribution; uint256 weiRaised; } //info of each phase PhaseInfo[] public phases; //Total funding uint256 public totalFunding; //total tokens available for sale considering 8 decimal places uint256 tokensAvailableForSale = 17700000000000000; uint8 public noOfPhases; //Keep track of whether contract is up or not bool public contractUp; //Keep track of whether the sale has ended or not bool public saleEnded; //Keep track of emergency stop bool public ifEmergencyStop ; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger Sale restart event SaleRestarted(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finished(address _owner, uint256 time); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //modifiers modifier _contractUp(){ require(contractUp); _; } modifier nonZeroAddress(address _to) { require(_to != address(0)); _; } modifier _saleEnded() { require(saleEnded); _; } modifier _saleNotEnded() { require(!saleEnded); _; } modifier _ifNotEmergencyStop() { require(!ifEmergencyStop); _; } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { // Contract should not be powered up previously require(!contractUp); // Contract should have enough CLX credits require(token.balanceOf(this) >= tokensAvailableForSale); //activate the sale process contractUp = true; } //for Emergency stop of the sale function emergencyStop() external onlyOwner _contractUp _ifNotEmergencyStop { ifEmergencyStop = true; emit SaleStopped(msg.sender, now); } //to restart the sale after emergency stop function emergencyRestart() external onlyOwner _contractUp { require(ifEmergencyStop); ifEmergencyStop = false; emit SaleRestarted(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { return (phases[noOfPhases-1].endTime != 0); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfPhases The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3 and 4 . * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfPhases, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps ,uint256[] _minEtherContribution, uint8[2] _bonusPercentages)private { require(_noOfPhases == 2); //Each array should contain info about each tier require(_startTimes.length == 2); require(_endTimes.length == _noOfPhases); require(_hardCaps.length == _noOfPhases); require(_bonusPercentages.length == _noOfPhases); noOfPhases = _noOfPhases; for(uint8 i = 0; i < _noOfPhases; i++){ require(_hardCaps[i] > 0); if(i>0){ phases.push(PhaseInfo({ hardcap:_hardCaps[i], startTime:_startTimes[i], endTime:_endTimes[i], minEtherContribution : _minEtherContribution[i], bonusPercentages:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i] > now); phases.push(PhaseInfo({ hardcap:_hardCaps[i], startTime:_startTimes[i], minEtherContribution : _minEtherContribution[i], endTime:_endTimes[i], bonusPercentages:_bonusPercentages[i], weiRaised:0 })); } } } /** * @dev Constructor method * @param _tokenToBeUsed Address of the token to be used for Sales * @param _wallet Address of the wallet which will receive the collected funds */ function CLXTokenSale(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); uint256[] memory startTimes = new uint256[](2); uint256[] memory endTimes = new uint256[](2); uint256[] memory hardCaps = new uint256[](2); uint256[] memory minEtherContribution = new uint256[](2); uint8[2] memory bonusPercentages; //pre-sales startTimes[0] = 1525910400; //MAY 10, 2018 00:00 AM GMT endTimes[0] = 0; //NO END TIME INITIALLY hardCaps[0] = 7500 ether; minEtherContribution[0] = 0.3 ether; bonusPercentages[0] = 20; //phase-1: Public Sale startTimes[1] = 0; //NO START TIME INITIALLY endTimes[1] = 0; //NO END TIME INITIALLY hardCaps[1] = 12500 ether; minEtherContribution[1] = 0.1 ether; bonusPercentages[1] = 5; setTiersInfo(2, startTimes, endTimes, hardCaps, minEtherContribution, bonusPercentages); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } function startNextPhase() public onlyOwner _saleNotEnded _contractUp _ifNotEmergencyStop returns(bool){ int8 currentPhaseIndex = getCurrentlyRunningPhase(); require(currentPhaseIndex == 0); PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)]; uint256 tokensLeft; uint256 tokensInPreICO = 7200000000000000; //considering 8 decimal places //Checking if tokens are left after the Pre ICO sale, if left, transfer all to the owner if(currentlyRunningPhase.weiRaised <= 7500 ether) { tokensLeft = tokensInPreICO.sub(currentlyRunningPhase.weiRaised.mul(9600).div(10000000000)); token.transfer(msg.sender, tokensLeft); } phases[0].endTime = now; phases[1].startTime = now; return true; } /** * @dev Must be called to end the sale, to do some extra finalization * work. It finishes the sale, sends the unsold tokens to the owner's address * IMP : Call withdrawFunds() before finishing the sale */ function finishSale() public onlyOwner _contractUp _saleNotEnded returns (bool){ int8 currentPhaseIndex = getCurrentlyRunningPhase(); require(currentPhaseIndex == 1); PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)]; uint256 tokensLeft; uint256 tokensInPublicSale = 10500000000000000; //considering 8 decimal places //Checking if tokens are left after the Public sale, if left, transfer all to the owner if(currentlyRunningPhase.weiRaised <= 12500 ether) { tokensLeft = tokensInPublicSale.sub(currentlyRunningPhase.weiRaised.mul(8400).div(10000000000)); token.transfer(msg.sender, tokensLeft); } //End the sale saleEnded = true; //Set the endTime of Public Sale phases[noOfPhases-1].endTime = now; emit Finished(msg.sender, now); return true; } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _contractUp _saleNotEnded _ifNotEmergencyStop nonZeroAddress(beneficiary) payable returns(bool){ int8 currentPhaseIndex = getCurrentlyRunningPhase(); assert(currentPhaseIndex >= 0); // recheck this for storage and memory PhaseInfo storage currentlyRunningPhase = phases[uint256(currentPhaseIndex)]; uint256 weiAmount = msg.value; //Check hard cap for this phase has not been reached require(weiAmount.add(currentlyRunningPhase.weiRaised) <= currentlyRunningPhase.hardcap); //check the minimum ether contribution require(weiAmount >= currentlyRunningPhase.minEtherContribution); uint256 tokens = weiAmount.mul(rate).div(10000000000);//considering decimal places to be 8 for token uint256 bonusedTokens = applyBonus(tokens, currentlyRunningPhase.bonusPercentages); totalFunding = totalFunding.add(weiAmount); currentlyRunningPhase.weiRaised = currentlyRunningPhase.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); return true; } /** *@dev Method to calculate bonus for the user as per currently running phase and contribution by the user * @param tokens Total tokens purchased by the user * @param percentage Array of bonus percentages for the phase */ function applyBonus(uint256 tokens, uint8 percentage) private pure returns (uint256) { uint256 tokensToAdd = 0; tokensToAdd = tokens.mul(percentage).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningPhase()public view returns(int8){ for(uint8 i=0;i<noOfPhases;i++){ if(phases[i].startTime!=0 && now>=phases[i].startTime && phases[i].endTime == 0){ return int8(i); } } return -1; } /** * @dev Get funding info of user/address. * It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } /** * @dev Allow owner to withdraw funds to his wallet anytime in between the sale process */ function withDrawFunds()public onlyOwner _saleNotEnded _contractUp { vault.withdrawToWallet(); } }
Constructor method _tokenToBeUsed Address of the token to be used for Sales _wallet Address of the wallet which will receive the collected funds/pre-salesphase-1: Public Sale
function CLXTokenSale(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); uint256[] memory startTimes = new uint256[](2); uint256[] memory endTimes = new uint256[](2); uint256[] memory hardCaps = new uint256[](2); uint256[] memory minEtherContribution = new uint256[](2); uint8[2] memory bonusPercentages; hardCaps[0] = 7500 ether; minEtherContribution[0] = 0.3 ether; bonusPercentages[0] = 20; hardCaps[1] = 12500 ether; minEtherContribution[1] = 0.1 ether; bonusPercentages[1] = 5; setTiersInfo(2, startTimes, endTimes, hardCaps, minEtherContribution, bonusPercentages); }
411,161
pragma solidity ^0.4.18; /// @title SafeMath contract - math operations with safety checks contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /// @title Ownable contract - base contract with an owner contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /// @title Killable contract - base contract that can be killed by owner. All funds in contract will be sent to the owner. contract Killable is Ownable { function kill() public onlyOwner { selfdestruct(owner); } } /// @title ERC20 interface see https://github.com/ethereum/EIPs/issues/20 contract ERC20 { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); function decimals() public constant returns (uint value); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /// @title SilentNotaryToken contract - standard ERC20 token with Short Hand Attack and approve() race condition mitigation. contract SilentNotaryToken is SafeMath, ERC20, Killable { string constant public name = "Silent Notary Token"; string constant public symbol = "SNTR"; /// Holder list address[] public holders; /// Balance data struct Balance { /// Tokens amount uint value; /// Object exist bool exist; } /// Holder balances mapping(address => Balance) public balances; /// Contract that is allowed to create new tokens and allows unlift the transfer limits on this token address public crowdsaleAgent; /// A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period. bool public released = false; /// approve() allowances mapping (address => mapping (address => uint)) allowed; /// @dev Limit token transfer until the crowdsale is over. modifier canTransfer() { if(!released) require(msg.sender == crowdsaleAgent); _; } /// @dev The function can be called only before or after the tokens have been releasesd /// @param _released token transfer and mint state modifier inReleaseState(bool _released) { require(_released == released); _; } /// @dev If holder does not exist add to array /// @param holder Token holder modifier addIfNotExist(address holder) { if(!balances[holder].exist) holders.push(holder); _; } /// @dev The function can be called only by release agent. modifier onlyCrowdsaleAgent() { require(msg.sender == crowdsaleAgent); _; } /// @dev Fix for the ERC20 short address attack http://vessenes.com/the-erc20-short-address-attack-explained/ /// @param size payload size modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } /// @dev Make sure we are not done yet. modifier canMint() { require(!released); _; } /// @dev Constructor function SilentNotaryToken() public { } /// Fallback method function() payable public { revert(); } function decimals() public constant returns (uint value) { return 4; } /// @dev Create new tokens and allocate them to an address. Only callably by a crowdsale contract /// @param receiver Address of receiver /// @param amount Number of tokens to issue. function mint(address receiver, uint amount) onlyCrowdsaleAgent canMint addIfNotExist(receiver) public { totalSupply = safeAdd(totalSupply, amount); balances[receiver].value = safeAdd(balances[receiver].value, amount); balances[receiver].exist = true; Transfer(0, receiver, amount); } /// @dev Set the contract that can call release and make the token transferable. /// @param _crowdsaleAgent crowdsale contract address function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner inReleaseState(false) public { crowdsaleAgent = _crowdsaleAgent; } /// @dev One way function to release the tokens to the wild. Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). function releaseTokenTransfer() public onlyCrowdsaleAgent { released = true; } /// @dev Tranfer tokens to address /// @param _to dest address /// @param _value tokens amount /// @return transfer result function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer addIfNotExist(_to) public returns (bool success) { balances[msg.sender].value = safeSub(balances[msg.sender].value, _value); balances[_to].value = safeAdd(balances[_to].value, _value); balances[_to].exist = true; Transfer(msg.sender, _to, _value); return true; } /// @dev Tranfer tokens from one address to other /// @param _from source address /// @param _to dest address /// @param _value tokens amount /// @return transfer result function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer addIfNotExist(_to) public returns (bool success) { var _allowance = allowed[_from][msg.sender]; balances[_to].value = safeAdd(balances[_to].value, _value); balances[_from].value = safeSub(balances[_from].value, _value); balances[_to].exist = true; allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } /// @dev Tokens balance /// @param _owner holder address /// @return balance amount function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner].value; } /// @dev Approve transfer /// @param _spender holder address /// @param _value tokens amount /// @return result function approve(address _spender, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require ((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Token allowance /// @param _owner holder address /// @param _spender spender address /// @return remain amount function allowance(address _owner, address _spender) constant public returns (uint remaining) { return allowed[_owner][_spender]; } }
Set the contract that can call release and make the token transferable. _crowdsaleAgent crowdsale contract address
function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner inReleaseState(false) public { crowdsaleAgent = _crowdsaleAgent; }
941,373
pragma solidity ^0.4.13; contract EthicHubStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; /*** Modifiers ************/ /// @dev Only allow access from the latest version of a contract in the Rocket Pool network after deployment modifier onlyEthicHubContracts() { // Maje sure the access is permitted to only contracts in our Dapp require(addressStorage[keccak256("contract.address", msg.sender)] != 0x0); _; } constructor() public { addressStorage[keccak256("contract.address", msg.sender)] = msg.sender; } /**** Get 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 getUint(bytes32 _key) external view returns (uint) { return uintStorage[_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 getBytes(bytes32 _key) external view returns (bytes) { return bytesStorage[_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 getInt(bytes32 _key) external view returns (int) { return intStorage[_key]; } /**** Set Methods ***********/ /// @param _key The key for the record function setAddress(bytes32 _key, address _value) onlyEthicHubContracts external { addressStorage[_key] = _value; } /// @param _key The key for the record function setUint(bytes32 _key, uint _value) onlyEthicHubContracts external { uintStorage[_key] = _value; } /// @param _key The key for the record function setString(bytes32 _key, string _value) onlyEthicHubContracts external { stringStorage[_key] = _value; } /// @param _key The key for the record function setBytes(bytes32 _key, bytes _value) onlyEthicHubContracts external { bytesStorage[_key] = _value; } /// @param _key The key for the record function setBool(bytes32 _key, bool _value) onlyEthicHubContracts external { boolStorage[_key] = _value; } /// @param _key The key for the record function setInt(bytes32 _key, int _value) onlyEthicHubContracts external { intStorage[_key] = _value; } /**** Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) onlyEthicHubContracts external { delete addressStorage[_key]; } /// @param _key The key for the record function deleteUint(bytes32 _key) onlyEthicHubContracts external { delete uintStorage[_key]; } /// @param _key The key for the record function deleteString(bytes32 _key) onlyEthicHubContracts external { delete stringStorage[_key]; } /// @param _key The key for the record function deleteBytes(bytes32 _key) onlyEthicHubContracts external { delete bytesStorage[_key]; } /// @param _key The key for the record function deleteBool(bytes32 _key) onlyEthicHubContracts external { delete boolStorage[_key]; } /// @param _key The key for the record function deleteInt(bytes32 _key) onlyEthicHubContracts external { delete intStorage[_key]; } }
_key The key for the record
function setUint(bytes32 _key, uint _value) onlyEthicHubContracts external { uintStorage[_key] = _value; }
881,461
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import 'openzeppelin-solidity/contracts/access/Ownable.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/IERC20.sol'; import 'openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol'; contract TokenVault is Ownable { using SafeERC20 for IERC20; constructor () { } /** * @dev Sends tokens to specified address * @param _token address of the token being transferred * @param _to address where tokens will be sent * @param _amount amount of tokens to send */ function sendTokens(IERC20 _token, address _to, uint _amount) public onlyOwner { _token.safeTransfer(_to, _amount); } /** * @dev Sends Ether to specified address * @param _to address where Ether will be sent * @param _amount amount of Ether to send in wei */ function sendEther(address _to, uint _amount) public payable onlyOwner { require(_to != address(0), "Incorrect address"); (bool sent, ) = _to.call{value: _amount}(""); require(sent, "Failed to send Ether"); } /** * @dev Returns Ether balance of this contract */ function getBalance() public view returns (uint) { return address(this).balance; } receive() external payable {} fallback() external payable {} }
Sends tokens to specified address _token address of the token being transferred _to address where tokens will be sent _amount amount of tokens to send/
function sendTokens(IERC20 _token, address _to, uint _amount) public onlyOwner { _token.safeTransfer(_to, _amount); }
892,801
./full_match/5/0xD88d26086688EcaC0aF0E7E81cf3A15D5563057a/sources/browser/Math.sol
Total earned ETH/
function getTotalEarnedEther() public view returns (uint) { uint totalEth; for (uint i = 1; i <= currentId; i++) { totalEth = totalEth.add(users[userList[i]].totalEarningEth); } return totalEth; }
1,936,729
./partial_match/1/0x32d94d714F0F69Aca4f09bA6Ae49993DD8fA63C5/sources/PeeriumToken.sol
Transfers tokens from the caller to the recipient. _to The recipient address. _value The amount of tokens to transfer. return A boolean indicating whether the transfer was successful or not./
function transfer(address _to, uint256 _value) external override returns (bool) { require(_to != address(0), "Invalid recipient"); require(_value <= balanceOf[msg.sender], "Insufficient balance"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; }
2,665,108
./full_match/1/0x333545b0A1fc0675c8022Aa5685beBA31B1d62e9/sources/t2.sol
returning residue in token0, if any returning residue in token1, if any
function _sushiDeposit( address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 token0Bought, uint256 token1Bought ) internal returns (uint256) { IERC20(_ToUnipoolToken0).approve(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken1).approve(address(sushiSwapRouter), 0); IERC20(_ToUnipoolToken0).approve( address(sushiSwapRouter), token0Bought ); IERC20(_ToUnipoolToken1).approve( address(sushiSwapRouter), token1Bought ); (uint256 amountA, uint256 amountB, uint256 LP) = sushiSwapRouter .addLiquidity( _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought, 1, 1, address(this), deadline ); if (token0Bought.sub(amountA) > 0) { IERC20(_ToUnipoolToken0).safeTransfer( msg.sender, token0Bought.sub(amountA) ); } if (token1Bought.sub(amountB) > 0) { IERC20(_ToUnipoolToken1).safeTransfer( msg.sender, token1Bought.sub(amountB) ); } return LP; }
4,858,155
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/introspection/ERC165.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/EnumerableMap.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./interface/IERC721Metadata.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping(address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./ERC721.sol"; import "./interface/ILife.sol"; /** * @title NFTKEY Life collection contract */ contract Life is ILife, ERC721, Ownable, ReentrancyGuard { using SafeMath for uint256; using Address for address; constructor(string memory name_, string memory symbol_) public ERC721(name_, symbol_) {} uint256 public constant SALE_START_TIMESTAMP = 1616247000; uint256 public constant MAX_NFT_SUPPLY = 10000; mapping(address => uint256) private _pendingWithdrawals; mapping(uint256 => uint8[]) private _bioDNAById; mapping(bytes32 => bool) private _bioExistanceByHash; uint8 private _feeFraction = 1; uint8 private _feeBase = 100; mapping(uint256 => Listing) private _bioListedForSale; mapping(uint256 => Bid) private _bioWithBids; /** * @dev See {ILife-getBioDNA}. */ function getBioDNA(uint256 bioId) external view override returns (uint8[] memory) { return _bioDNAById[bioId]; } /** * @dev See {ILife-allBioDNAs}. */ function getBioDNAs(uint256 from, uint256 size) external view override returns (uint8[][] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many Bios"); uint8[][] memory bios = new uint8[][](size); for (uint256 i; i < size; i++) { bios[i] = _bioDNAById[i + from]; } return bios; } /** * @dev See {ILife-getBioPrice}. */ function getBioPrice() public view override returns (uint256) { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); uint256 currentSupply = totalSupply(); if (currentSupply > 9900) { return 100000000000000000000; // 9901 - 10000 100 BNB } else if (currentSupply > 9500) { return 20000000000000000000; // 9501 - 9900 20 BNB } else if (currentSupply > 8500) { return 10000000000000000000; // 8501 - 9500 10 BNB } else if (currentSupply > 4500) { return 8000000000000000000; // 4501 - 8500 8 BNB } else if (currentSupply > 2500) { return 6000000000000000000; // 2501 - 4500 6 BNB } else if (currentSupply > 1000) { return 4000000000000000000; // 1001 - 2500 4 BNB } else if (currentSupply > 100) { return 2000000000000000000; // 101 - 1000 2 BNB } else { return 1000000000000000000; // 0 - 100 1 BNB } } /** * @dev See {ILife-isBioExist}. */ function isBioExist(uint8[] memory bioDNA) external view override returns (bool) { bytes32 bioHashOriginal = keccak256(abi.encodePacked(bioDNA)); return _bioExistanceByHash[bioHashOriginal]; } /** * @dev See {ILife-mintBio}. */ function mintBio(uint8[] memory bioDNA) external payable override { // Bio RLE require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended"); require(totalSupply().add(1) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY"); require(getBioPrice() == msg.value, "Ether value sent is not correct"); bytes32 bioHash = keccak256(abi.encodePacked(bioDNA)); require(!_bioExistanceByHash[bioHash], "Bio already existed"); uint256 activeCellCount = 0; uint256 totalCellCount = 0; for (uint8 i = 0; i < bioDNA.length; i++) { totalCellCount = totalCellCount.add(bioDNA[i]); if (i % 2 == 1) { activeCellCount = activeCellCount.add(bioDNA[i]); } } require(totalCellCount <= 289, "Total cell count should be smaller than 289"); require( activeCellCount >= 5 && activeCellCount <= 48, "Active cell count of Bio is not allowed" ); uint256 mintIndex = totalSupply(); _bioExistanceByHash[bioHash] = true; _bioDNAById[mintIndex] = bioDNA; _safeMint(msg.sender, mintIndex); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(msg.value); emit BioMinted(mintIndex, msg.sender, bioDNA, bioHash); } modifier saleEnded() { require(totalSupply() >= MAX_NFT_SUPPLY, "Bio sale still going"); _; } modifier bioExist(uint256 bioId) { require(bioId < totalSupply(), "Bio doesn't exist"); _; } modifier isBioOwner(uint256 bioId) { require(ownerOf(bioId) == msg.sender, "Not the owner of this Bio"); _; } /** * @dev See {ILife-getBioListing}. */ function getBioListing(uint256 bioId) external view override returns (Listing memory) { return _bioListedForSale[bioId]; } /** * @dev See {ILife-getListings}. */ function getBioListings(uint256 from, uint256 size) external view override returns (Listing[] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many listings"); Listing[] memory listings = new Listing[](size); for (uint256 i; i < size; i++) { listings[i] = _bioListedForSale[i + from]; } return listings; } /** * @dev See {ILife-getBioBid}. */ function getBioBid(uint256 bioId) external view override returns (Bid memory) { return _bioWithBids[bioId]; } /** * @dev See {ILife-getBioBids}. */ function getBioBids(uint256 from, uint256 size) external view override returns (Bid[] memory) { uint256 endBioIndex = from + size; require(endBioIndex <= totalSupply(), "Requesting too many bids"); Bid[] memory bids = new Bid[](size); for (uint256 i; i < totalSupply(); i++) { bids[i] = _bioWithBids[i + from]; } return bids; } /** * @dev See {ILife-listBioForSale}. */ function listBioForSale(uint256 bioId, uint256 minValue) external override saleEnded bioExist(bioId) isBioOwner(bioId) { _bioListedForSale[bioId] = Listing( true, bioId, msg.sender, minValue, address(0), block.timestamp ); emit BioListed(bioId, minValue, msg.sender, address(0)); } /** * @dev See {ILife-listBioForSaleToAddress}. */ function listBioForSaleToAddress( uint256 bioId, uint256 minValue, address toAddress ) external override saleEnded bioExist(bioId) isBioOwner(bioId) { _bioListedForSale[bioId] = Listing( true, bioId, msg.sender, minValue, toAddress, block.timestamp ); emit BioListed(bioId, minValue, msg.sender, toAddress); } function _delistBio(uint256 bioId) private saleEnded bioExist(bioId) { emit BioDelisted(bioId, _bioListedForSale[bioId].seller); delete _bioListedForSale[bioId]; } function _removeBid(uint256 bioId) private saleEnded bioExist(bioId) { emit BioBidRemoved(bioId, _bioWithBids[bioId].bidder); delete _bioWithBids[bioId]; } /** * @dev See {ILife-delistBio}. */ function delistBio(uint256 bioId) external override isBioOwner(bioId) { require(_bioListedForSale[bioId].isForSale, "Bio is not for sale"); _delistBio(bioId); } /** * @dev Return fund if it's not a contract, else add it to pending withdrawals * @param receiver Address to receive value * @param value value to send */ function _sendValue(address receiver, uint256 value) private { if (receiver.isContract() && receiver != msg.sender) { _pendingWithdrawals[receiver] = value; } else { Address.sendValue(payable(receiver), value); } } /** * @dev See {ILife-buyBio}. */ function buyBio(uint256 bioId) external payable override saleEnded bioExist(bioId) nonReentrant { Listing memory listing = _bioListedForSale[bioId]; require(listing.isForSale, "Bio is not for sale"); require( listing.onlySellTo == address(0) || listing.onlySellTo == msg.sender, "Bio is not selling to this address" ); require(ownerOf(bioId) == listing.seller, "This seller is not the owner"); require(msg.sender != ownerOf(bioId), "This Bio belongs to this address"); uint256 fees = listing.minValue.mul(_feeFraction).div(_feeBase); require( msg.value >= listing.minValue + fees, "The value send is below sale price plus fees" ); uint256 valueWithoutFees = msg.value.sub(fees); _sendValue(ownerOf(bioId), valueWithoutFees); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(fees); emit BioBought(bioId, valueWithoutFees, listing.seller, msg.sender); _safeTransfer(ownerOf(bioId), msg.sender, bioId, ""); _delistBio(bioId); Bid memory existingBid = _bioWithBids[bioId]; if (existingBid.bidder == msg.sender) { _sendValue(msg.sender, existingBid.value); _removeBid(bioId); } } /** * @dev See {ILife-enterBidForBio}. */ function enterBidForBio(uint256 bioId) external payable override saleEnded bioExist(bioId) nonReentrant { require(ownerOf(bioId) != address(0), "This Bio has been burnt"); require(ownerOf(bioId) != msg.sender, "Owner of Bio doesn't need to bid"); require(msg.value != 0, "The bid price is too low"); Bid memory existingBid = _bioWithBids[bioId]; require(msg.value > existingBid.value, "The bid price is no higher than existing one"); if (existingBid.value > 0) { _sendValue(existingBid.bidder, existingBid.value); } _bioWithBids[bioId] = Bid(true, bioId, msg.sender, msg.value, block.timestamp); emit BioBidEntered(bioId, msg.value, msg.sender); } /** * @dev See {ILife-acceptBidForBio}. */ function acceptBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) isBioOwner(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.hasBid && existingBid.value > 0, "This Bio doesn't have a valid bid"); uint256 fees = existingBid.value.mul(_feeFraction).div(_feeBase + _feeFraction); uint256 bioValue = existingBid.value.sub(fees); _sendValue(msg.sender, bioValue); _pendingWithdrawals[owner()] = _pendingWithdrawals[owner()].add(fees); _safeTransfer(msg.sender, existingBid.bidder, bioId, ""); emit BioBidAccepted(bioId, bioValue, msg.sender, existingBid.bidder); _removeBid(bioId); if (_bioListedForSale[bioId].isForSale) { _delistBio(bioId); } } /** * @dev See {ILife-withdrawBidForBio}. */ function withdrawBidForBio(uint256 bioId) external override saleEnded bioExist(bioId) nonReentrant { Bid memory existingBid = _bioWithBids[bioId]; require(existingBid.bidder == msg.sender, "This address doesn't have active bid"); _sendValue(msg.sender, existingBid.value); emit BioBidWithdrawn(bioId, existingBid.value, existingBid.bidder); _removeBid(bioId); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 bioId ) public override nonReentrant { require( _isApprovedOrOwner(_msgSender(), bioId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, bioId); if (_bioListedForSale[bioId].seller == from) { _delistBio(bioId); } if (_bioWithBids[bioId].bidder == to) { _sendValue(_bioWithBids[bioId].bidder, _bioWithBids[bioId].value); _removeBid(bioId); } } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 bioId ) public override { safeTransferFrom(from, to, bioId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 bioId, bytes memory _data ) public override nonReentrant { require( _isApprovedOrOwner(_msgSender(), bioId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, bioId, _data); if (_bioListedForSale[bioId].seller == from) { _delistBio(bioId); } if (_bioWithBids[bioId].bidder == to) { _sendValue(_bioWithBids[bioId].bidder, _bioWithBids[bioId].value); _removeBid(bioId); } } /** * @dev See {ILife-serviceFee}. */ function serviceFee() external view override returns (uint8, uint8) { return (_feeFraction, _feeBase); } /** * @dev See {ILife-pendingWithdrawals}. */ function pendingWithdrawals(address toAddress) external view override returns (uint256) { return _pendingWithdrawals[toAddress]; } /** * @dev See {ILife-withdraw}. */ function withdraw() external override nonReentrant { require(_pendingWithdrawals[msg.sender] > 0, "There is nothing to withdraw"); _sendValue(msg.sender, _pendingWithdrawals[msg.sender]); _pendingWithdrawals[msg.sender] = 0; } /** * @dev Change withdrawal fee percentage. * If 1%, then input (1,100) * If 0.5%, then input (5,1000) * @param feeFraction_ Fraction of withdrawal fee based on feeBase_ * @param feeBase_ Fraction of withdrawal fee base */ function changeSeriveFee(uint8 feeFraction_, uint8 feeBase_) external onlyOwner { require(feeFraction_ <= feeBase_, "Fee fraction exceeded base."); uint256 percentage = (feeFraction_ * 1000) / feeBase_; require(percentage <= 25, "Attempt to set percentage higher than 2.5%."); _feeFraction = feeFraction_; _feeBase = feeBase_; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "@openzeppelin/contracts/token/ERC721/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); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12; pragma experimental ABIEncoderV2; /** * @title NFTKEY Life interface */ interface ILife { struct Listing { bool isForSale; uint256 bioId; address seller; uint256 minValue; address onlySellTo; uint256 timestamp; } struct Bid { bool hasBid; uint256 bioId; address bidder; uint256 value; uint256 timestamp; } event BioMinted(uint256 indexed bioId, address indexed owner, uint8[] bioDNA, bytes32 bioHash); event BioListed( uint256 indexed bioId, uint256 minValue, address indexed fromAddress, address indexed toAddress ); event BioDelisted(uint256 indexed bioId, address indexed fromAddress); event BioBidEntered(uint256 indexed bioId, uint256 value, address indexed fromAddress); event BioBidWithdrawn(uint256 indexed bioId, uint256 value, address indexed fromAddress); event BioBidRemoved(uint256 indexed bioId, address indexed fromAddress); event BioBought( uint256 indexed bioId, uint256 value, address indexed fromAddress, address indexed toAddress ); event BioBidAccepted( uint256 indexed bioId, uint256 value, address indexed fromAddress, address indexed toAddress ); /** * @dev Gets DNA encoding of a Bio by token Id * @param bioId Bio token Id * @return Bio DNA encoding */ function getBioDNA(uint256 bioId) external view returns (uint8[] memory); /** * @dev Gets DNA encoding of a Bios * @param from From Bio id * @param size Query size * @return Bio DNAs */ function getBioDNAs(uint256 from, uint256 size) external view returns (uint8[][] memory); /** * @dev Gets current Bio Price * @return Current Bio Price */ function getBioPrice() external view returns (uint256); /** * @dev Check if a Bio is already minted or not * @param bioDNA Bio DNA encoding * @return If Bio exist, or if similar Bio exist */ function isBioExist(uint8[] memory bioDNA) external view returns (bool); /** * @dev Mint Bio * @param bioDNA Bio DNA encoding */ function mintBio(uint8[] memory bioDNA) external payable; /** * @dev Get Bio listing information * @param bioId Bio token id * @return Bio Listing detail */ function getBioListing(uint256 bioId) external view returns (Listing memory); /** * @dev Get Bio listings * @param from From Bio id * @param size Query size * @return Bio Listings */ function getBioListings(uint256 from, uint256 size) external view returns (Listing[] memory); /** * @dev Get Bio bid information * @param bioId Bio token id * @return Bio bid detail */ function getBioBid(uint256 bioId) external view returns (Bid memory); /** * @dev Get Bio bids * @param from From Bio id * @param size Query size * @return Bio bids */ function getBioBids(uint256 from, uint256 size) external view returns (Bid[] memory); /** * @dev List a Bio for sale * @param bioId Bio token id * @param minValue Bio minimum value */ function listBioForSale(uint256 bioId, uint256 minValue) external; /** * @dev List a Bio for sale to a certain address * @param bioId Bio token id * @param minValue Bio minimum value * @param toAddress Address to sell this Bio to */ function listBioForSaleToAddress( uint256 bioId, uint256 minValue, address toAddress ) external; /** * @dev Delist a Bio * @param bioId Bio token id */ function delistBio(uint256 bioId) external; /** * @dev Buy a Bio * @param bioId Bio token id */ function buyBio(uint256 bioId) external payable; /** * @dev Put bid on a Bio * @param bioId Bio token id */ function enterBidForBio(uint256 bioId) external payable; /** * @dev Accept s bid for a Bio * @param bioId Bio token id */ function acceptBidForBio(uint256 bioId) external; /** * @dev Withdraw s bid for a Bio * @param bioId Bio token id */ function withdrawBidForBio(uint256 bioId) external; /** * @dev Returns service fee. * @return The first value is fraction, the second one is fraction base */ function serviceFee() external view returns (uint8, uint8); /** * @dev Get pending withdrawals * @param toAddress Address to check withdrawals */ function pendingWithdrawals(address toAddress) external view returns (uint256); /** * @dev Withdraw ether from this contract */ function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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.6.2 <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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // 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 String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
See {IERC721-safeTransferFrom}./
function safeTransferFrom( address from, address to, uint256 bioId ) public override { safeTransferFrom(from, to, bioId, ""); }
6,268,174
/** *Submitted for verification at Etherscan.io on 2020-09-03 */ /** *Submitted for verification at Etherscan.io on 2020-08-26 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/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 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: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/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 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: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/CocktailToken.sol pragma solidity 0.6.12; // CocktailToken with Governance. contract CocktailToken is ERC20("CocktailToken", "COCK"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (Bartender). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "COCK::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "COCK::delegateBySig: invalid nonce"); require(now <= expiry, "COCK::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "COCK::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying COCKs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "COCK::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/Bartender.sol pragma solidity 0.6.12; interface IMigratorChef { // Perform LP token migration from legacy UniswapV2 to CockSwap. // 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. // CockSwap must mint EXACTLY the same amount of CockSwap LP tokens or // else something bad will happen. Traditional UniswapV2 does not // do that so be careful! function migrate(IERC20 token) external returns (IERC20); } // Bartender is the master of Cock. He can make Cock and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once COCK is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract Bartender is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of COCKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCockPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCockPerShare` (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 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. COCKs to distribute per block. uint256 lastRewardBlock; // Last block number that COCKs distribution occurs. uint256 accCockPerShare; // Accumulated COCKs per share, times 1e12. See below. } // The COCK TOKEN! CocktailToken public cock; // Dev address. address public devaddr; // Block number when bonus COCK period ends. uint256 public bonusEndBlock; // COCK tokens created per block. uint256 public cockPerBlock; // Bonus muliplier for early cock makers. uint256 public constant BONUS_MULTIPLIER = 10; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP 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 = 0; // The block number when COCK mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( CocktailToken _cock, address _devaddr, uint256 _cockPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { cock = _cock; devaddr = _devaddr; cockPerBlock = _cockPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCockPerShare: 0 })); } // Update the given pool's COCK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending COCKs on frontend. function pendingCock(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCockPerShare = pool.accCockPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cockReward = multiplier.mul(cockPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCockPerShare = accCockPerShare.add(cockReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCockPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cockReward = multiplier.mul(cockPerBlock).mul(pool.allocPoint).div(totalAllocPoint); cock.mint(devaddr, cockReward.div(10)); cock.mint(address(this), cockReward); pool.accCockPerShare = pool.accCockPerShare.add(cockReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Bartender for COCK allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCockPerShare).div(1e12).sub(user.rewardDebt); safeCockTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCockPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from Bartender. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accCockPerShare).div(1e12).sub(user.rewardDebt); safeCockTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCockPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe cock transfer function, just in case if rounding error causes pool to not have enough COCKs. function safeCockTransfer(address _to, uint256 _amount) internal { uint256 cockBal = cock.balanceOf(address(this)); if (_amount > cockBal) { cock.transfer(_to, cockBal); } else { cock.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "COCK::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
14,469,873
./partial_match/97/0xFc08167F6D8c7662cc10B41cA1D4AbD3E24be313/sources/CrowdSale.sol
update crowdsale params eswToken - ESW token address uniswapFactory - uniswap factory address, for getting market rates referralStoreInput - referral contract address wethToken - wethToken token address _foundationWallet - _foundationWallet wallet address _teamWallet - _teamWallet wallet address _defRef - _defRef wallet address/
function updateParams( address eswToken, address uniswapFactory, address referralStoreInput, address wethToken, address payable _foundationWallet, address _teamWallet, address _defRef ) public onlyAdmin { require( eswToken != address(0) || uniswapFactory != address(0) || referralStoreInput != address(0) || wethToken != address(0) || _foundationWallet != address(0) || _teamWallet != address(0) || _defRef != address(0), "Sale: Addresses cannot be empty!" ); _token = eswToken; _uniswapFactory = uniswapFactory; referralStore = referralStoreInput; _wethToken = wethToken; foundationWallet = _foundationWallet; teamWallet = _teamWallet; defRef = _defRef; }
11,367,499
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; /** * @title Rebud Collection ERC1155 Smart Contract * @dev Extends ERC1155 */ contract RebudCollection is ERC1155, ERC1155Supply, ERC1155Burnable, Ownable, ReentrancyGuard { string private _contractURI; address public minterAddress; string _name = "Rebud"; string _symbol = "BUDS"; uint256 public mintingTokenID = 0; uint256 public numberMintedTotal = 0; uint256 public maxTokens = 420; uint256 public maxPerWallet = 50; /// PUBLIC MINT uint256 public tokenPricePublic = 0.089 ether; bool public mintIsActivePublic = false; uint256 public maxTokensPerTransactionPublic = 50; uint256 public numberMintedPublic = 0; uint256 public maxTokensPublic = 420; // PRESALE MINT uint256 public tokenPricePresale = 0.089 ether; bool public mintIsActivePresale = false; mapping (uint256 => mapping (address => bool) ) public presaleWalletList; uint256 public maxTokensPerTransactionPresale = 50; uint256 public numberMintedPresale = 0; uint256 public maxTokensPresale = 420; // FREE WALLET BASED MINT bool public mintIsActiveFree = false; uint256 public numberFreeToMint = 1; mapping (uint256 => mapping (address => bool) ) public freeWalletList; // PRESALE MERKLE MINT mapping (uint256 => mapping (address => bool) ) public presaleMerkleWalletList; bytes32 public presaleMerkleRoot; /** * @notice sets Merkle Root for presale */ function setMerkleRoot(bytes32 _presaleMerkleRoot) public onlyOwner { presaleMerkleRoot = _presaleMerkleRoot; } /** * @notice view function to check if a merkleProof is valid before sending presale mint function */ function isOnPresaleMerkle(bytes32[] calldata _merkleProof) public view returns(bool) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); return MerkleProof.verify(_merkleProof, presaleMerkleRoot, leaf); } constructor() ERC1155(""){} // PUBLIC MINT /** * @notice turn on/off public mint */ function flipMintStatePublic() external onlyOwner { mintIsActivePublic = !mintIsActivePublic; } /** * @notice Public mint function */ function mint(uint256 numberOfTokens) external payable nonReentrant { require(mintIsActivePublic, "Public mint is not active"); require(balanceOf(msg.sender, mintingTokenID) <= maxPerWallet); require( numberOfTokens <= maxTokensPerTransactionPublic, "You went over max tokens per transaction" ); require( msg.value >= tokenPricePublic * numberOfTokens, "You sent the incorrect amount of ETH" ); require( numberMintedPublic + numberOfTokens <= maxTokensPublic, "Not enough Public Mint tokens left to mint that many" ); require( numberMintedTotal + numberOfTokens <= maxTokens, "Not enough Total tokens left to mint that many" ); numberMintedPublic += numberOfTokens; numberMintedTotal += numberOfTokens; _mint(msg.sender, mintingTokenID, numberOfTokens, ""); } // PRESALE WALLET MINT /** * @notice Turn on/off presale wallet mint */ function flipPresaleMintState() external onlyOwner { mintIsActivePresale = !mintIsActivePresale; } /** * @notice useful to reset a list of addresses to be able to presale mint again. */ function initPresaleWalletList(address[] memory walletList) external onlyOwner { for (uint i; i < walletList.length; i++) { presaleWalletList[mintingTokenID][walletList[i]] = true; } } /** * @notice check if address is on presale list */ function checkAddressOnPresaleList(uint256 tokenId, address wallet) public view returns (bool) { return presaleWalletList[tokenId][wallet]; } /** * @notice Presale wallet list mint */ function mintPresale(uint256 numberOfTokens) external payable nonReentrant { require(mintIsActivePresale, "Presale mint is not active"); require( numberOfTokens <= maxTokensPerTransactionPresale, "You went over max tokens per transaction" ); require( msg.value >= tokenPricePresale * numberOfTokens, "You sent the incorrect amount of ETH" ); require( presaleWalletList[mintingTokenID][msg.sender] == true, "You are not on the presale wallet list or have already minted" ); require( numberMintedPresale + numberOfTokens <= maxTokensPresale, "Not enough tokens left to mint that many" ); require( numberMintedTotal + numberOfTokens <= maxTokens, "Not enough tokens left to mint that many" ); numberMintedPresale += numberOfTokens; numberMintedTotal += numberOfTokens; presaleWalletList[mintingTokenID][msg.sender] = false; _mint(msg.sender, mintingTokenID, numberOfTokens, ""); } // PRESALE WALLET MERKLE MINT /** * @notice useful to reset a list of addresses to be able to presale mint again. */ function initPresaleMerkleWalletList(address[] memory walletList) external onlyOwner { for (uint i; i < walletList.length; i++) { presaleMerkleWalletList[mintingTokenID][walletList[i]] = false; } } /** * @notice check if address is on presale list */ function checkAddressOnPresaleMerkleWalletList(uint256 tokenId, address wallet) public view returns (bool) { return presaleMerkleWalletList[tokenId][wallet]; } /** * @notice Presale wallet list mint */ function mintPresaleMerkle(uint256 numberOfTokens, bytes32[] calldata _merkleProof) external payable nonReentrant{ require(mintIsActivePresale, "Presale mint is not active"); require( numberOfTokens <= maxTokensPerTransactionPresale, "You went over max tokens per transaction" ); require( msg.value >= tokenPricePresale * numberOfTokens, "You sent the incorrect amount of ETH" ); require( presaleMerkleWalletList[mintingTokenID][msg.sender] == false, "You are not on the presale wallet list or have already minted" ); require( numberMintedPresale + numberOfTokens <= maxTokensPresale, "Not enough tokens left to mint that many" ); require( numberMintedTotal + numberOfTokens <= maxTokens, "Not enough tokens left to mint that many" ); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_merkleProof, presaleMerkleRoot, leaf), "Invalid Proof"); numberMintedPresale += numberOfTokens; numberMintedTotal += numberOfTokens; presaleMerkleWalletList[mintingTokenID][msg.sender] = true; _mint(msg.sender, mintingTokenID, numberOfTokens, ""); } // Free Wallet Mint /** * @notice turn on/off free wallet mint */ function flipFreeWalletState() external onlyOwner { mintIsActiveFree = !mintIsActiveFree; } /** * @notice data structure for uploading free mint wallets */ function initFreeWalletList(address[] memory walletList) external onlyOwner { for (uint256 i = 0; i < walletList.length; i++) { freeWalletList[mintingTokenID][walletList[i]] = true; } } /** * @notice check if address is on free wallet list */ function checkAddressOnFreeWalletList(uint256 tokenId, address wallet) public view returns (bool) { return freeWalletList[tokenId][wallet]; } /** * @notice Free mint for wallets in freeWalletList */ function mintFreeWalletList() external nonReentrant { require(mintIsActiveFree, "Free mint is not active"); require( numberMintedTotal + numberFreeToMint <= maxTokens, "Not enough tokens left to mint that many" ); require( freeWalletList[mintingTokenID][msg.sender] == true, "You are not on the free wallet list or have already minted" ); numberMintedTotal += numberFreeToMint; freeWalletList[mintingTokenID][msg.sender] = false; _mint(msg.sender, mintingTokenID, numberFreeToMint, ""); } /** * @notice set address of minter for airdrops */ function setMinterAddress(address minter) public onlyOwner { minterAddress = minter; } modifier onlyMinter { require(minterAddress == msg.sender || owner() == msg.sender, "You must have the Minter role"); _; } /** * @notice mint a collection to the contract wallet */ function mintReserve(uint256 amount) public onlyOwner { _mint(msg.sender, mintingTokenID, amount, ""); } /** * @notice mint a batch of token collections to the contract wallet */ function mintBatch( uint256[] memory ids, uint256[] memory amounts ) public onlyMinter { _mintBatch(msg.sender, ids, amounts, ""); } /** * @notice mint a collection to a wallet */ function mintToWallet(address toWallet, uint256 amount) public onlyOwner { _mint(toWallet, mintingTokenID, amount, ""); } /** * @notice airdrop a specific token to a list of addresses */ function airdrop(address[] calldata addresses, uint id, uint amt_each) public onlyMinter { for (uint i=0; i < addresses.length; i++) { _mint(addresses[i], id, amt_each, ""); } } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function contractURI() public view returns (string memory) { return _contractURI; } // @title SETTER FUNCTIONS /** * @notice set token base uri */ function setURI(string memory baseURI) public onlyMinter { _setURI(baseURI); } /** * @notice set contract uri https://docs.opensea.io/docs/contract-level-metadata */ function setContractURI(string memory newContractURI) public onlyOwner { _contractURI = newContractURI; } /** * @notice Set token price of presale - tokenPricePublic */ function setTokenPricePublic(uint256 tokenPrice) external onlyOwner { require(tokenPrice >= 0, "Must be greater or equal then zer0"); tokenPricePublic = tokenPrice; } /** * @notice Set max tokens allowed minted in public sale - maxTokensPublic */ function setMaxTokens (uint256 amount) external onlyOwner { require(amount >= 0, "Must be greater or equal than zer0"); maxTokens = amount; } /** * @notice Set total number of tokens minted in public sale - numberMintedPublic */ function setNumberMintedTotal(uint256 amount) external onlyOwner { require(amount >= 0, "Must be greater or equal than zer0"); numberMintedTotal = amount; } /** * @notice Set max tokens allowed minted in public sale - maxTokensPublic */ function setMaxTokensPublic (uint256 amount) external onlyOwner { require(amount >= 0, "Must be greater or equal than zer0"); maxTokensPublic = amount; } /** * @notice Set total number of tokens minted in public sale - numberMintedPublic */ function setNumberMintedPublic(uint256 amount) external onlyOwner { require(amount >= 0, "Must be greater or equal than zer0"); numberMintedPublic = amount; } /** * @notice Set max tokens per transaction for public sale - maxTokensPerTransactionPublic */ function setMaxTokensPerTransactionPublic(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); maxTokensPerTransactionPublic = amount; } /** * @notice Set token price of presale - tokenPricePresale */ function setTokenPricePresale(uint256 tokenPrice) external onlyOwner { require(tokenPrice >= 0, "Must be greater or equal than zer0"); tokenPricePresale = tokenPrice; } /** * @notice Set max tokens allowed minted in presale - maxTokensPresale */ function setMaxTokensPresale(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); maxTokensPresale = amount; } /** * @notice Set total number of tokens minted in presale - numberMintedPresale */ function setNumberMintedPresale(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); numberMintedPresale = amount; } /** * @notice Set max tokens per transaction for presale - maxTokensPerTransactionPresale */ function setMaxTokensPerTransactionPresale(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); maxTokensPerTransactionPresale = amount; } /** * @notice Set the current token ID minting - mintingTokenID */ function setMintingTokenID(uint256 tokenID) external onlyOwner { require(tokenID >= 0, "Invalid token id"); mintingTokenID = tokenID; } /** * @notice Set max tokens per wallet - maxPerWallet */ function setMaxPerWallet(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); maxPerWallet = amount; } /** * @notice Set the current token ID minting and reset all counters and active mints to 0 and false respectively */ function setMintingTokenIdAndResetState(uint256 tokenID) external onlyOwner { require(tokenID >= 0, "Invalid token id"); mintingTokenID = tokenID; mintIsActivePublic = false; mintIsActivePresale = false; mintIsActiveFree = false; numberMintedTotal = 0; numberMintedPresale = 0; numberMintedPublic = 0; } /** * @notice Withdraw ETH in contract to ownership wallet */ function withdraw() external onlyOwner { uint256 balance = address(this).balance; Address.sendValue(payable(owner()), balance); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155, ERC1155Supply) { 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 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155Burnable is ERC1155 { function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } } // SPDX-License-Identifier: MIT // 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 v4.4.1 (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 = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // 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 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/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 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
Set total number of tokens minted in presale - numberMintedPresale/
function setNumberMintedPresale(uint256 amount) external onlyOwner { require(amount >= 0, "Invalid amount"); numberMintedPresale = amount; }
1,460,690
pragma solidity ^0.4.17; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address from, address to); /** * The address whcih deploys this contrcat is automatically assgined ownership. * */ function Ownable() public { owner = msg.sender; } /** * Functions with this modifier can only be executed by the owner of the contract. * */ modifier onlyOwner { require(msg.sender == owner); _; } /** * Transfers ownership provided that a valid address is given. This function can * only be called by the owner of the contract. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint; mapping(address => uint) balances; modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } /** * @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, uint _value) public onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint256)) allowances; /** * Transfers tokens from the account of the owner by an approved spender. * The spender cannot spend more than the approved amount. * * @param _from The address of the owners account. * @param _amount The amount of tokens to transfer. * */ function transferFrom(address _from, address _to, uint256 _amount) public onlyPayloadSize(3 * 32) { require(allowances[_from][msg.sender] >= _amount && balances[_from] >= _amount); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); Transfer(_from, _to, _amount); } /** * Allows another account to spend a given amount of tokens on behalf of the * owner's account. If the owner has previously allowed a spender to spend * tokens on his or her behalf and would like to change the approval amount, * he or she will first have to set the allowance back to 0 and then update * the allowance. * * @param _spender The address of the spenders account. * @param _amount The amount of tokens the spender is allowed to spend. * */ function approve(address _spender, uint256 _amount) public { require((_amount == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); } /** * Returns the approved allowance from an owners account to a spenders account. * * @param _owner The address of the owners account. * @param _spender The address of the spenders account. **/ function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } } contract MintableToken is StandardToken { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * Mints a given amount of tokens to the provided address. This function can only be called by the contract's * owner, which in this case is the ICO contract itself. From there, the founders of the ICO contract will be * able to invoke this function. * * @param _to The address which will receive the tokens. * @param _amount The total amount of ETCL tokens to be minted. */ function mint(address _to, uint256 _amount) public onlyOwner canMint onlyPayloadSize(2 * 32) returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * Terminates the minting period permanently. This function can only be called by the owner of the contract. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract Ethercloud is MintableToken { uint8 public decimals; string public name; string public symbol; function Ethercloud() public { totalSupply = 0; decimals = 18; name = "Ethercloud"; symbol = "ETCL"; } } contract ICO is Ownable { using SafeMath for uint256; Ethercloud public ETCL; bool public success; uint256 public rate; uint256 public rateWithBonus; uint256 public bountiesIssued; uint256 public tokensSold; uint256 public tokensForSale; uint256 public tokensForBounty; uint256 public maxTokens; uint256 public startTime; uint256 public endTime; uint256 public softCap; uint256 public hardCap; uint256[3] public bonusStages; mapping (address => uint256) investments; event TokensPurchased(address indexed by, uint256 amount); event RefundIssued(address indexed by, uint256 amount); event FundsWithdrawn(address indexed by, uint256 amount); event BountyIssued(address indexed to, uint256 amount); event IcoSuccess(); event CapReached(); function ICO() public { ETCL = new Ethercloud(); success = false; rate = 1288; rateWithBonus = 1674; bountiesIssued = 0; tokensSold = 0; tokensForSale = 78e24; //78 million ETCL for sale tokensForBounty = 2e24; //2 million ETCL for bounty maxTokens = 100e24; //100 million ETCL startTime = now.add(15 days); //ICO starts 15 days after deployment endTime = startTime.add(30 days); //30 days end time softCap = 6212530674370205e6; //6212.530674370205 ETH hardCap = 46594980057776535e6; //46594.980057776535 ETH bonusStages[0] = startTime.add(7 days); for (uint i = 1; i < bonusStages.length; i++) { bonusStages[i] = bonusStages[i - 1].add(7 days); } } /** * When ETH is sent to the contract, the fallback function calls the buy tokens function. */ function() public payable { buyTokens(msg.sender); } /** * Allows investors to buy ETCL tokens by sending ETH and automatically receiving tokens * to the provided address. * * @param _beneficiary The address which will receive the tokens. */ function buyTokens(address _beneficiary) public payable { require(_beneficiary != 0x0 && validPurchase() && this.balance.sub(msg.value) < hardCap); if (this.balance >= softCap && !success) { success = true; IcoSuccess(); } uint256 weiAmount = msg.value; if (this.balance > hardCap) { CapReached(); uint256 toRefund = this.balance.sub(hardCap); msg.sender.transfer(toRefund); weiAmount = weiAmount.sub(toRefund); } uint256 tokens = weiAmount.mul(getCurrentRateWithBonus()); if (tokensSold.add(tokens) > tokensForSale) { revert(); } ETCL.mint(_beneficiary, tokens); tokensSold = tokensSold.add(tokens); investments[_beneficiary] = investments[_beneficiary].add(weiAmount); TokensPurchased(_beneficiary, tokens); } /** * Returns the current rate with bonus percentage of the tokens. */ function getCurrentRateWithBonus() internal returns (uint256) { rateWithBonus = (rate.mul(getBonusPercentage()).div(100)).add(rate); return rateWithBonus; } /** * Returns the current bonus percentage. */ function getBonusPercentage() internal view returns (uint256 bonusPercentage) { uint256 timeStamp = now; if (timeStamp > bonusStages[2]) { bonusPercentage = 0; } if (timeStamp <= bonusStages[2]) { bonusPercentage = 5; } if (timeStamp <= bonusStages[1]) { bonusPercentage = 15; } if (timeStamp <= bonusStages[0]) { bonusPercentage = 30; } return bonusPercentage; } /** * Mints a given amount of new tokens to the provided address. This function can only be * called by the owner of the contract. * * @param _beneficiary The address which will receive the tokens. * @param _amount The total amount of tokens to be minted. */ function issueTokens(address _beneficiary, uint256 _amount) public onlyOwner { require(_beneficiary != 0x0 && _amount > 0 && tokensSold.add(_amount) <= tokensForSale); ETCL.mint(_beneficiary, _amount); tokensSold = tokensSold.add(_amount); TokensPurchased(_beneficiary, _amount); } /** * Checks whether or not a purchase is valid. If not, then the buy tokens function will * not execute. */ function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } /** * Allows investors to claim refund in the case that the soft cap has not been reached and * the duration of the ICO has passed. * * @param _addr The address to be refunded. If no address is provided, the _addr will default * to the message sender. */ function getRefund(address _addr) public { if (_addr == 0x0) { _addr = msg.sender; } require(!isSuccess() && hasEnded() && investments[_addr] > 0); uint256 toRefund = investments[_addr]; investments[_addr] = 0; _addr.transfer(toRefund); RefundIssued(_addr, toRefund); } /** * Mints new tokens for the bounty campaign. This function can only be called by the owner * of the contract. * * @param _beneficiary The address which will receive the tokens. * @param _amount The total amount of tokens that will be minted. */ function issueBounty(address _beneficiary, uint256 _amount) public onlyOwner { require(bountiesIssued.add(_amount) <= tokensForBounty && _beneficiary != 0x0); ETCL.mint(_beneficiary, _amount); bountiesIssued = bountiesIssued.add(_amount); BountyIssued(_beneficiary, _amount); } /** * Withdraws the total amount of ETH raised to the owners address. This function can only be * called by the owner of the contract given that the ICO is a success and the duration has * passed. */ function withdraw() public onlyOwner { uint256 inCirculation = tokensSold.add(bountiesIssued); ETCL.mint(owner, inCirculation.mul(25).div(100)); owner.transfer(this.balance); } /** * Returns true if the ICO is a success, false otherwise. */ function isSuccess() public constant returns (bool) { return success; } /** * Returns true if the duration of the ICO has passed, false otherwise. */ function hasEnded() public constant returns (bool) { return now > endTime; } /** * Returns the end time of the ICO. */ function endTime() public constant returns (uint256) { return endTime; } /** * Returns the total investment of a given ETH address. * * @param _addr The address being queried. */ function investmentOf(address _addr) public constant returns (uint256) { return investments[_addr]; } /** * Finishes the minting period. This function can only be called by the owner of the * contract given that the duration of the ICO has ended. */ function finishMinting() public onlyOwner { require(hasEnded()); ETCL.finishMinting(); } }
Mints a given amount of tokens to the provided address. This function can only be called by the contract's owner, which in this case is the ICO contract itself. From there, the founders of the ICO contract will be able to invoke this function. _to The address which will receive the tokens. _amount The total amount of ETCL tokens to be minted./
function mint(address _to, uint256 _amount) public onlyOwner canMint onlyPayloadSize(2 * 32) returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; }
12,849,582
./full_match/3/0x77AD263Cd578045105FBFC88A477CAd808d39Cf6/sources/contracts/libraries/Oracle.sol
Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos` Reverts if `secondsAgos` > oldest observation self The stored oracle array time The current block.timestamp secondsAgos Each amount of time to look back, in seconds, at which point to return an observation tick The current tick index The location of a given observation within the oracle array liquidity The current in-range pool liquidity cardinality The number of populated elements in the oracle array return tickCumulatives The tick time elapsed since the pool was first initialized, as of each `secondsAgo` return liquidityCumulatives The liquidity time elapsed since the pool was first initialized, as of each `secondsAgo`
function observe( Observation[65535] storage self, uint32 time, uint32[] memory secondsAgos, int24 tick, uint16 index, uint128 liquidity, uint16 cardinality ) internal view returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives) { require(cardinality > 0, 'I'); tickCumulatives = new int56[](secondsAgos.length); liquidityCumulatives = new uint160[](secondsAgos.length); for (uint256 i = 0; i < secondsAgos.length; i++) { (tickCumulatives[i], liquidityCumulatives[i]) = observeSingle( self, time, secondsAgos[i], tick, index, liquidity, cardinality ); } }
14,155,926
./partial_match/56/0xA541219F5596823f12436070352993D3a9d7578C/sources/MasterChef.sol
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "CHRY::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
11,041,191
./full_match/41/0xa07A08178759e7C99984523980807356640118D0/sources/contracts/PairBridgeRegister.sol
UTILS ================================================================ >
function _isERC20Bridgeable(IERC20Bridgeable token) internal view returns(bool) { try token.supportsInterface(0x01ffc9a7) { return true; return false; } }
16,378,677
/** * Because the use of ABIEncoderV2 , the pragma should be locked above 0.5.10 , * as there is a known bug in array storage: * https://blog.ethereum.org/2019/06/25/solidity-storage-array-bugs/ */ pragma solidity >=0.5.10 <0.6.0; pragma experimental ABIEncoderV2; import {Proxiable} from "./Proxiable.sol"; import {Ownable} from "./Ownable.sol"; import {LibraryLock} from "./LibraryLock.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {ReentrancyGuard} from "./ReentrancyGuard.sol"; import {RTokenStructs} from "./RTokenStructs.sol"; import {RTokenStorage} from "./RTokenStorage.sol"; import {IERC20, IRToken} from "./IRToken.sol"; import {IRTokenAdmin} from "./IRTokenAdmin.sol"; import {IAllocationStrategy} from "./IAllocationStrategy.sol"; import {Dai} from "./test/Dai.sol"; /** * @notice RToken an ERC20 token that is 1:1 redeemable to its underlying ERC20 token. */ contract RToken is RTokenStorage, IRToken, IRTokenAdmin, Ownable, Proxiable, LibraryLock, ReentrancyGuard { using SafeMath for uint256; uint256 public constant ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE = 1e18; uint256 public constant INITIAL_SAVING_ASSET_CONVERSION_RATE = 1e18; uint256 public constant MAX_UINT256 = uint256(int256(-1)); uint256 public constant SELF_HAT_ID = MAX_UINT256; uint32 public constant PROPORTION_BASE = 0xFFFFFFFF; uint256 public constant MAX_NUM_HAT_RECIPIENTS = 50; /** * @notice Create rToken linked with cToken at `cToken_` */ function initialize( IAllocationStrategy allocationStrategy, string memory name_, string memory symbol_, uint256 decimals_) public { require(!initialized, "The library has already been initialized."); LibraryLock.initialize(); _owner = msg.sender; _guardCounter = 1; name = name_; symbol = symbol_; decimals = decimals_; savingAssetConversionRate = INITIAL_SAVING_ASSET_CONVERSION_RATE; ias = allocationStrategy; token = IERC20(ias.underlying()); // special hat aka. zero hat : hatID = 0 hats.push(Hat(new address[](0), new uint32[](0))); // everyone is using it by default! hatStats[0].useCount = MAX_UINT256; emit AllocationStrategyChanged(address(ias), savingAssetConversionRate); } // // ERC20 Interface // /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address owner) external view returns (uint256) { return accounts[owner].rAmount; } /** * @notice Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Moves `amount` tokens from the caller's account to `dst`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. * May also emit `InterestPaid` event. */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); transferInternal(src, src, dst, amount); payInterestInternal(dst); return true; } /// @dev IRToken.transferAll implementation function transferAll(address dst) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); transferInternal(src, src, dst, accounts[src].rAmount); payInterestInternal(dst); return true; } /// @dev IRToken.transferAllFrom implementation function transferAllFrom(address src, address dst) external nonReentrant returns (bool) { payInterestInternal(src); transferInternal(msg.sender, src, dst, accounts[src].rAmount); payInterestInternal(dst); return true; } /** * @notice 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 src, address dst, uint256 amount) external nonReentrant returns (bool) { payInterestInternal(src); transferInternal(msg.sender, src, dst, amount); payInterestInternal(dst); return true; } // // rToken interface // /// @dev IRToken.mint implementation function mint(uint256 mintAmount) external nonReentrant returns (bool) { mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /// @dev IRToken.mintWithSelectedHat implementation function mintWithSelectedHat(uint256 mintAmount, uint256 hatID) external nonReentrant returns (bool) { changeHatInternal(msg.sender, hatID); mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /** * @dev IRToken.mintWithNewHat implementation */ function mintWithNewHat( uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions ) external nonReentrant returns (bool) { uint256 hatID = createHatInternal(recipients, proportions); changeHatInternal(msg.sender, hatID); mintInternal(mintAmount); payInterestInternal(msg.sender); return true; } /** * @dev IRToken.redeem implementation * It withdraws equal amount of initially supplied underlying assets */ function redeem(uint256 redeemTokens) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(src, redeemTokens); return true; } /// @dev IRToken.redeemAll implementation function redeemAll() external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(src, accounts[src].rAmount); return true; } /// @dev IRToken.redeemAndTransfer implementation function redeemAndTransfer(address redeemTo, uint256 redeemTokens) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(redeemTo, redeemTokens); return true; } /// @dev IRToken.redeemAndTransferAll implementation function redeemAndTransferAll(address redeemTo) external nonReentrant returns (bool) { address src = msg.sender; payInterestInternal(src); redeemInternal(redeemTo, accounts[src].rAmount); return true; } /// @dev IRToken.createHat implementation function createHat( address[] calldata recipients, uint32[] calldata proportions, bool doChangeHat ) external nonReentrant returns (uint256 hatID) { hatID = createHatInternal(recipients, proportions); if (doChangeHat) { changeHatInternal(msg.sender, hatID); } } /// @dev IRToken.changeHat implementation function changeHat(uint256 hatID) external nonReentrant returns (bool) { changeHatInternal(msg.sender, hatID); payInterestInternal(msg.sender); return true; } /// @dev IRToken.getMaximumHatID implementation function getMaximumHatID() external view returns (uint256 hatID) { return hats.length - 1; } /// @dev IRToken.getHatByAddress implementation function getHatByAddress(address owner) external view returns ( uint256 hatID, address[] memory recipients, uint32[] memory proportions ) { hatID = accounts[owner].hatID; (recipients, proportions) = _getHatByID(hatID); } /// @dev IRToken.getHatByID implementation function getHatByID(uint256 hatID) external view returns (address[] memory recipients, uint32[] memory proportions) { (recipients, proportions) = _getHatByID(hatID); } function _getHatByID(uint256 hatID) private view returns (address[] memory recipients, uint32[] memory proportions) { if (hatID != 0 && hatID != SELF_HAT_ID) { Hat memory hat = hats[hatID]; recipients = hat.recipients; proportions = hat.proportions; } else { recipients = new address[](0); proportions = new uint32[](0); } } /// @dev IRToken.receivedSavingsOf implementation function receivedSavingsOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; uint256 rGross = sInternalToR(account.sInternalAmount); return rGross; } /// @dev IRToken.receivedLoanOf implementation function receivedLoanOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; return account.lDebt; } /// @dev IRToken.interestPayableOf implementation function interestPayableOf(address owner) external view returns (uint256 amount) { Account storage account = accounts[owner]; return getInterestPayableOf(account); } /// @dev IRToken.payInterest implementation function payInterest(address owner) external nonReentrant returns (bool) { payInterestInternal(owner); return true; } /// @dev IRToken.getAccountStats implementation!1 function getGlobalStats() external view returns (GlobalStats memory) { uint256 totalSavingsAmount; totalSavingsAmount += sOriginalToR(savingAssetOrignalAmount); return GlobalStats({ totalSupply: totalSupply, totalSavingsAmount: totalSavingsAmount }); } /// @dev IRToken.getAccountStats implementation function getAccountStats(address owner) external view returns (AccountStatsView memory stats) { Account storage account = accounts[owner]; stats.hatID = account.hatID; stats.rAmount = account.rAmount; stats.rInterest = account.rInterest; stats.lDebt = account.lDebt; stats.sInternalAmount = account.sInternalAmount; stats.rInterestPayable = getInterestPayableOf(account); AccountStatsStored storage statsStored = accountStats[owner]; stats.cumulativeInterest = statsStored.cumulativeInterest; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; if (account.hatID == 0 || account.hatID == SELF_HAT_ID) { // Self-hat has storage optimization for lRecipients. // We use the account invariant to calculate lRecipientsSum instead, // so it does look like a tautology indeed. // Check RTokenStructs documentation for more info. stats.lRecipientsSum = gentleSub(stats.rAmount, stats.rInterest); } else { for (uint256 i = 0; i < hat.proportions.length; ++i) { stats.lRecipientsSum += account.lRecipients[hat.recipients[i]]; } } return stats; } /// @dev IRToken.getHatStats implementation function getHatStats(uint256 hatID) external view returns (HatStatsView memory stats) { HatStatsStored storage statsStored = hatStats[hatID]; stats.useCount = statsStored.useCount; stats.totalLoans = statsStored.totalLoans; stats.totalSavings = sInternalToR(statsStored.totalInternalSavings); return stats; } /// @dev IRToken.getCurrentSavingStrategy implementation function getCurrentSavingStrategy() external view returns (address) { return address(ias); } /// @dev IRToken.getSavingAssetBalance implementation function getSavingAssetBalance() external view returns (uint256 rAmount, uint256 sOriginalAmount) { sOriginalAmount = savingAssetOrignalAmount; rAmount = sOriginalToR(sOriginalAmount); } /// @dev IRToken.changeAllocationStrategy implementation function changeAllocationStrategy(address allocationStrategy_) external nonReentrant onlyOwner { IAllocationStrategy allocationStrategy = IAllocationStrategy(allocationStrategy_); require( allocationStrategy.underlying() == address(token), "New strategy should have the same underlying asset" ); IAllocationStrategy oldIas = ias; ias = allocationStrategy; // redeem everything from the old strategy (uint256 sOriginalBurned, ) = oldIas.redeemAll(); uint256 totalAmount = token.balanceOf(address(this)); // invest everything into the new strategy require(token.approve(address(ias), totalAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(totalAmount); // give back the ownership of the old allocation strategy to the admin // unless we are simply switching to the same allocaiton Strategy // // - But why would we switch to the same allocation strategy? // - This is a special case where one could pick up the unsoliciated // savings from the allocation srategy contract as extra "interest" // for all rToken holders. if (address(ias) != address(oldIas)) { Ownable(address(oldIas)).transferOwnership(address(owner())); } // calculate new saving asset conversion rate // // NOTE: // - savingAssetConversionRate should be scaled by 1e18 // - to keep internalSavings constant: // internalSavings == sOriginalBurned * savingAssetConversionRateOld // internalSavings == sOriginalCreated * savingAssetConversionRateNew // => // savingAssetConversionRateNew = sOriginalBurned // * savingAssetConversionRateOld // / sOriginalCreated // uint256 sInternalAmount = sOriginalToSInternal(savingAssetOrignalAmount); uint256 savingAssetConversionRateOld = savingAssetConversionRate; savingAssetConversionRate = sOriginalBurned .mul(savingAssetConversionRateOld) .div(sOriginalCreated); savingAssetOrignalAmount = sInternalToSOriginal(sInternalAmount); emit AllocationStrategyChanged(allocationStrategy_, savingAssetConversionRate); } /// @dev IRToken.changeHatFor implementation function getCurrentAllocationStrategy() external view returns (address allocationStrategy) { return address(ias); } /// @dev IRToken.changeHatFor implementation function changeHatFor(address contractAddress, uint256 hatID) external onlyOwner { require(_isContract(contractAddress), "Admin can only change hat for contract address"); changeHatInternal(contractAddress, hatID); } /// @dev Update the rToken logic contract code function updateCode(address newCode) external onlyOwner delegatedOnly { updateCodeAddress(newCode); emit CodeUpdated(newCode); } /** * @dev Transfer `tokens` tokens from `src` to `dst` by `spender` Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferInternal( address spender, address src, address dst, uint256 tokens ) internal { require(src != dst, "src should not equal dst"); require( accounts[src].rAmount >= tokens, "Not enough balance to transfer" ); /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = MAX_UINT256; } else { startingAllowance = transferAllowances[src][spender]; } require( startingAllowance >= tokens, "Not enough allowance for transfer" ); /* Do the calculations, checking for {under,over}flow */ uint256 allowanceNew = startingAllowance.sub(tokens); uint256 srcTokensNew = accounts[src].rAmount.sub(tokens); uint256 dstTokensNew = accounts[dst].rAmount.add(tokens); /* Eat some of the allowance (if necessary) */ if (startingAllowance != MAX_UINT256) { transferAllowances[src][spender] = allowanceNew; } // lRecipients adjustments uint256 sInternalEstimated = estimateAndRecollectLoans(src, tokens); distributeLoans(dst, tokens, sInternalEstimated); // update token balances accounts[src].rAmount = srcTokensNew; accounts[dst].rAmount = dstTokensNew; // apply hat inheritance rule if ((accounts[src].hatID != 0 && accounts[dst].hatID == 0 && accounts[src].hatID != SELF_HAT_ID)) { changeHatInternal(dst, accounts[src].hatID); } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); } /** * @dev Sender supplies assets into the market and receives rTokens in exchange * @dev Invest into underlying assets immediately * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint256 mintAmount) internal { require( token.allowance(msg.sender, address(this)) >= mintAmount, "Not enough allowance" ); Account storage account = accounts[msg.sender]; // create saving assets require(token.transferFrom(msg.sender, address(this), mintAmount), "token transfer failed"); require(token.approve(address(ias), mintAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(mintAmount); // update global and account r balances totalSupply = totalSupply.add(mintAmount); account.rAmount = account.rAmount.add(mintAmount); // update global stats savingAssetOrignalAmount = savingAssetOrignalAmount.add(sOriginalCreated); // distribute saving assets as loans to recipients uint256 sInternalCreated = sOriginalToSInternal(sOriginalCreated); distributeLoans(msg.sender, mintAmount, sInternalCreated); emit Transfer(address(0), msg.sender, mintAmount); } /** * @notice Sender redeems rTokens in exchange for the underlying asset * @dev Withdraw equal amount of initially supplied underlying assets * @param redeemTo Destination address to send the redeemed tokens to * @param redeemAmount The number of rTokens to redeem into underlying */ function redeemInternal(address redeemTo, uint256 redeemAmount) internal { Account storage account = accounts[msg.sender]; require(redeemAmount > 0, "Redeem amount cannot be zero"); require( redeemAmount <= account.rAmount, "Not enough balance to redeem" ); redeemAndRecollectLoans(msg.sender, redeemAmount); // update Account r balances and global statistics account.rAmount = account.rAmount.sub(redeemAmount); totalSupply = totalSupply.sub(redeemAmount); // transfer the token back require(token.transfer(redeemTo, redeemAmount), "token transfer failed"); emit Transfer(msg.sender, address(0), redeemAmount); } /** * @dev Create a new Hat * @param recipients List of beneficial recipients * * @param proportions Relative proportions of benefits received by the recipients */ function createHatInternal( address[] memory recipients, uint32[] memory proportions ) internal returns (uint256 hatID) { uint256 i; require(recipients.length > 0, "Invalid hat: at least one recipient"); require(recipients.length <= MAX_NUM_HAT_RECIPIENTS, "Invalild hat: maximum number of recipients reached"); require( recipients.length == proportions.length, "Invalid hat: length not matching" ); // normalize the proportions // safemath is not used here, because: // proportions are uint32, there is no overflow concern uint256 totalProportions = 0; for (i = 0; i < recipients.length; ++i) { require( proportions[i] > 0, "Invalid hat: proportion should be larger than 0" ); require(recipients[i] != address(0), "Invalid hat: recipient should not be 0x0"); // don't panic, no safemath, look above comment totalProportions += uint256(proportions[i]); } for (i = 0; i < proportions.length; ++i) { proportions[i] = uint32( // don't panic, no safemath, look above comment (uint256(proportions[i]) * uint256(PROPORTION_BASE)) / totalProportions ); } hatID = hats.push(Hat(recipients, proportions)) - 1; emit HatCreated(hatID); } /** * @dev Change the hat for `owner` * @param owner Account owner * @param hatID The id of the Hat */ function changeHatInternal(address owner, uint256 hatID) internal { require(hatID == SELF_HAT_ID || hatID < hats.length, "Invalid hat ID"); Account storage account = accounts[owner]; uint256 oldHatID = account.hatID; HatStatsStored storage oldHatStats = hatStats[oldHatID]; HatStatsStored storage newHatStats = hatStats[hatID]; if (account.rAmount > 0) { uint256 sInternalEstimated = estimateAndRecollectLoans(owner, account.rAmount); account.hatID = hatID; distributeLoans(owner, account.rAmount, sInternalEstimated); } else { account.hatID = hatID; } oldHatStats.useCount -= 1; newHatStats.useCount += 1; emit HatChanged(owner, oldHatID, hatID); } /** * @dev Get interest payable of the account */ function getInterestPayableOf(Account storage account) internal view returns (uint256) { uint256 rGross = sInternalToR(account.sInternalAmount); if (rGross > (account.lDebt.add(account.rInterest))) { // don't panic, the condition guarantees that safemath is not needed return rGross - account.lDebt - account.rInterest; } else { // no interest accumulated yet or even negative interest rate!? return 0; } } /** * @dev Distribute the incoming tokens to the recipients as loans. * The tokens are immediately invested into the saving strategy and * add to the sAmount of the recipient account. * Recipient also inherits the owner's hat if it does already have one. * @param owner Owner account address * @param rAmount rToken amount being loaned to the recipients * @param sInternalAmount Amount of saving assets (internal amount) being given to the recipients */ function distributeLoans( address owner, uint256 rAmount, uint256 sInternalAmount ) internal { Account storage account = accounts[owner]; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; uint256 i; if (hat.recipients.length > 0) { uint256 rLeft = rAmount; uint256 sInternalLeft = sInternalAmount; for (i = 0; i < hat.proportions.length; ++i) { Account storage recipientAccount = accounts[hat.recipients[i]]; bool isLastRecipient = i == (hat.proportions.length - 1); // calculate the loan amount of the recipient uint256 lDebtRecipient = isLastRecipient ? rLeft : (rAmount.mul(hat.proportions[i])) / PROPORTION_BASE; // distribute the loan to the recipient account.lRecipients[hat.recipients[i]] = account.lRecipients[hat.recipients[i]] .add(lDebtRecipient); recipientAccount.lDebt = recipientAccount.lDebt .add(lDebtRecipient); // remaining value adjustments rLeft = gentleSub(rLeft, lDebtRecipient); // calculate the savings holdings of the recipient uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft : (sInternalAmount.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.sInternalAmount = recipientAccount.sInternalAmount .add(sInternalAmountRecipient); // remaining value adjustments sInternalLeft = gentleSub(sInternalLeft, sInternalAmountRecipient); _updateLoanStats(owner, hat.recipients[i], account.hatID, true, lDebtRecipient, sInternalAmountRecipient); } } else { // Account uses the zero/self hat, give all interest to the owner account.lDebt = account.lDebt.add(rAmount); account.sInternalAmount = account.sInternalAmount .add(sInternalAmount); _updateLoanStats(owner, owner, account.hatID, true, rAmount, sInternalAmount); } } /** * @dev Recollect loans from the recipients for further distribution * without actually redeeming the saving assets * @param owner Owner account address * @param rAmount rToken amount neeeds to be recollected from the recipients * by giving back estimated amount of saving assets * @return Estimated amount of saving assets (internal) needs to recollected */ function estimateAndRecollectLoans(address owner, uint256 rAmount) internal returns (uint256 sInternalEstimated) { // accrue interest so estimate is up to date require(ias.accrueInterest(), "accrueInterest failed"); sInternalEstimated = rToSInternal(rAmount); recollectLoans(owner, rAmount); } /** * @dev Recollect loans from the recipients for further distribution * by redeeming the saving assets in `rAmount` * @param owner Owner account address * @param rAmount rToken amount neeeds to be recollected from the recipients * by redeeming equivalent value of the saving assets * @return Amount of saving assets redeemed for rAmount of tokens. */ function redeemAndRecollectLoans(address owner, uint256 rAmount) internal { uint256 sOriginalBurned = ias.redeemUnderlying(rAmount); sOriginalToSInternal(sOriginalBurned); recollectLoans(owner, rAmount); // update global stats if (savingAssetOrignalAmount > sOriginalBurned) { savingAssetOrignalAmount -= sOriginalBurned; } else { savingAssetOrignalAmount = 0; } } /** * @dev Recollect loan from the recipients * @param owner Owner address * @param rAmount rToken amount of debt to be collected from the recipients */ function recollectLoans( address owner, uint256 rAmount ) internal { Account storage account = accounts[owner]; Hat storage hat = hats[account.hatID == SELF_HAT_ID ? 0 : account.hatID]; // interest part of the balance is not debt // hence maximum amount debt to be collected is: uint256 debtToCollect = gentleSub(account.rAmount, account.rInterest); // only a portion of debt needs to be collected if (debtToCollect > rAmount) { debtToCollect = rAmount; } uint256 sInternalToCollect = rToSInternal(debtToCollect); if (hat.recipients.length > 0) { uint256 rLeft = 0; uint256 sInternalLeft = 0; uint256 i; // adjust recipients' debt and savings rLeft = debtToCollect; sInternalLeft = sInternalToCollect; for (i = 0; i < hat.proportions.length; ++i) { Account storage recipientAccount = accounts[hat.recipients[i]]; bool isLastRecipient = i == (hat.proportions.length - 1); // calulate loans to be collected from the recipient uint256 lDebtRecipient = isLastRecipient ? rLeft : (debtToCollect.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.lDebt = gentleSub( recipientAccount.lDebt, lDebtRecipient); account.lRecipients[hat.recipients[i]] = gentleSub( account.lRecipients[hat.recipients[i]], lDebtRecipient); // loans leftover adjustments rLeft = gentleSub(rLeft, lDebtRecipient); // calculate savings to be collected from the recipient uint256 sInternalAmountRecipient = isLastRecipient ? sInternalLeft : (sInternalToCollect.mul(hat.proportions[i])) / PROPORTION_BASE; recipientAccount.sInternalAmount = gentleSub( recipientAccount.sInternalAmount, sInternalAmountRecipient); // savings leftover adjustments sInternalLeft = gentleSub(sInternalLeft, sInternalAmountRecipient); adjustRInterest(recipientAccount); _updateLoanStats(owner, hat.recipients[i], account.hatID, false, lDebtRecipient, sInternalAmountRecipient); } } else { // Account uses the zero hat, recollect interests from the owner // collect debt from self hat account.lDebt = gentleSub(account.lDebt, debtToCollect); // collect savings account.sInternalAmount = gentleSub(account.sInternalAmount, sInternalToCollect); adjustRInterest(account); _updateLoanStats(owner, owner, account.hatID, false, debtToCollect, sInternalToCollect); } // debt-free portion of internal savings needs to be collected too if (rAmount > debtToCollect) { sInternalToCollect = rToSInternal(rAmount - debtToCollect); account.sInternalAmount = gentleSub(account.sInternalAmount, sInternalToCollect); adjustRInterest(account); } } /** * @dev pay interest to the owner * @param owner Account owner address */ function payInterestInternal(address owner) internal { Account storage account = accounts[owner]; AccountStatsStored storage stats = accountStats[owner]; require(ias.accrueInterest(), "accrueInterest failed"); uint256 interestAmount = getInterestPayableOf(account); if (interestAmount > 0) { stats.cumulativeInterest = stats .cumulativeInterest .add(interestAmount); account.rInterest = account.rInterest.add(interestAmount); account.rAmount = account.rAmount.add(interestAmount); totalSupply = totalSupply.add(interestAmount); emit InterestPaid(owner, interestAmount); emit Transfer(address(0), owner, interestAmount); } } function _updateLoanStats( address owner, address recipient, uint256 hatID, bool isDistribution, uint256 redeemableAmount, uint256 sInternalAmount) private { HatStatsStored storage hatStats = hatStats[hatID]; emit LoansTransferred(owner, recipient, hatID, isDistribution, redeemableAmount, sInternalAmount); if (isDistribution) { hatStats.totalLoans = hatStats.totalLoans.add(redeemableAmount); hatStats.totalInternalSavings = hatStats.totalInternalSavings .add(sInternalAmount); } else { hatStats.totalLoans = gentleSub(hatStats.totalLoans, redeemableAmount); hatStats.totalInternalSavings = gentleSub( hatStats.totalInternalSavings, sInternalAmount); } } function _isContract(address addr) private view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } /** * @dev Gently subtract b from a without revert * * Due to the use of integer arithmatic, imprecision may cause a tiny * amount to be off when substracting the otherwise precise proportions. */ function gentleSub(uint256 a, uint256 b) private pure returns (uint256) { if (a < b) return 0; else return a - b; } /// @dev convert internal savings amount to redeemable amount function sInternalToR(uint256 sInternalAmount) private view returns (uint256 rAmount) { // - rGross is in underlying(redeemable) asset unit // - Both ias.exchangeRateStored and savingAssetConversionRate are scaled by 1e18 // they should cancel out // - Formula: // savingsOriginalAmount = sInternalAmount / savingAssetConversionRate // rGross = savingAssetOrignalAmount * ias.exchangeRateStored // => return sInternalAmount .mul(ias.exchangeRateStored()) .div(savingAssetConversionRate); } /// @dev convert redeemable amount to internal savings amount function rToSInternal(uint256 rAmount) private view returns (uint256 sInternalAmount) { return rAmount .mul(savingAssetConversionRate) .div(ias.exchangeRateStored()); } /// @dev convert original savings amount to redeemable amount function sOriginalToR(uint sOriginalAmount) private view returns (uint256 sInternalAmount) { return sOriginalAmount .mul(ias.exchangeRateStored()) .div(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE); } // @dev convert from original savings amount to internal savings amount function sOriginalToSInternal(uint sOriginalAmount) private view returns (uint256 sInternalAmount) { // savingAssetConversionRate is scaled by 1e18 return sOriginalAmount .mul(savingAssetConversionRate) .div(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE); } // @dev convert from internal savings amount to original savings amount function sInternalToSOriginal(uint sInternalAmount) private view returns (uint256 sOriginalAmount) { // savingAssetConversionRate is scaled by 1e18 return sInternalAmount .mul(ALLOCATION_STRATEGY_EXCHANGE_RATE_SCALE) .div(savingAssetConversionRate); } // @dev adjust rInterest value // if savings are transferred, rInterest should be also adjusted function adjustRInterest(Account storage account) private { uint256 rGross = sInternalToR(account.sInternalAmount); if (account.rInterest > rGross - account.lDebt) { account.rInterest = rGross - account.lDebt; } } /// @dev IRToken.mintFor implementation function mintFor(uint256 mintAmount, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // Call DAI.permit - this will allow this contract to pull DAI from user & will fail if not valid signature // permit required each time??? daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); // This won't be reached if signature is incorrect. // Should there be a check on mintAmount? mintInternal(mintAmount, holder); payInterestInternal(holder); return true; } /// @dev IRToken.mintForWithSelectedHat implementation function mintForWithSelectedHat(uint256 mintAmount, uint256 hatID, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // Call DAI.permit - this will allow this contract to pull DAI from user & will fail if not valid signature // Check if permit required??? daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); // This won't be reached if signature is incorrect. // Should there be a check on mintAmount? changeHatInternal(holder, hatID); mintInternal(mintAmount, holder); payInterestInternal(holder); return true; } /** * @dev Sender supplies assets into the market and receives rTokens in exchange * @dev Invest into underlying assets immediately * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint256 mintAmount, address holder) internal { require( token.allowance(holder, address(this)) >= mintAmount, "Not enough allowance" ); Account storage account = accounts[holder]; // create saving assets require(token.transferFrom(holder, address(this), mintAmount), "token transfer failed"); require(token.approve(address(ias), mintAmount), "token approve failed"); uint256 sOriginalCreated = ias.investUnderlying(mintAmount); // update global and account r balances totalSupply = totalSupply.add(mintAmount); account.rAmount = account.rAmount.add(mintAmount); // update global stats savingAssetOrignalAmount = savingAssetOrignalAmount.add(sOriginalCreated); // distribute saving assets as loans to recipients uint256 sInternalCreated = sOriginalToSInternal(sOriginalCreated); distributeLoans(holder, mintAmount, sInternalCreated); emit Transfer(address(0), holder, mintAmount); } /** * @dev IRToken.mintWithNewHat implementation */ // Error: CompileError: InternalCompilerError: Stack too deep when compiling inline assembly: Variable dataEnd is 1 slot(s) too deep inside the stack. /* Initial attempt - function mintForWithNewHat(uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions, uint256 hatID, address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) Attempt to use arrays - function mintForWithNewHat( uint256 mintAmount, address[] calldata recipients, uint32[] calldata proportions, address[] calldata holderSpender, uint256[] calldata amountnonceExpiry, bool allowed, uint8 v, bytes32 [] calldata sigData ) external nonReentrant returns (bool) { require(spender == address(this), "Spender must be this contract."); Dai daiToken = Dai(ias.underlying()); // daiToken.permit(holderSpender[0], holderSpender[1], nonceExpiry[0], nonceExpiry[1], allowed, v, r, s); // daiToken.permit(holder, spender, nonce, expiry, allowed, v, r, s); uint256 hatID = createHatInternal(recipients, proportions); //changeHatInternal(holder, hatID); changeHatInternal(holderSpender[0], hatID); mintInternal(mintAmount, holderSpender[0]); //mintInternal(mintAmount, holder); payInterestInternal(holderSpender[0]); //payInterestInternal(holder); return true; } */ }
adjust rInterest value if savings are transferred, rInterest should be also adjusted
function adjustRInterest(Account storage account) private { uint256 rGross = sInternalToR(account.sInternalAmount); if (account.rInterest > rGross - account.lDebt) { account.rInterest = rGross - account.lDebt; } }
5,495,296
pragma solidity ^0.4.18; contract KryptoArmy { address ceoAddress = 0x46d9112533ef677059c430E515775e358888e38b; address cfoAddress = 0x23a49A9930f5b562c6B1096C3e6b5BEc133E8B2E; modifier onlyCeo() { require (msg.sender == ceoAddress); _; } // Struct for Army struct Army { string name; // The name of the army (invented by the user) string idArmy; // The id of the army (USA for United States) uint experiencePoints; // The experience points of the army, we will use this to handle uint256 price; // The cost of the Army in Wei (1 ETH = 1000000000000000000 Wei) uint attackBonus; // The attack bonus for the soldiers (from 0 to 10) uint defenseBonus; // The defense bonus for the soldiers (from 0 to 10) bool isForSale; // User is selling this army, it can be purchase on the marketplace address ownerAddress; // The address of the owner uint soldiersCount; // The count of all the soldiers in this army } Army[] armies; // Struct for Battles struct Battle { uint idArmyAttacking; // The id of the army attacking uint idArmyDefensing; // The id of the army defensing uint idArmyVictorious; // The id of the winning army } Battle[] battles; // Mapping army mapping (address => uint) public ownerToArmy; // Which army does this address own mapping (address => uint) public ownerArmyCount; // How many armies own this address? // Mapping weapons to army mapping (uint => uint) public armyDronesCount; mapping (uint => uint) public armyPlanesCount; mapping (uint => uint) public armyHelicoptersCount; mapping (uint => uint) public armyTanksCount; mapping (uint => uint) public armyAircraftCarriersCount; mapping (uint => uint) public armySubmarinesCount; mapping (uint => uint) public armySatelitesCount; // Mapping battles mapping (uint => uint) public armyCountBattlesWon; mapping (uint => uint) public armyCountBattlesLost; // This function creates a new army and saves it in the array with its parameters function _createArmy(string _name, string _idArmy, uint _price, uint _attackBonus, uint _defenseBonus) public onlyCeo { // We add the new army to the list and save the id in a variable armies.push(Army(_name, _idArmy, 0, _price, _attackBonus, _defenseBonus, true, address(this), 0)); } // We use this function to purchase an army with Metamask function purchaseArmy(uint _armyId) public payable { // We verify that the value paid is equal to the cost of the army require(msg.value == armies[_armyId].price); require(msg.value > 0); // We check if this army is owned by another user if(armies[_armyId].ownerAddress != address(this)) { uint CommissionOwnerValue = msg.value - (msg.value / 10); armies[_armyId].ownerAddress.transfer(CommissionOwnerValue); } // We modify the ownership of the army _ownershipArmy(_armyId); } // Function to purchase a soldier function purchaseSoldiers(uint _armyId, uint _countSoldiers) public payable { // Check that message value > 0 require(msg.value > 0); uint256 msgValue = msg.value; if(msgValue == 1000000000000000 && _countSoldiers == 1) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 8000000000000000 && _countSoldiers == 10) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 65000000000000000 && _countSoldiers == 100) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } else if(msgValue == 500000000000000000 && _countSoldiers == 1000) { // Increment soldiers count in army armies[_armyId].soldiersCount = armies[_armyId].soldiersCount + _countSoldiers; } } // Payable function to purchase weapons function purchaseWeapons(uint _armyId, uint _weaponId, uint _bonusAttack, uint _bonusDefense ) public payable { // Check that message value > 0 uint isValid = 0; uint256 msgValue = msg.value; if(msgValue == 10000000000000000 && _weaponId == 0) { armyDronesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 1) { armyPlanesCount[_armyId]++; isValid = 1; } else if(msgValue == 25000000000000000 && _weaponId == 2) { armyHelicoptersCount[_armyId]++; isValid = 1; } else if(msgValue == 45000000000000000 && _weaponId == 3) { armyTanksCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 4) { armyAircraftCarriersCount[_armyId]++; isValid = 1; } else if(msgValue == 100000000000000000 && _weaponId == 5) { armySubmarinesCount[_armyId]++; isValid = 1; } else if(msgValue == 120000000000000000 && _weaponId == 6) { armySatelitesCount[_armyId]++; isValid = 1; } // We check if the data has been verified as valid if(isValid == 1) { armies[_armyId].attackBonus = armies[_armyId].attackBonus + _bonusAttack; armies[_armyId].defenseBonus = armies[_armyId].defenseBonus + _bonusDefense; } } // We use this function to affect an army to an address (when someone purchase an army) function _ownershipArmy(uint armyId) private { // We check if the sender already own an army require (ownerArmyCount[msg.sender] == 0); // If this army has alreay been purchased we verify that the owner put it on sale require(armies[armyId].isForSale == true); // We check one more time that the price paid is the price of the army require(armies[armyId].price == msg.value); // We decrement the army count for the previous owner (in case a user is selling army on marketplace) ownerArmyCount[armies[armyId].ownerAddress]--; // We set the new army owner armies[armyId].ownerAddress = msg.sender; ownerToArmy[msg.sender] = armyId; // We increment the army count for this address ownerArmyCount[msg.sender]++; // Send event for new ownership armies[armyId].isForSale = false; } // We use this function to start a new battle function startNewBattle(uint _idArmyAttacking, uint _idArmyDefensing, uint _randomIndicatorAttack, uint _randomIndicatorDefense) public returns(uint) { // We verify that the army attacking is the army of msg.sender require (armies[_idArmyAttacking].ownerAddress == msg.sender); // Get details for army attacking uint ScoreAttack = armies[_idArmyAttacking].attackBonus * (armies[_idArmyAttacking].soldiersCount/3) + armies[_idArmyAttacking].soldiersCount + _randomIndicatorAttack; // Get details for army defending uint ScoreDefense = armies[_idArmyAttacking].defenseBonus * (armies[_idArmyDefensing].soldiersCount/2) + armies[_idArmyDefensing].soldiersCount + _randomIndicatorDefense; uint VictoriousArmy; uint ExperiencePointsGained; if(ScoreDefense >= ScoreAttack) { VictoriousArmy = _idArmyDefensing; ExperiencePointsGained = armies[_idArmyAttacking].attackBonus + 2; armies[_idArmyDefensing].experiencePoints = armies[_idArmyDefensing].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyDefensing]++; armyCountBattlesLost[_idArmyAttacking]++; } else { VictoriousArmy = _idArmyAttacking; ExperiencePointsGained = armies[_idArmyDefensing].defenseBonus + 2; armies[_idArmyAttacking].experiencePoints = armies[_idArmyAttacking].experiencePoints + ExperiencePointsGained; // Increment mapping battles won armyCountBattlesWon[_idArmyAttacking]++; armyCountBattlesLost[_idArmyDefensing]++; } // We add the new battle to the blockchain and save its id in a variable battles.push(Battle(_idArmyAttacking, _idArmyDefensing, VictoriousArmy)); // Send event return (VictoriousArmy); } // Owner can sell army function ownerSellArmy(uint _armyId, uint256 _amount) public { // We close the function if the user calling this function doesn't own the army require (armies[_armyId].ownerAddress == msg.sender); require (_amount > 0); require (armies[_armyId].isForSale == false); armies[_armyId].isForSale = true; armies[_armyId].price = _amount; } // Owner remove army from marketplace function ownerCancelArmyMarketplace(uint _armyId) public { require (armies[_armyId].ownerAddress == msg.sender); require (armies[_armyId].isForSale == true); armies[_armyId].isForSale = false; } // Function to return all the value of an army function getArmyFullData(uint armyId) public view returns(string, string, uint, uint256, uint, uint, bool) { string storage ArmyName = armies[armyId].name; string storage ArmyId = armies[armyId].idArmy; uint ArmyExperiencePoints = armies[armyId].experiencePoints; uint256 ArmyPrice = armies[armyId].price; uint ArmyAttack = armies[armyId].attackBonus; uint ArmyDefense = armies[armyId].defenseBonus; bool ArmyIsForSale = armies[armyId].isForSale; return (ArmyName, ArmyId, ArmyExperiencePoints, ArmyPrice, ArmyAttack, ArmyDefense, ArmyIsForSale); } // Function to return the owner of the army function getArmyOwner(uint armyId) public view returns(address, bool) { return (armies[armyId].ownerAddress, armies[armyId].isForSale); } // Function to return the owner of the army function getSenderArmyDetails() public view returns(uint, string) { uint ArmyId = ownerToArmy[msg.sender]; string storage ArmyName = armies[ArmyId].name; return (ArmyId, ArmyName); } // Function to return the owner army count function getSenderArmyCount() public view returns(uint) { uint ArmiesCount = ownerArmyCount[msg.sender]; return (ArmiesCount); } // Function to return the soldiers count of an army function getArmySoldiersCount(uint armyId) public view returns(uint) { uint SoldiersCount = armies[armyId].soldiersCount; return (SoldiersCount); } // Return an array with the weapons of the army function getWeaponsArmy1(uint armyId) public view returns(uint, uint, uint, uint) { uint CountDrones = armyDronesCount[armyId]; uint CountPlanes = armyPlanesCount[armyId]; uint CountHelicopters = armyHelicoptersCount[armyId]; uint CountTanks = armyTanksCount[armyId]; return (CountDrones, CountPlanes, CountHelicopters, CountTanks); } function getWeaponsArmy2(uint armyId) public view returns(uint, uint, uint) { uint CountAircraftCarriers = armyAircraftCarriersCount[armyId]; uint CountSubmarines = armySubmarinesCount[armyId]; uint CountSatelites = armySatelitesCount[armyId]; return (CountAircraftCarriers, CountSubmarines, CountSatelites); } // Retrieve count battles won function getArmyBattles(uint _armyId) public view returns(uint, uint) { return (armyCountBattlesWon[_armyId], armyCountBattlesLost[_armyId]); } // Retrieve the details of a battle function getDetailsBattles(uint battleId) public view returns(uint, uint, uint, string, string) { return (battles[battleId].idArmyAttacking, battles[battleId].idArmyDefensing, battles[battleId].idArmyVictorious, armies[battles[battleId].idArmyAttacking].idArmy, armies[battles[battleId].idArmyDefensing].idArmy); } // Get battles count function getBattlesCount() public view returns(uint) { return (battles.length); } // To withdraw fund from this contract function withdraw(uint amount, uint who) public onlyCeo returns(bool) { require(amount <= this.balance); if(who == 0) { ceoAddress.transfer(amount); } else { cfoAddress.transfer(amount); } return true; } // Initial function to create the 100 armies with their attributes function KryptoArmy() public onlyCeo { // 1. USA _createArmy("United States", "USA", 550000000000000000, 8, 9); // 2. North Korea _createArmy("North Korea", "NK", 500000000000000000, 10, 5); // 3. Russia _createArmy("Russia", "RUS", 450000000000000000, 8, 7); // 4. China _createArmy("China", "CHN", 450000000000000000, 7, 8); // 5. Japan _createArmy("Japan", "JPN", 420000000000000000, 7, 7); // 6. France _createArmy("France", "FRA", 400000000000000000, 6, 8); // 7. Germany _createArmy("Germany", "GER", 400000000000000000, 7, 6); // 8. India _createArmy("India", "IND", 400000000000000000, 7, 6); // 9. United Kingdom _createArmy("United Kingdom", "UK", 350000000000000000, 5, 7); // 10. South Korea _createArmy("South Korea", "SK", 350000000000000000, 6, 6); // 11. Turkey _createArmy("Turkey", "TUR", 300000000000000000, 7, 4); // 12. Italy //_createArmy("Italy", "ITA", 280000000000000000, 5, 5); } }
Retrieve the details of a battle
function getDetailsBattles(uint battleId) public view returns(uint, uint, uint, string, string) { return (battles[battleId].idArmyAttacking, battles[battleId].idArmyDefensing, battles[battleId].idArmyVictorious, armies[battles[battleId].idArmyAttacking].idArmy, armies[battles[battleId].idArmyDefensing].idArmy); }
13,131,605
./full_match/11155111/0xa10f35f707FA2bc5f72453acfD1560CDd024b430/sources/contracts/CrowdFunding.sol
call is used to receive 'amount' ether to provided payable address
function donateToCampaign(uint id_) external payable { Campaign storage campaign = allCampaigns[id_]; require(sent, "Failed to send Ether"); campaign.collectedAmount += msg.value; campaign.donaters.push(msg.sender); campaign.donations.push(msg.value); }
3,786,828
./full_match/10200/0xc5Be8Bf53755a41C2385e7Aa86f6a9E28746f466/sources/project_/contracts/SBCToken.sol
Allows to transfer any locked token from this contract. Only admin can call this method. _token address of the token, if it is not provided (0x00..00), native coins will be transferred. _to address that will receive the locked tokens from this contract./
function claimTokens(address _token, address _to) external onlyAdmin { _claimValues(_token, _to); }
3,784,747
// SPDX-License-Identifier: MIT pragma solidity >=0.8; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./CreepzInterfaces.sol"; // /$$$$$$ /$$ /$$ // /$$__ $$ | $$ | $$ // | $$ \__/ /$$$$$$ | $$$$$$$ /$$$$$$ | $$ /$$$$$$ // | $$ |____ $$| $$__ $$ |____ $$| $$ |____ $$ // | $$ /$$$$$$$| $$ \ $$ /$$$$$$$| $$ /$$$$$$$ // | $$ $$ /$$__ $$| $$ | $$ /$$__ $$| $$ /$$__ $$ // | $$$$$$/| $$$$$$$| $$$$$$$/| $$$$$$$| $$| $$$$$$$ // \______/ \_______/|_______/ \_______/|__/ \_______/ // /$$$$$$ // /$$__ $$ // | $$ \__/ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ // | $$ /$$__ $$ /$$__ $$ /$$__ $$ /$$__ $$|____ /$$/ // | $$ | $$ \__/| $$$$$$$$| $$$$$$$$| $$ \ $$ /$$$$/ // | $$ $$| $$ | $$_____/| $$_____/| $$ | $$ /$$__/ // | $$$$$$/| $$ | $$$$$$$| $$$$$$$| $$$$$$$/ /$$$$$$$$ // \______/ |__/ \_______/ \_______/| $$____/ |________/ // /$$$$$$$ /$$ | $$ // | $$__ $$ | $$ | $$ // | $$ \ $$ /$$$$$$ /$$$$$$ | $$ |__/ // | $$$$$$$//$$__ $$ /$$__ $$| $$ // | $$____/| $$ \ $$| $$ \ $$| $$ // | $$ | $$ | $$| $$ | $$| $$ // | $$ | $$$$$$/| $$$$$$/| $$ // |__/ \______/ \______/ |__/ // catch us at https://cabalacreepz.co contract CreepzAggregatorPool is Context, Initializable, IERC721Receiver { struct Stakeholder { uint256 totalStaked; uint256 unclaimed; uint256 TWAP; } uint256 public totalStaked; uint256 public totalTaxReceived; uint256 public totalClaimable; uint256 public lastClaimedTimestamp; uint256 public TWAP; mapping(address => Stakeholder) public stakes; address public immutable allowedOrigin; ILoomi public immutable Loomi; ICreepz public immutable Creepz; IMegaShapeshifter public immutable MegaShapeshifter; modifier onlyFromAllowedOrigin() { require(_msgSender() == allowedOrigin); _; } constructor( address origin, address loomiAddress, address creepzAddress, address megaShapeshifterAddress ) { // set the allowed origin to the aggregator address allowedOrigin = origin; Loomi = ILoomi(loomiAddress); Creepz = ICreepz(creepzAddress); MegaShapeshifter = IMegaShapeshifter(megaShapeshifterAddress); } function initialize() external initializer { // allow the aggregator to flash stake creepz & unstake mega Creepz.setApprovalForAll(allowedOrigin, true); MegaShapeshifter.setApprovalForAll(allowedOrigin, true); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { return this.onERC721Received.selector; } function updateTWAPForTransfer( address from, address to, uint256 changes ) external onlyFromAllowedOrigin { // update the from's stats stakes[from].unclaimed += (TWAP - stakes[from].TWAP) * stakes[from].totalStaked; stakes[from].totalStaked -= changes; stakes[from].TWAP = TWAP; // update the to's stats stakes[to].unclaimed += (TWAP - stakes[to].TWAP) * stakes[to].totalStaked; stakes[to].totalStaked += changes; stakes[to].TWAP = TWAP; } function claimTaxFromCreepz( uint256 creepzId, uint256 reward, uint256 commissionRate, uint256 creepzNonce, bytes calldata creepzSignature ) external onlyFromAllowedOrigin { // need at least one shapeshifter staked to distribute tax require(totalStaked > 0); // claim the tax from creepz MegaShapeshifter.claimTax(reward, creepzNonce, creepzId, creepzSignature); // deduct the commission from the total tax received reward = (reward * commissionRate) / 1e4; // update the pool's stats TWAP += reward / totalStaked; totalTaxReceived += reward; totalClaimable += reward; // update the last claimed timestamp lastClaimedTimestamp = block.timestamp; } function claimTaxFromPool(address stakeholder) external onlyFromAllowedOrigin { // calculate the total reward amount uint256 totalReward = stakes[stakeholder].unclaimed + (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked; // update the pool's stats totalClaimable -= totalReward; // update the stakeholder's stats stakes[stakeholder].unclaimed = 0; stakes[stakeholder].TWAP = TWAP; // transfer the total reward to the stakeholder Loomi.transferLoomi(stakeholder, totalReward); } function stakeShapeshifters(address stakeholder, uint256[6] calldata shapeTypes) external onlyFromAllowedOrigin { // update the pool's stats totalStaked += shapeTypes[5]; // update the stakeholder's stats stakes[stakeholder].unclaimed += (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked; stakes[stakeholder].totalStaked += shapeTypes[5]; stakes[stakeholder].TWAP = TWAP; } function unstakeShapeshifters(address stakeholder, uint256[6] calldata shapeTypes) external onlyFromAllowedOrigin { // update the pool's stats totalStaked -= shapeTypes[5]; // update the stakeholder's stats stakes[stakeholder].unclaimed += (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked; stakes[stakeholder].totalStaked -= shapeTypes[5]; stakes[stakeholder].TWAP = TWAP; } function unstakeMegashapeshifter(address stakeholder, uint256 megaId) external onlyFromAllowedOrigin { // calculate the inefficiency score require(stakes[stakeholder].totalStaked * MegaShapeshifter.balanceOf(address(this)) >= totalStaked); // update the pool's stats totalStaked -= 5; // update the stakeholder's stats stakes[stakeholder].unclaimed += (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked; stakes[stakeholder].totalStaked -= 5; stakes[stakeholder].TWAP = TWAP; // transfer the mega shapeshifter MegaShapeshifter.transferFrom(address(this), stakeholder, megaId); } function mutateMegaShapeshifter( uint256[] calldata shapeIds, uint256 shapeType, bytes calldata signature ) external { // mutate by calling the MegaShapeshifter contract MegaShapeshifter.mutate(shapeIds, shapeType, signature); } function withdrawPoolEarnOwner(address withdrawAddress) external onlyFromAllowedOrigin { // get the loomi balance of the contract uint256 loomiBalance = Loomi.getUserBalance(address(this)); // transfer the commission received to the withdraw address Loomi.transferLoomi(withdrawAddress, loomiBalance - totalClaimable); } } // 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) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !Address.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.8; interface ILoomi { function approve(address spender, uint256 amount) external; function transferLoomi(address to, uint256 amount) external; function getUserBalance(address user) external view returns (uint256); } interface ICreepz { function setApprovalForAll(address to, bool approved) external; function transferFrom( address from, address to, uint256 tokenId ) external; } interface IShapeshifter { function transferFrom( address from, address to, uint256 tokenId ) external; } interface IMegaShapeshifter { function setApprovalForAll(address to, bool approved) external; function claimTax( uint256 amount, uint256 nonce, uint256 creepzId, bytes calldata signature ) external; function mutate( uint256[] memory shapeIds, uint256 shapeType, bytes calldata signature ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function balanceOf(address account) external view returns (uint256); } // 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 pool's stats update the stakeholder's stats
function unstakeShapeshifters(address stakeholder, uint256[6] calldata shapeTypes) external onlyFromAllowedOrigin { totalStaked -= shapeTypes[5]; stakes[stakeholder].unclaimed += (TWAP - stakes[stakeholder].TWAP) * stakes[stakeholder].totalStaked; stakes[stakeholder].totalStaked -= shapeTypes[5]; stakes[stakeholder].TWAP = TWAP; }
5,725,204
./full_match/43113/0x9B21EB2E30D8320c3c1b8d8465284D78E58cB971/sources/contracts/PriceOracle/PriceOracleV1.sol
abs(price - anchorPrice) / anchorPrice can't underflow Given greaterThan check above, price >= anchorPrice so can't underflow.
function calculateSwing(Exp memory anchorPrice, Exp memory price) internal pure returns (Error, Exp memory) { Exp memory numerator; Error err; if (greaterThanExp(anchorPrice, price)) { (err, numerator) = subExp(anchorPrice, price); assert(err == Error.NO_ERROR); (err, numerator) = subExp(price, anchorPrice); assert(err == Error.NO_ERROR); } return divExp(numerator, anchorPrice); }
7,198,170
/// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma abicoder v2; import "./interfaces/IHypervisor.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; /// @title UniProxy /// @notice Proxy contract for hypervisor positions management contract UniProxy is ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using SignedSafeMath for int256; mapping(address => Position) public positions; address public owner; bool public freeDeposit = false; bool public twapCheck = false; uint32 public twapInterval = 1 hours; uint256 public depositDelta = 1010; uint256 public deltaScale = 1000; /// must be a power of 10 uint256 public priceThreshold = 100; uint256 constant MAX_INT = 2**256 - 1; struct Position { uint8 version; // 1->3 proxy 3 transfers, 2-> proxy two transfers, 3-> proxy no transfers mapping(address=>bool) list; // whitelist certain accounts for freedeposit bool twapOverride; // force twap check for hypervisor instance uint32 twapInterval; // override global twap uint256 priceThreshold; // custom price threshold bool depositOverride; // force custom deposit constraints uint256 deposit0Max; uint256 deposit1Max; uint256 maxTotalSupply; bool freeDeposit; // override global freeDepsoit } /// events event PositionAdded(address, uint8); event CustomDeposit(address, uint256, uint256, uint256); event PriceThresholdSet(uint256 _priceThreshold); event DepositDeltaSet(uint256 _depositDelta); event DeltaScaleSet(uint256 _deltaScale); event TwapIntervalSet(uint32 _twapInterval); event TwapOverrideSet(address pos, bool twapOverride, uint32 _twapInterval); event DepositFreeToggled(); event DepositOverrideToggled(address pos); event DepositFreeOverrideToggled(address pos); event TwapToggled(); event ListAppended(address pos, address[] listed); event ListRemoved(address pos, address listed); constructor() { owner = msg.sender; } modifier onlyAddedPosition(address pos) { Position storage p = positions[pos]; require(p.version != 0, "not added"); _; } /// @notice Add the hypervisor position /// @param pos Address of the hypervisor /// @param version Type of hypervisor function addPosition(address pos, uint8 version) external onlyOwner { Position storage p = positions[pos]; require(p.version == 0, 'already added'); require(version > 0, 'version < 1'); p.version = version; IHypervisor(pos).token0().safeApprove(pos, MAX_INT); IHypervisor(pos).token1().safeApprove(pos, MAX_INT); emit PositionAdded(pos, version); } /// @notice Deposit into the given position /// @param deposit0 Amount of token0 to deposit /// @param deposit1 Amount of token1 to deposit /// @param to Address to receive liquidity tokens /// @param pos Hypervisor Address /// @return shares Amount of liquidity tokens received function deposit( uint256 deposit0, uint256 deposit1, address to, address pos ) nonReentrant external onlyAddedPosition(pos) returns (uint256 shares) { require(to != address(0), "to should be non-zero"); Position storage p = positions[pos]; if (p.version < 3) { /// requires asset transfer to proxy if (deposit0 != 0) { IHypervisor(pos).token0().safeTransferFrom(msg.sender, address(this), deposit0); } if (deposit1 != 0) { IHypervisor(pos).token1().safeTransferFrom(msg.sender, address(this), deposit1); } } if (twapCheck || p.twapOverride) { /// check twap checkPriceChange( pos, (p.twapOverride ? p.twapInterval : twapInterval), (p.twapOverride ? p.priceThreshold : priceThreshold) ); } if (!freeDeposit && !p.list[msg.sender] && !p.freeDeposit) { // freeDeposit off and hypervisor msg.sender not on list if (deposit0 > 0) { (uint256 test1Min, uint256 test1Max) = getDepositAmount(pos, address(IHypervisor(pos).token0()), deposit0); require(deposit1 >= test1Min && deposit1 <= test1Max, "Improper ratio"); } if (deposit1 > 0) { (uint256 test0Min, uint256 test0Max) = getDepositAmount(pos, address(IHypervisor(pos).token1()), deposit1); require(deposit0 >= test0Min && deposit0 <= test0Max, "Improper ratio"); } } if (p.depositOverride) { if (p.deposit0Max > 0) { require(deposit0 <= p.deposit0Max, "token0 exceeds"); } if (p.deposit1Max > 0) { require(deposit1 <= p.deposit1Max, "token1 exceeds"); } } if (p.version < 3) { if (p.version < 2) { /// requires lp token transfer from proxy to msg.sender shares = IHypervisor(pos).deposit(deposit0, deposit1, address(this)); IHypervisor(pos).transfer(to, shares); } else{ /// transfer lp tokens direct to msg.sender shares = IHypervisor(pos).deposit(deposit0, deposit1, msg.sender); } } else { /// transfer lp tokens direct to msg.sender shares = IHypervisor(pos).deposit(deposit0, deposit1, msg.sender, msg.sender); } if (p.depositOverride) { require(IHypervisor(pos).totalSupply() <= p.maxTotalSupply, "supply exceeds"); } } /// @notice Get the amount of token to deposit for the given amount of pair token /// @param pos Hypervisor Address /// @param token Address of token to deposit /// @param _deposit Amount of token to deposit /// @return amountStart Minimum amounts of the pair token to deposit /// @return amountEnd Maximum amounts of the pair token to deposit function getDepositAmount( address pos, address token, uint256 _deposit ) public view returns (uint256 amountStart, uint256 amountEnd) { require(token == address(IHypervisor(pos).token0()) || token == address(IHypervisor(pos).token1()), "token mistmatch"); require(_deposit > 0, "deposits can't be zero"); (uint256 total0, uint256 total1) = IHypervisor(pos).getTotalAmounts(); if (IHypervisor(pos).totalSupply() == 0 || total0 == 0 || total1 == 0) { amountStart = 0; if (token == address(IHypervisor(pos).token0())) { amountEnd = IHypervisor(pos).deposit1Max(); } else { amountEnd = IHypervisor(pos).deposit0Max(); } } else { uint256 ratioStart; uint256 ratioEnd; if (token == address(IHypervisor(pos).token0())) { ratioStart = FullMath.mulDiv(total0.mul(depositDelta), 1e18, total1.mul(deltaScale)); ratioEnd = FullMath.mulDiv(total0.mul(deltaScale), 1e18, total1.mul(depositDelta)); } else { ratioStart = FullMath.mulDiv(total1.mul(depositDelta), 1e18, total0.mul(deltaScale)); ratioEnd = FullMath.mulDiv(total1.mul(deltaScale), 1e18, total0.mul(depositDelta)); } amountStart = FullMath.mulDiv(_deposit, 1e18, ratioStart); amountEnd = FullMath.mulDiv(_deposit, 1e18, ratioEnd); } } /// @notice Check if the price change overflows or not based on given twap and threshold in the hypervisor /// @param pos Hypervisor Address /// @param _twapInterval Time intervals /// @param _priceThreshold Price Threshold /// @return price Current price function checkPriceChange( address pos, uint32 _twapInterval, uint256 _priceThreshold ) public view returns (uint256 price) { uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(IHypervisor(pos).currentTick()); price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), 1e18, 2**(96 * 2)); uint160 sqrtPriceBefore = getSqrtTwapX96(pos, _twapInterval); uint256 priceBefore = FullMath.mulDiv(uint256(sqrtPriceBefore).mul(uint256(sqrtPriceBefore)), 1e18, 2**(96 * 2)); if (price.mul(100).div(priceBefore) > _priceThreshold || priceBefore.mul(100).div(price) > _priceThreshold) revert("Price change Overflow"); } /// @notice Get the sqrt price before the given interval /// @param pos Hypervisor Address /// @param _twapInterval Time intervals /// @return sqrtPriceX96 Sqrt price before interval function getSqrtTwapX96(address pos, uint32 _twapInterval) public view returns (uint160 sqrtPriceX96) { if (_twapInterval == 0) { /// return the current price if _twapInterval == 0 (sqrtPriceX96, , , , , , ) = IHypervisor(pos).pool().slot0(); } else { uint32[] memory secondsAgos = new uint32[](2); secondsAgos[0] = _twapInterval; /// from (before) secondsAgos[1] = 0; /// to (now) (int56[] memory tickCumulatives, ) = IHypervisor(pos).pool().observe(secondsAgos); /// tick(imprecise as it's an integer) to price sqrtPriceX96 = TickMath.getSqrtRatioAtTick( int24((tickCumulatives[1] - tickCumulatives[0]) / _twapInterval) ); } } /// @param _priceThreshold Price Threshold function setPriceThreshold(uint256 _priceThreshold) external onlyOwner { priceThreshold = _priceThreshold; emit PriceThresholdSet(_priceThreshold); } /// @param _depositDelta Number to calculate deposit ratio function setDepositDelta(uint256 _depositDelta) external onlyOwner { depositDelta = _depositDelta; emit DepositDeltaSet(_depositDelta); } /// @param _deltaScale Number to calculate deposit ratio function setDeltaScale(uint256 _deltaScale) external onlyOwner { deltaScale = _deltaScale; emit DeltaScaleSet(_deltaScale); } /// @param pos Hypervisor address /// @param deposit0Max Amount of maximum deposit amounts of token0 /// @param deposit1Max Amount of maximum deposit amounts of token1 /// @param maxTotalSupply Maximum total suppoy of hypervisor function customDeposit( address pos, uint256 deposit0Max, uint256 deposit1Max, uint256 maxTotalSupply ) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; p.deposit0Max = deposit0Max; p.deposit1Max = deposit1Max; p.maxTotalSupply = maxTotalSupply; emit CustomDeposit(pos, deposit0Max, deposit1Max, maxTotalSupply); } /// @notice Toogle free deposit function toggleDepositFree() external onlyOwner { freeDeposit = !freeDeposit; emit DepositFreeToggled(); } /// @notice Toggle deposit override /// @param pos Hypervisor Address function toggleDepositOverride(address pos) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; p.depositOverride = !p.depositOverride; emit DepositOverrideToggled(pos); } /// @notice Toggle free deposit of the given hypervisor /// @param pos Hypervisor Address function toggleDepositFreeOverride(address pos) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; p.freeDeposit = !p.freeDeposit; emit DepositFreeOverrideToggled(pos); } /// @param _twapInterval Time intervals function setTwapInterval(uint32 _twapInterval) external onlyOwner { twapInterval = _twapInterval; emit TwapIntervalSet(_twapInterval); } /// @param pos Hypervisor Address /// @param twapOverride Twap Override /// @param _twapInterval Time Intervals function setTwapOverride(address pos, bool twapOverride, uint32 _twapInterval) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; p.twapOverride = twapOverride; p.twapInterval = _twapInterval; emit TwapOverrideSet(pos, twapOverride, _twapInterval); } /// @notice Twap Toggle function toggleTwap() external onlyOwner { twapCheck = !twapCheck; emit TwapToggled(); } /// @notice Append whitelist to hypervisor /// @param pos Hypervisor Address /// @param listed Address array to add in whitelist function appendList(address pos, address[] memory listed) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; for (uint8 i; i < listed.length; i++) { p.list[listed[i]] = true; } emit ListAppended(pos, listed); } /// @notice Remove address from whitelist /// @param pos Hypervisor Address /// @param listed Address to remove from whitelist function removeListed(address pos, address listed) external onlyOwner onlyAddedPosition(pos) { Position storage p = positions[pos]; p.list[listed] = false; emit ListRemoved(pos, listed); } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0), "newOwner should be non-zero"); owner = newOwner; } modifier onlyOwner { require(msg.sender == owner, "only owner"); _; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; interface IHypervisor { function deposit( uint256, uint256, address ) external returns (uint256); function deposit( uint256, uint256, address, address ) external returns (uint256); function withdraw( uint256, address, address ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity, int256 amountMin, uint160 sqrtPriceLimitX96 ) external; function addBaseLiquidity( uint256 amount0, uint256 amount1 ) external; function addLimitLiquidity( uint256 amount0, uint256 amount1 ) external; function pullLiquidity(uint256 shares) external returns( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function compound() external returns( uint128 baseToken0Owed, uint128 baseToken1Owed, uint128 limitToken0Owed, uint128 limitToken1Owed ); function whitelisted() external view returns (bool); function pool() external view returns (IUniswapV3Pool); function currentTick() external view returns (int24 tick); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function deposit0Max() external view returns (uint256); function deposit1Max() external view returns (uint256); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256 ); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function removeListed(address listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
_deltaScale Number to calculate deposit ratio
function setDeltaScale(uint256 _deltaScale) external onlyOwner { deltaScale = _deltaScale; emit DeltaScaleSet(_deltaScale); }
1,364,583
./full_match/1/0x9f6a8939d5f45d3C51bAF58dadaB04D75b8Da4C1/sources/contracts/MAHAXLocker.sol
Calculate total voting power at some point in the past point The point (bias/slope) to start search from t Time to calculate the total voting power at return Total voting power at that time
{ Point memory lastPoint = point; uint256 tI = (lastPoint.ts / WEEK) * WEEK; function balanceOfAtNFT(uint256 _tokenId, uint256 _block) external view returns (uint256) } function _supplyAt(Point memory point, uint256 t) internal view returns (uint256) for (uint256 i = 0; i < 255; ++i) { tI += WEEK; int128 dSlope = 0; if (tI > t) { tI = t; dSlope = slopeChanges[tI]; } lastPoint.bias -= lastPoint.slope * int128(int256(tI - lastPoint.ts)); if (tI == t) { break; } lastPoint.slope += dSlope; lastPoint.ts = tI; } function balanceOfAtNFT(uint256 _tokenId, uint256 _block) external view returns (uint256) } function _supplyAt(Point memory point, uint256 t) internal view returns (uint256) for (uint256 i = 0; i < 255; ++i) { tI += WEEK; int128 dSlope = 0; if (tI > t) { tI = t; dSlope = slopeChanges[tI]; } lastPoint.bias -= lastPoint.slope * int128(int256(tI - lastPoint.ts)); if (tI == t) { break; } lastPoint.slope += dSlope; lastPoint.ts = tI; } } else { function balanceOfAtNFT(uint256 _tokenId, uint256 _block) external view returns (uint256) } function _supplyAt(Point memory point, uint256 t) internal view returns (uint256) for (uint256 i = 0; i < 255; ++i) { tI += WEEK; int128 dSlope = 0; if (tI > t) { tI = t; dSlope = slopeChanges[tI]; } lastPoint.bias -= lastPoint.slope * int128(int256(tI - lastPoint.ts)); if (tI == t) { break; } lastPoint.slope += dSlope; lastPoint.ts = tI; } if (lastPoint.bias < 0) { lastPoint.bias = 0; } return uint256(uint128(lastPoint.bias)); }
2,959,402
pragma solidity ^0.5.2; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Marketplace.sol"; /** *@dev A interface for shop holder to set product information and prices * in data marketplace */ contract Shop is Ownable { using SafeMath for uint256; struct data { string mamRoot; string metadata; uint256 time; } struct dataInfo { uint256 time; bool valid; } struct timePeriod { uint256 start; uint256 end; } address public supervisor; uint256 public singlePurchasePrice; uint256 public subscribePerTimePrice; uint256 public timeUnit = 1 hours; bool public openForPurchase = false; /* TODO: make it a linked list */ data[] public dataList; mapping (string => dataInfo) private dataAvailability; mapping (address => timePeriod) private subscriptionList; modifier supervised { assert(msg.sender == supervisor); _; } modifier subscriptionValid(address account) { require( subscriptionList[account].start != 0 && subscriptionList[account].end >= block.timestamp, "Subscription invalid" ); _; } modifier isPurchasable { require(openForPurchase); _; } modifier isDataExist(string memory mamRoot) { require(dataAvailability[mamRoot].valid); _; } event Purchase( bytes32 indexed scriptHash, address indexed buyer, string mamRoot ); event Subscribe( address indexed buyer, uint256 expirationTime ); constructor (address owner) public { transferOwnership(owner); supervisor = msg.sender; } /** *@dev Enable buyer to purchase data from shop */ function setPurchaseOpen() onlyOwner external { openForPurchase = true; } /** *@dev Disable buyer to purchase data from shop */ function setPurchaseClose() onlyOwner external { openForPurchase = false; } /** *@dev Use this method to set single purchase price of the data *@param price The price of data */ function setSinglePurchasePrice( uint256 price ) onlyOwner public { singlePurchasePrice = price; } /** *@dev Use this method to set subscribe per time unit price of the data *@param price The price of subscribe per time unit */ function setSubscribePrice( uint256 price ) onlyOwner public { subscribePerTimePrice = price; } /** *@dev An api for user to get dataList size, since user cannot get it directly */ function getDataListSize() public view returns (uint256) { return dataList.length; } function getDataAvailability( string memory mamRoot ) public view returns (bool) { return dataAvailability[mamRoot].valid; } /** *@dev Shop holder can use this method to set the availability of data *@param mamRoot The specified data root *@param isValid The availability of data */ function setDataAvailability( string memory mamRoot, bool isValid ) onlyOwner public { dataAvailability[mamRoot].valid = isValid; } /** *@dev Shop holder can use this method to add new data onto their shop *@param mamRoot The specified data root *@param metadata The metadata of the data */ function updateData( string memory mamRoot, string memory metadata ) onlyOwner public { require(bytes(mamRoot).length == 81); dataList.push( data({ mamRoot: mamRoot, metadata: metadata, time: block.timestamp }) ); dataAvailability[mamRoot].time = block.timestamp; dataAvailability[mamRoot].valid = true; } /** *@dev Method used to get metadata in data list *@param index The index of data in the dataList */ function getData( uint256 index ) public view returns (string memory, string memory) { return (dataList[index].mamRoot, dataList[index].metadata); } /** *@dev An internel purchase function only used by supervisor */ function purchase( address buyer, string memory mamRoot, uint256 amount, bytes32 scriptHash ) supervised isPurchasable isDataExist(mamRoot) public { require( amount == singlePurchasePrice, "Payment amount is not correct" ); emit Purchase(scriptHash, buyer, mamRoot); } /** *@dev An internel subscribe function only used by supervisor */ function subscribe( address buyer, uint256 timeInHours, uint256 amount ) supervised isPurchasable public { uint256 totalPayAmount = subscribePerTimePrice.mul(timeInHours); uint256 totalTime = timeInHours.mul(timeUnit); require(amount == totalPayAmount); subscriptionList[buyer].start = block.timestamp; subscriptionList[buyer].end = subscriptionList[buyer].start.add(totalTime); emit Subscribe(buyer, subscriptionList[buyer].end); } /** *@dev An internel function to redeem data by valid subscription */ function getSubscribedData( address buyer, string memory mamRoot, bytes32 scriptHash ) supervised subscriptionValid(buyer) isPurchasable isDataExist(mamRoot) public { require( subscriptionList[buyer].start <= dataAvailability[mamRoot].time && subscriptionList[buyer].end >= dataAvailability[mamRoot].time, "Data not available for this subscription" ); emit Purchase(scriptHash, buyer, mamRoot); } /** *@dev The method for shop holder to call after data transfer is finished, * it will set transaction status to FULFILLED */ function txFinalize( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address buyer, bytes32 scriptHash, bytes32 txHash ) onlyOwner public { Marketplace(supervisor).fulfillPurchase( sigV, sigR, sigS, buyer, scriptHash, txHash ); } /** *@dev Internal function for supervisor to destruct the shop */ function kill() supervised public { address payable payAddress = address(uint160(owner())); selfdestruct(payAddress); } }
An internel purchase function only used by supervisor/
function purchase( address buyer, string memory mamRoot, uint256 amount, bytes32 scriptHash ) supervised isPurchasable isDataExist(mamRoot) public { require( amount == singlePurchasePrice, "Payment amount is not correct" ); emit Purchase(scriptHash, buyer, mamRoot); }
12,617,036
./full_match/80001/0x0c839b43E80c5a587Ae042DB165D2DbEAAEE6d13/sources/contracts/Copy_Roll.sol
Settle bet. Function can only be called by fulfillRandomness function, which in turn can only be called by Chainlink VRF. Validation checks. Fetch bet parameters into local variables (to save gas). Do a roll by taking a modulo of random number. Win amount if gambler wins this bet Roll reward if gambler loses this bet Actual win amount by gambler. Determine dice outcome. For small modulo games, check the outcome against a bit mask. For larger modulos, check inclusion into half-open interval. Send prize to winner, add ROLL reward to loser, and update house profit. miner.addReward(gambler, rollReward);
function settleBet(bytes32 requestId, uint randomNumber) internal nonReentrant { uint betId = betMap[requestId]; Bet storage bet = bets[betId]; uint amount = bet.amount; require(amount > 0, "Bet does not exist"); require(bet.isSettled == false, "Bet is settled already"); uint modulo = bet.modulo; uint rollUnder = bet.rollUnder; address payable gambler = bet.gambler; uint outcome = randomNumber % modulo; uint possibleWinAmount = getWinAmount(amount, modulo, rollUnder); uint rollReward = getRollReward(amount, modulo, rollUnder); uint winAmount = 0; if (modulo <= MAX_MASK_MODULO) { if ((2 ** outcome) & bet.mask != 0) { winAmount = possibleWinAmount; rollReward = 0; } if (outcome < rollUnder) { winAmount = possibleWinAmount; rollReward = 0; } } bet.winAmount = winAmount; bet.outcome = outcome; if (winAmount > 0) { houseProfit -= int(winAmount - amount); gambler.transfer(winAmount); } else { houseProfit += int(amount); } }
5,621,577
pragma solidity 0.5.10; import "../interfaces/IBlockRewardAuRa.sol"; import "../interfaces/IERC677.sol"; import "../interfaces/IRandomAuRa.sol"; import "../interfaces/IStakingAuRa.sol"; import "../interfaces/IValidatorSetAuRa.sol"; import "../upgradeability/UpgradeableOwned.sol"; import "../libs/SafeMath.sol"; contract Sacrifice { constructor(address payable _recipient) public payable { selfdestruct(_recipient); } } /// @dev Generates and distributes rewards according to the logic and formulas described in the POSDAO white paper. contract BlockRewardAuRaBase is UpgradeableOwned, IBlockRewardAuRa { using SafeMath for uint256; // =============================================== Storage ======================================================== // WARNING: since this contract is upgradeable, do not remove // existing storage variables, do not change their order, // and do not change their types! mapping(address => uint256[]) internal _epochsPoolGotRewardFor; mapping(address => bool) internal _ercToNativeBridgeAllowed; address[] internal _ercToNativeBridgesAllowed; IBlockRewardAuRa internal _prevBlockRewardContract; bool internal _queueERInitialized; uint256 internal _queueERFirst; uint256 internal _queueERLast; struct ExtraReceiverQueue { uint256 amount; address bridge; address receiver; } mapping(uint256 => ExtraReceiverQueue) internal _queueER; // Reserved storage space to allow for layout changes in the future. uint256[25] private ______gapForInternal; /// @dev A number of blocks produced by the specified validator during the specified staking epoch /// (beginning from the block when the `finalizeChange` function is called until the latest block /// of the staking epoch. The results are used by the `_distributeRewards` function to track /// each validator's downtime (when a validator's node is not running and doesn't produce blocks). /// While the validator is banned, the block producing statistics is not accumulated for them. mapping(uint256 => mapping(address => uint256)) public blocksCreated; /// @dev The current bridge's total fee/reward amount of native coins accumulated by /// the `addBridgeNativeRewardReceivers` function. uint256 public bridgeNativeReward; /// @dev The reward amount to be distributed in native coins among participants (the validator and their /// delegators) of the specified pool (mining address) for the specified staking epoch. mapping(uint256 => mapping(address => uint256)) public epochPoolNativeReward; /// @dev The total amount of native coins minted for the specified address /// by the `erc-to-native` bridges through the `addExtraReceiver` function. mapping(address => uint256) public mintedForAccount; /// @dev The amount of native coins minted at the specified block for the specified /// address by the `erc-to-native` bridges through the `addExtraReceiver` function. mapping(address => mapping(uint256 => uint256)) public mintedForAccountInBlock; /// @dev The total amount of native coins minted at the specified block /// by the `erc-to-native` bridges through the `addExtraReceiver` function. mapping(uint256 => uint256) public mintedInBlock; /// @dev The total amount of native coins minted by the /// `erc-to-native` bridges through the `addExtraReceiver` function. uint256 public mintedTotally; /// @dev The total amount of native coins minted by the specified /// `erc-to-native` bridge through the `addExtraReceiver` function. mapping(address => uint256) public mintedTotallyByBridge; /// @dev The total reward amount in native coins which is not yet distributed among pools. uint256 public nativeRewardUndistributed; /// @dev The total amount staked into the specified pool (mining address) /// before the specified staking epoch. Filled by the `_snapshotPoolStakeAmounts` function. mapping(uint256 => mapping(address => uint256)) public snapshotPoolTotalStakeAmount; /// @dev The validator's amount staked into the specified pool (mining address) /// before the specified staking epoch. Filled by the `_snapshotPoolStakeAmounts` function. mapping(uint256 => mapping(address => uint256)) public snapshotPoolValidatorStakeAmount; /// @dev The validator's min reward percent which was actual at the specified staking epoch. /// This percent is taken from the VALIDATOR_MIN_REWARD_PERCENT constant and saved for every staking epoch /// by the `reward` function. Used by the `delegatorShare` and `validatorShare` public getters. /// This is needed to have an ability to change validator's min reward percent in the VALIDATOR_MIN_REWARD_PERCENT /// constant by upgrading the contract. mapping(uint256 => uint256) public validatorMinRewardPercent; /// @dev The address of the `ValidatorSet` contract. IValidatorSetAuRa public validatorSetContract; // Reserved storage space to allow for layout changes in the future. uint256[25] private ______gapForPublic; // ================================================ Events ======================================================== /// @dev Emitted by the `addExtraReceiver` function. /// @param amount The amount of native coins which must be minted for the `receiver` by the `erc-to-native` /// `bridge` with the `reward` function. /// @param receiver The address for which the `amount` of native coins must be minted. /// @param bridge The bridge address which called the `addExtraReceiver` function. event AddedReceiver(uint256 amount, address indexed receiver, address indexed bridge); /// @dev Emitted by the `addBridgeNativeRewardReceivers` function. /// @param amount The fee/reward amount in native coins passed to the /// `addBridgeNativeRewardReceivers` function as a parameter. /// @param cumulativeAmount The value of `bridgeNativeReward` state variable /// after adding the `amount` to it. /// @param bridge The bridge address which called the `addBridgeNativeRewardReceivers` function. event BridgeNativeRewardAdded(uint256 amount, uint256 cumulativeAmount, address indexed bridge); /// @dev Emitted by the `_mintNativeCoins` function which is called by the `reward` function. /// This event is only used by the unit tests because the `reward` function cannot emit events. /// @param receivers The array of receiver addresses for which native coins are minted. The length of this /// array is equal to the length of the `rewards` array. /// @param rewards The array of amounts minted for the relevant `receivers`. The length of this array /// is equal to the length of the `receivers` array. event MintedNative(address[] receivers, uint256[] rewards); // ============================================== Modifiers ======================================================= /// @dev Ensures the caller is the `erc-to-native` bridge contract address. modifier onlyErcToNativeBridge { require(_ercToNativeBridgeAllowed[msg.sender]); _; } /// @dev Ensures the `initialize` function was called before. modifier onlyInitialized { require(isInitialized()); _; } /// @dev Ensures the caller is the SYSTEM_ADDRESS. /// See https://openethereum.github.io/wiki/Block-Reward-Contract.html modifier onlySystem { require(msg.sender == 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE); _; } /// @dev Ensures the caller is the StakingAuRa contract address. modifier onlyStakingContract() { require(msg.sender == address(validatorSetContract.stakingContract())); _; } /// @dev Ensures the caller is the ValidatorSetAuRa contract address. modifier onlyValidatorSetContract() { require(msg.sender == address(validatorSetContract)); _; } // =============================================== Setters ======================================================== /// @dev Fallback function. Prevents direct sending native coins to this contract. function () payable external { revert(); } /// @dev An alias for `addBridgeNativeRewardReceivers` /// (for backward compatibility with the previous bridge contract). function addBridgeNativeFeeReceivers(uint256 _amount) external { addBridgeNativeRewardReceivers(_amount); } /// @dev Called by the `erc-to-native` bridge contract when a portion of the bridge fee/reward should be minted /// and distributed to participants (validators and their delegators) in native coins. The specified amount /// is used by the `_distributeRewards` function. /// @param _amount The fee/reward amount distributed to participants. function addBridgeNativeRewardReceivers(uint256 _amount) public onlyErcToNativeBridge { require(_amount != 0); bridgeNativeReward = bridgeNativeReward.add(_amount); emit BridgeNativeRewardAdded(_amount, bridgeNativeReward, msg.sender); } /// @dev Called by the `erc-to-native` bridge contract when the bridge needs to mint a specified amount of native /// coins for a specified address using the `reward` function. /// @param _amount The amount of native coins which must be minted for the `_receiver` address. /// @param _receiver The address for which the `_amount` of native coins must be minted. function addExtraReceiver(uint256 _amount, address _receiver) external onlyErcToNativeBridge { require(_amount != 0); require(_queueERInitialized); _enqueueExtraReceiver(_amount, _receiver, msg.sender); emit AddedReceiver(_amount, _receiver, msg.sender); } /// @dev Called by the `ValidatorSetAuRa.finalizeChange` to clear the values in /// the `blocksCreated` mapping for the current staking epoch and a new validator set. function clearBlocksCreated() external onlyValidatorSetContract { IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); address[] memory validators = validatorSetContract.getValidators(); for (uint256 i = 0; i < validators.length; i++) { blocksCreated[stakingEpoch][validators[i]] = 0; } } /// @dev Initializes the contract at network startup. /// Can only be called by the constructor of the `InitializerAuRa` contract or owner. /// @param _validatorSet The address of the `ValidatorSetAuRa` contract. /// @param _prevBlockReward The address of the previous BlockReward contract /// (for statistics migration purposes). function initialize(address _validatorSet, address _prevBlockReward) external { require(_getCurrentBlockNumber() == 0 || msg.sender == _admin()); require(!isInitialized()); require(_validatorSet != address(0)); validatorSetContract = IValidatorSetAuRa(_validatorSet); validatorMinRewardPercent[0] = VALIDATOR_MIN_REWARD_PERCENT; _prevBlockRewardContract = IBlockRewardAuRa(_prevBlockReward); } /// @dev Called by the validator's node when producing and closing a block, /// see https://openethereum.github.io/wiki/Block-Reward-Contract.html. /// This function performs all of the automatic operations needed for controlling numbers revealing by validators, /// accumulating block producing statistics, starting a new staking epoch, snapshotting staking amounts /// for the upcoming staking epoch, rewards distributing at the end of a staking epoch, and minting /// native coins needed for the `erc-to-native` bridge. function reward(address[] calldata benefactors, uint16[] calldata kind) external onlySystem returns(address[] memory receiversNative, uint256[] memory rewardsNative) { if (benefactors.length != kind.length || benefactors.length != 1 || kind[0] != 0) { return (new address[](0), new uint256[](0)); } // Check if the validator is existed if (validatorSetContract == IValidatorSetAuRa(0) || !validatorSetContract.isValidator(benefactors[0])) { return (new address[](0), new uint256[](0)); } // Check the current validators at the end of each collection round whether // they revealed their numbers, and remove a validator as a malicious if needed IRandomAuRa(validatorSetContract.randomContract()).onFinishCollectRound(); // Initialize the extra receivers queue if (!_queueERInitialized) { _queueERFirst = 1; _queueERLast = 0; _queueERInitialized = true; // Migrate minting statistics for erc-to-native bridges // from the `_prevBlockRewardContract` _migrateMintingStatistics(); } uint256 bridgeQueueLimit = 100; IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); uint256 stakingEpochEndBlock = stakingContract.stakingEpochEndBlock(); uint256 nativeTotalRewardAmount = 0; if (validatorSetContract.validatorSetApplyBlock() != 0) { if (stakingEpoch != 0 && !validatorSetContract.isValidatorBanned(benefactors[0])) { // Accumulate blocks producing statistics for each of the // active validators during the current staking epoch. This // statistics is used by the `_distributeRewards` function blocksCreated[stakingEpoch][benefactors[0]]++; } } if (_getCurrentBlockNumber() == stakingEpochEndBlock) { // Distribute rewards among validator pools if (stakingEpoch != 0) { nativeTotalRewardAmount = _distributeRewards( stakingContract, stakingEpoch, stakingEpochEndBlock ); } // Choose new validators validatorSetContract.newValidatorSet(); // Snapshot total amounts staked into the pools uint256 i; uint256 nextStakingEpoch = stakingEpoch + 1; address[] memory miningAddresses; // We need to remember the total staked amounts for the pending addresses // for the possible case when these pending addresses are finalized // by the `ValidatorSetAuRa.finalizeChange` function and thus become validators miningAddresses = validatorSetContract.getPendingValidators(); for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } // We need to remember the total staked amounts for the current validators // for the possible case when these validators continue to be validators // throughout the upcoming staking epoch (if the new validator set is not finalized // for some reason) miningAddresses = validatorSetContract.getValidators(); for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } // We need to remember the total staked amounts for the addresses currently // being finalized but not yet finalized (i.e. the `InitiateChange` event is emitted // for them but not yet handled by validator nodes thus the `ValidatorSetAuRa.finalizeChange` // function is not called yet) for the possible case when these addresses finally // become validators on the upcoming staking epoch (miningAddresses, ) = validatorSetContract.validatorsToBeFinalized(); for (i = 0; i < miningAddresses.length; i++) { _snapshotPoolStakeAmounts(stakingContract, nextStakingEpoch, miningAddresses[i]); } // Remember validator's min reward percent for the upcoming staking epoch validatorMinRewardPercent[nextStakingEpoch] = VALIDATOR_MIN_REWARD_PERCENT; // Pause bridge for this block bridgeQueueLimit = 0; } // Mint native coins if needed return _mintNativeCoins(nativeTotalRewardAmount, bridgeQueueLimit); } /// @dev Sets the array of `erc-to-native` bridge addresses which are allowed to call some of the functions with /// the `onlyErcToNativeBridge` modifier. This setter can only be called by the `owner`. /// @param _bridgesAllowed The array of bridge addresses. function setErcToNativeBridgesAllowed(address[] calldata _bridgesAllowed) external onlyOwner onlyInitialized { uint256 i; for (i = 0; i < _ercToNativeBridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_ercToNativeBridgesAllowed[i]] = false; } _ercToNativeBridgesAllowed = _bridgesAllowed; for (i = 0; i < _bridgesAllowed.length; i++) { _ercToNativeBridgeAllowed[_bridgesAllowed[i]] = true; } } // =============================================== Getters ======================================================== /// @dev Returns an identifier for the bridge contract so that the latter could /// ensure it works with the BlockReward contract. function blockRewardContractId() public pure returns(bytes4) { return 0x0d35a7ca; // bytes4(keccak256("blockReward")) } /// @dev Returns an array of epoch numbers for which the specified pool (mining address) /// got a non-zero reward. function epochsPoolGotRewardFor(address _miningAddress) public view returns(uint256[] memory) { return _epochsPoolGotRewardFor[_miningAddress]; } /// @dev Returns the array of `erc-to-native` bridge addresses set by the `setErcToNativeBridgesAllowed` setter. function ercToNativeBridgesAllowed() public view returns(address[] memory) { return _ercToNativeBridgesAllowed; } /// @dev Returns the current size of the address queue created by the `addExtraReceiver` function. function extraReceiversQueueSize() public view returns(uint256) { return _queueERLast + 1 - _queueERFirst; } /// @dev Returns a boolean flag indicating if the `initialize` function has been called. function isInitialized() public view returns(bool) { return validatorSetContract != IValidatorSetAuRa(0); } /// @dev Prevents sending tokens directly to the `BlockRewardAuRa` contract address /// by the `ERC677BridgeTokenRewardable.transferAndCall` function. function onTokenTransfer(address, uint256, bytes memory) public pure returns(bool) { revert(); } /// @dev Returns an array of epoch numbers for which the specified staker /// can claim a reward from the specified pool by the `StakingAuRa.claimReward` function. /// @param _poolStakingAddress The pool staking address. /// @param _staker The staker's address (delegator or candidate/validator). function epochsToClaimRewardFrom( address _poolStakingAddress, address _staker ) public view returns(uint256[] memory epochsToClaimFrom) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); bool isDelegator = _poolStakingAddress != _staker; uint256 firstEpoch; uint256 lastEpoch; if (isDelegator) { firstEpoch = stakingContract.stakeFirstEpoch(_poolStakingAddress, _staker); if (firstEpoch == 0) { return (new uint256[](0)); } lastEpoch = stakingContract.stakeLastEpoch(_poolStakingAddress, _staker); } uint256[] storage epochs = _epochsPoolGotRewardFor[miningAddress]; uint256 length = epochs.length; uint256[] memory tmp = new uint256[](length); uint256 tmpLength = 0; uint256 i; for (i = 0; i < length; i++) { uint256 epoch = epochs[i]; if (isDelegator) { if (epoch < firstEpoch) { // If the delegator staked for the first time before // the `epoch`, skip this staking epoch continue; } if (lastEpoch <= epoch && lastEpoch != 0) { // If the delegator withdrew all their stake before the `epoch`, // don't check this and following epochs since it makes no sense break; } } if (!stakingContract.rewardWasTaken(_poolStakingAddress, _staker, epoch)) { tmp[tmpLength++] = epoch; } } epochsToClaimFrom = new uint256[](tmpLength); for (i = 0; i < tmpLength; i++) { epochsToClaimFrom[i] = tmp[i]; } } /// @dev Returns the reward coefficient for the specified validator. The given value should be divided by 10000 /// to get the value of the reward percent (since EVM doesn't support float values). If the specified staking /// address is an address of a candidate that is not about to be a validator on the current staking epoch /// the potentially possible reward coefficient is returned. /// @param _stakingAddress The staking address of the validator/candidate /// pool for which the getter must return the coefficient. function validatorRewardPercent(address _stakingAddress) public view returns(uint256) { IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); uint256 stakingEpoch = stakingContract.stakingEpoch(); if (stakingEpoch == 0) { // No one gets a reward for the initial staking epoch, so we return zero return 0; } address miningAddress = validatorSetContract.miningByStakingAddress(_stakingAddress); if (validatorSetContract.isValidator(miningAddress)) { // For the validator we return the coefficient based on // snapshotted total amounts return validatorShare( stakingEpoch, snapshotPoolValidatorStakeAmount[stakingEpoch][miningAddress], snapshotPoolTotalStakeAmount[stakingEpoch][miningAddress], REWARD_PERCENT_MULTIPLIER ); } if (validatorSetContract.validatorSetApplyBlock() == 0) { // For the candidate that is about to be a validator on the current // staking epoch we return the coefficient based on snapshotted total amounts address[] memory miningAddresses; uint256 i; miningAddresses = validatorSetContract.getPendingValidators(); for (i = 0; i < miningAddresses.length; i++) { if (miningAddress == miningAddresses[i]) { return validatorShare( stakingEpoch, snapshotPoolValidatorStakeAmount[stakingEpoch][miningAddress], snapshotPoolTotalStakeAmount[stakingEpoch][miningAddress], REWARD_PERCENT_MULTIPLIER ); } } (miningAddresses, ) = validatorSetContract.validatorsToBeFinalized(); for (i = 0; i < miningAddresses.length; i++) { if (miningAddress == miningAddresses[i]) { return validatorShare( stakingEpoch, snapshotPoolValidatorStakeAmount[stakingEpoch][miningAddress], snapshotPoolTotalStakeAmount[stakingEpoch][miningAddress], REWARD_PERCENT_MULTIPLIER ); } } } // For the candidate that is not about to be a validator on the current staking epoch, // we return the potentially possible reward coefficient return validatorShare( stakingEpoch, stakingContract.stakeAmount(_stakingAddress, _stakingAddress), stakingContract.stakeAmountTotal(_stakingAddress), REWARD_PERCENT_MULTIPLIER ); } /// @dev Calculates delegator's share for the given pool reward amount and the specified staking epoch. /// Used by the `StakingAuRa.claimReward` function. /// @param _stakingEpoch The number of staking epoch. /// @param _delegatorStaked The amount staked by a delegator. /// @param _validatorStaked The amount staked by a validator. /// @param _totalStaked The total amount staked by a validator and their delegators. /// @param _poolReward The value of pool reward. function delegatorShare( uint256 _stakingEpoch, uint256 _delegatorStaked, uint256 _validatorStaked, uint256 _totalStaked, uint256 _poolReward ) public view returns(uint256) { if (_delegatorStaked == 0 || _validatorStaked == 0 || _totalStaked == 0) { return 0; } uint256 share = 0; uint256 delegatorsStaked = _totalStaked >= _validatorStaked ? _totalStaked - _validatorStaked : 0; uint256 validatorMinPercent = validatorMinRewardPercent[_stakingEpoch]; if (_validatorStaked * (100 - validatorMinPercent) > delegatorsStaked * validatorMinPercent) { // Validator has more than validatorMinPercent % share = _poolReward * _delegatorStaked / _totalStaked; } else { // Validator has validatorMinPercent % share = _poolReward * _delegatorStaked * (100 - validatorMinPercent) / (delegatorsStaked * 100); } return share; } /// @dev Calculates validator's share for the given pool reward amount and the specified staking epoch. /// Used by the `validatorRewardPercent` and `StakingAuRa.claimReward` functions. /// @param _stakingEpoch The number of staking epoch. /// @param _validatorStaked The amount staked by a validator. /// @param _totalStaked The total amount staked by a validator and their delegators. /// @param _poolReward The value of pool reward. function validatorShare( uint256 _stakingEpoch, uint256 _validatorStaked, uint256 _totalStaked, uint256 _poolReward ) public view returns(uint256) { if (_validatorStaked == 0 || _totalStaked == 0) { return 0; } uint256 share = 0; uint256 delegatorsStaked = _totalStaked >= _validatorStaked ? _totalStaked - _validatorStaked : 0; uint256 validatorMinPercent = validatorMinRewardPercent[_stakingEpoch]; if (_validatorStaked * (100 - validatorMinPercent) > delegatorsStaked * validatorMinPercent) { // Validator has more than validatorMinPercent % share = _poolReward * _validatorStaked / _totalStaked; } else { // Validator has validatorMinPercent % share = _poolReward * validatorMinPercent / 100; } return share; } // ============================================== Internal ======================================================== uint256 internal constant VALIDATOR_MIN_REWARD_PERCENT = 30; // 30% uint256 internal constant REWARD_PERCENT_MULTIPLIER = 1000000; function _coinInflationAmount(uint256, address[] memory) internal view returns(uint256); /// @dev Distributes rewards in native coins among pools at the latest block of a staking epoch. /// This function is called by the `_distributeRewards` function. /// @param _stakingEpoch The number of the current staking epoch. /// @param _totalRewardShareNum Numerator of the total reward share. /// @param _totalRewardShareDenom Denominator of the total reward share. /// @param _validators The array of the current validators (their mining addresses). /// @param _blocksCreatedShareNum Numerators of blockCreated share for each of the validators. /// @param _blocksCreatedShareDenom Denominator of blockCreated share. /// @return Returns the amount of native coins which need to be minted. function _distributeNativeRewards( uint256 _stakingEpoch, uint256 _totalRewardShareNum, uint256 _totalRewardShareDenom, address[] memory _validators, uint256[] memory _blocksCreatedShareNum, uint256 _blocksCreatedShareDenom ) internal returns(uint256) { uint256 totalReward = bridgeNativeReward + nativeRewardUndistributed; totalReward += _coinInflationAmount(_stakingEpoch, _validators); if (totalReward == 0) { return 0; } bridgeNativeReward = 0; uint256 rewardToDistribute = 0; uint256 distributedAmount = 0; if (_blocksCreatedShareDenom != 0 && _totalRewardShareDenom != 0) { rewardToDistribute = totalReward * _totalRewardShareNum / _totalRewardShareDenom; if (rewardToDistribute != 0) { for (uint256 i = 0; i < _validators.length; i++) { uint256 poolReward = rewardToDistribute * _blocksCreatedShareNum[i] / _blocksCreatedShareDenom; epochPoolNativeReward[_stakingEpoch][_validators[i]] = poolReward; distributedAmount += poolReward; if (poolReward != 0) { _epochsPoolGotRewardFor[_validators[i]].push(_stakingEpoch); } } } } nativeRewardUndistributed = totalReward - distributedAmount; return distributedAmount; } function _distributeTokenRewards( address, uint256, uint256, uint256, address[] memory, uint256[] memory, uint256 ) internal; /// @dev Distributes rewards among pools at the latest block of a staking epoch. /// This function is called by the `reward` function. /// @param _stakingContract The address of the StakingAuRa contract. /// @param _stakingEpoch The number of the current staking epoch. /// @param _stakingEpochEndBlock The number of the latest block of the current staking epoch. /// @return Returns the reward amount in native coins needed to be minted /// and accrued to the balance of this contract. function _distributeRewards( IStakingAuRa _stakingContract, uint256 _stakingEpoch, uint256 _stakingEpochEndBlock ) internal returns(uint256 nativeTotalRewardAmount) { address[] memory validators = validatorSetContract.getValidators(); // Determine shares uint256 totalRewardShareNum = 0; uint256 totalRewardShareDenom = 1; uint256 realFinalizeBlock = validatorSetContract.validatorSetApplyBlock(); if (realFinalizeBlock != 0) { uint256 idealFinalizeBlock = _stakingContract.stakingEpochStartBlock() + validatorSetContract.MAX_VALIDATORS()*2/3 + 1; if (realFinalizeBlock < idealFinalizeBlock) { realFinalizeBlock = idealFinalizeBlock; } totalRewardShareNum = _stakingEpochEndBlock - realFinalizeBlock + 1; totalRewardShareDenom = _stakingEpochEndBlock - idealFinalizeBlock + 1; } uint256[] memory blocksCreatedShareNum = new uint256[](validators.length); uint256 blocksCreatedShareDenom = 0; if (totalRewardShareNum != 0) { for (uint256 i = 0; i < validators.length; i++) { if ( !validatorSetContract.isValidatorBanned(validators[i]) && snapshotPoolValidatorStakeAmount[_stakingEpoch][validators[i]] != 0 ) { blocksCreatedShareNum[i] = blocksCreated[_stakingEpoch][validators[i]]; } else { blocksCreatedShareNum[i] = 0; } blocksCreatedShareDenom += blocksCreatedShareNum[i]; } } // Distribute native coins among pools nativeTotalRewardAmount = _distributeNativeRewards( _stakingEpoch, totalRewardShareNum, totalRewardShareDenom, validators, blocksCreatedShareNum, blocksCreatedShareDenom ); // Distribute ERC tokens among pools _distributeTokenRewards( address(_stakingContract), _stakingEpoch, totalRewardShareNum, totalRewardShareDenom, validators, blocksCreatedShareNum, blocksCreatedShareDenom ); } /// @dev Copies the minting statistics from the previous BlockReward contract /// for the `mintedTotally` and `mintedTotallyByBridge` getters. /// Called only once by the `reward` function. function _migrateMintingStatistics() internal { if (_prevBlockRewardContract == IBlockRewardAuRa(0)) { return; } for (uint256 i = 0; i < _ercToNativeBridgesAllowed.length; i++) { address bridge = _ercToNativeBridgesAllowed[i]; mintedTotallyByBridge[bridge] = _prevBlockRewardContract.mintedTotallyByBridge(bridge); } if (_ercToNativeBridgesAllowed.length != 0) { mintedTotally = _prevBlockRewardContract.mintedTotally(); } } /// @dev Returns the current block number. Needed mostly for unit tests. function _getCurrentBlockNumber() internal view returns(uint256) { return block.number; } /// @dev Calculates and returns inflation amount based on the specified /// staking epoch, validator set, and inflation rate. /// Used by `_coinInflationAmount` and `_distributeTokenRewards` functions. /// @param _stakingEpoch The number of the current staking epoch. /// @param _validators The array of the current validators (their mining addresses). /// @param _inflationRate Inflation rate. function _inflationAmount( uint256 _stakingEpoch, address[] memory _validators, uint256 _inflationRate ) internal view returns(uint256) { if (_inflationRate == 0) return 0; uint256 snapshotTotalStakeAmount = 0; for (uint256 i = 0; i < _validators.length; i++) { snapshotTotalStakeAmount += snapshotPoolTotalStakeAmount[_stakingEpoch][_validators[i]]; } return snapshotTotalStakeAmount * _inflationRate / 1 ether; } /// @dev Joins two native coin receiver elements into a single set and returns the result /// to the `reward` function: the first element comes from the `erc-to-native` bridge fee distribution, /// the second - from the `erc-to-native` bridge when native coins are minted for the specified addresses. /// Dequeues the addresses enqueued with the `addExtraReceiver` function by the `erc-to-native` bridge. /// Accumulates minting statistics for the `erc-to-native` bridges. /// @param _nativeTotalRewardAmount The native coins amount which should be accrued to the balance /// of this contract (as a total reward for the finished staking epoch). /// @param _queueLimit Max number of addresses which can be dequeued from the queue formed by the /// `addExtraReceiver` function. function _mintNativeCoins( uint256 _nativeTotalRewardAmount, uint256 _queueLimit ) internal returns(address[] memory receivers, uint256[] memory rewards) { uint256 extraLength = extraReceiversQueueSize(); if (extraLength > _queueLimit) { extraLength = _queueLimit; } bool totalRewardNotEmpty = _nativeTotalRewardAmount != 0; receivers = new address[](extraLength + (totalRewardNotEmpty ? 1 : 0)); rewards = new uint256[](receivers.length); for (uint256 i = 0; i < extraLength; i++) { (uint256 amount, address receiver, address bridge) = _dequeueExtraReceiver(); receivers[i] = receiver; rewards[i] = amount; _setMinted(amount, receiver, bridge); } if (totalRewardNotEmpty) { receivers[extraLength] = address(this); rewards[extraLength] = _nativeTotalRewardAmount; } emit MintedNative(receivers, rewards); return (receivers, rewards); } /// @dev Dequeues the information about the native coins receiver enqueued with the `addExtraReceiver` /// function by the `erc-to-native` bridge. This function is used by `_mintNativeCoins`. /// @return `uint256 amount` - The amount to be minted for the `receiver` address. /// `address receiver` - The address for which the `amount` is minted. /// `address bridge` - The address of the bridge contract which called the `addExtraReceiver` function. function _dequeueExtraReceiver() internal returns(uint256 amount, address receiver, address bridge) { uint256 queueFirst = _queueERFirst; uint256 queueLast = _queueERLast; if (queueLast < queueFirst) { amount = 0; receiver = address(0); bridge = address(0); } else { amount = _queueER[queueFirst].amount; receiver = _queueER[queueFirst].receiver; bridge = _queueER[queueFirst].bridge; delete _queueER[queueFirst]; _queueERFirst++; } } /// @dev Enqueues the information about the receiver of native coins which must be minted for the /// specified `erc-to-native` bridge. This function is used by the `addExtraReceiver` function. /// @param _amount The amount of native coins which must be minted for the `_receiver` address. /// @param _receiver The address for which the `_amount` of native coins must be minted. /// @param _bridge The address of the bridge contract which requested the minting of native coins. function _enqueueExtraReceiver(uint256 _amount, address _receiver, address _bridge) internal { uint256 queueLast = _queueERLast + 1; _queueER[queueLast] = ExtraReceiverQueue({ amount: _amount, bridge: _bridge, receiver: _receiver }); _queueERLast = queueLast; } /// @dev Accumulates minting statistics for the `erc-to-native` bridge. /// This function is used by the `_mintNativeCoins` function. /// @param _amount The amount minted for the `_account` address. /// @param _account The address for which the `_amount` is minted. /// @param _bridge The address of the bridge contract which called the `addExtraReceiver` function. function _setMinted(uint256 _amount, address _account, address _bridge) internal { uint256 blockNumber = _getCurrentBlockNumber(); mintedForAccountInBlock[_account][blockNumber] = _amount; mintedForAccount[_account] += _amount; mintedInBlock[blockNumber] += _amount; mintedTotallyByBridge[_bridge] += _amount; mintedTotally += _amount; } /// @dev Makes snapshots of total amount staked into the specified pool /// before the specified staking epoch. Used by the `reward` function. /// @param _stakingContract The address of the `StakingAuRa` contract. /// @param _stakingEpoch The number of upcoming staking epoch. /// @param _miningAddress The mining address of the pool. function _snapshotPoolStakeAmounts( IStakingAuRa _stakingContract, uint256 _stakingEpoch, address _miningAddress ) internal { if (snapshotPoolTotalStakeAmount[_stakingEpoch][_miningAddress] != 0) { return; } address stakingAddress = validatorSetContract.stakingByMiningAddress(_miningAddress); uint256 totalAmount = _stakingContract.stakeAmountTotal(stakingAddress); if (totalAmount == 0) { return; } snapshotPoolTotalStakeAmount[_stakingEpoch][_miningAddress] = totalAmount; snapshotPoolValidatorStakeAmount[_stakingEpoch][_miningAddress] = _stakingContract.stakeAmount(stakingAddress, stakingAddress); } /// @dev Called by the `transferReward` of a child contract to transfer native coins /// from the balance of the `BlockRewardAuRa` contract to the specified address as a reward. /// @param _amount The amount of native coins to transfer as a reward. /// @param _to The target address to transfer the amounts to. function _transferNativeReward(uint256 _amount, address payable _to) internal { if (_amount != 0 && !_to.send(_amount)) { // We use the `Sacrifice` trick to be sure the coins can be 100% sent to the receiver. // Otherwise, if the receiver is a contract which has a revert in its fallback function, // the sending will fail. (new Sacrifice).value(_amount)(_to); } } }
Returns an array of epoch numbers for which the specified staker can claim a reward from the specified pool by the `StakingAuRa.claimReward` function. _poolStakingAddress The pool staking address. _staker The staker's address (delegator or candidate/validator). If the delegator staked for the first time before the `epoch`, skip this staking epoch If the delegator withdrew all their stake before the `epoch`, don't check this and following epochs since it makes no sense
function epochsToClaimRewardFrom( address _poolStakingAddress, address _staker ) public view returns(uint256[] memory epochsToClaimFrom) { address miningAddress = validatorSetContract.miningByStakingAddress(_poolStakingAddress); IStakingAuRa stakingContract = IStakingAuRa(validatorSetContract.stakingContract()); bool isDelegator = _poolStakingAddress != _staker; uint256 firstEpoch; uint256 lastEpoch; if (isDelegator) { firstEpoch = stakingContract.stakeFirstEpoch(_poolStakingAddress, _staker); if (firstEpoch == 0) { return (new uint256[](0)); } lastEpoch = stakingContract.stakeLastEpoch(_poolStakingAddress, _staker); } uint256[] storage epochs = _epochsPoolGotRewardFor[miningAddress]; uint256 length = epochs.length; uint256[] memory tmp = new uint256[](length); uint256 tmpLength = 0; uint256 i; for (i = 0; i < length; i++) { uint256 epoch = epochs[i]; if (isDelegator) { if (epoch < firstEpoch) { continue; } if (lastEpoch <= epoch && lastEpoch != 0) { break; } } if (!stakingContract.rewardWasTaken(_poolStakingAddress, _staker, epoch)) { tmp[tmpLength++] = epoch; } } epochsToClaimFrom = new uint256[](tmpLength); for (i = 0; i < tmpLength; i++) { epochsToClaimFrom[i] = tmp[i]; } }
1,773,672
./partial_match/1/0x15bBeB47e642828778937b90fdA1926b744b0733/sources/Bank.sol
chooses a random Alien Cowboy when a newly minted token is stolen seed a random value to choose a Alien from return the owner of the randomly selected Alien Cowboy/ choose a value from 0 to total alpha staked loop through each bucket of Aliens with the same alpha score
function randomAlienOwner(uint256 seed) external view returns (address) { if (totalAlphaStaked == 0) return address(0x0); uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; uint256 cumulative; seed >>= 32; for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) { cumulative += pack[i].length * i; if (bucket >= cumulative) continue; return pack[i][seed % pack[i].length].owner; } return address(0x0); }
4,336,648
/** *Submitted for verification at Etherscan.io on 2021-08-12 */ // File: contracts/interfaces/IMarketHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/context/BlockContext.sol pragma solidity 0.6.12; /** * @title BiFi's BlockContext contract * @notice BiFi getter Contract for Block Context Information * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract BlockContext { function _blockContext() internal view returns(uint256 context) { // block number chain context = block.number; // block timestamp chain // context = block.timestamp; } } // File: contracts/marketHandler/marketHandlerDataStorage/MarketHandlerDataStorage.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's market handler data storage contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract MarketHandlerDataStorage is IMarketHandlerDataStorage, HandlerDataStorageModifier, BlockContext { address payable owner; bool emergency = false; address payable reservedAddr; int256 reservedAmount; address marketHandlerAddr; address interestModelAddr; uint256 lastUpdatedBlock; uint256 inactiveActionDelta; uint256 actionDepositEXR; uint256 actionBorrowEXR; uint256 public depositTotalAmount; uint256 public borrowTotalAmount; uint256 public globalDepositEXR; uint256 public globalBorrowEXR; mapping(address => IntraUser) intraUsers; MarketInterestModelParameters interestParams; uint256 constant unifiedPoint = 10 ** 18; uint256 public liquidityLimit = unifiedPoint; uint256 public limitOfAction = 100000 * unifiedPoint; struct MarketInterestModelParameters { uint256 borrowLimit; uint256 marginCallLimit; uint256 minimumInterestRate; uint256 liquiditySensitivity; } struct IntraUser { bool userAccessed; uint256 intraDepositAmount; uint256 intraBorrowAmount; uint256 userDepositEXR; uint256 userBorrowEXR; } modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyBifiContract { address msgSender = msg.sender; require(((msgSender == marketHandlerAddr) || (msgSender == interestModelAddr)) || (msgSender == owner), ONLY_BIFI_CONTRACT); _; } modifier circuitBreaker { address msgSender = msg.sender; require((!emergency) || (msgSender == owner), CIRCUIT_BREAKER); _; } constructor (uint256 _borrowLimit, uint256 _marginCallLimit, uint256 _minimumInterestRate, uint256 _liquiditySensitivity) public { owner = msg.sender; /* default reservedAddr */ reservedAddr = owner; _initializeEXR(); MarketInterestModelParameters memory _interestParams = interestParams; _interestParams.borrowLimit = _borrowLimit; _interestParams.marginCallLimit = _marginCallLimit; _interestParams.minimumInterestRate = _minimumInterestRate; _interestParams.liquiditySensitivity = _liquiditySensitivity; interestParams = _interestParams; } function ownershipTransfer(address payable _owner) onlyOwner public returns (bool) { owner = _owner; return true; } function getOwner() public view returns (address) { return owner; } function setCircuitBreaker(bool _emergency) onlyBifiContract external override returns (bool) { emergency = _emergency; return true; } function setNewCustomer(address payable userAddr) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userAccessed = true; intraUsers[userAddr].userDepositEXR = unifiedPoint; intraUsers[userAddr].userBorrowEXR = unifiedPoint; return true; } function setUserAccessed(address payable userAddr, bool _accessed) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userAccessed = _accessed; return true; } function getReservedAddr() external view override returns (address payable) { return reservedAddr; } function setReservedAddr(address payable reservedAddress) onlyOwner external override returns (bool) { reservedAddr = reservedAddress; return true; } function getReservedAmount() external view override returns (int256) { return reservedAmount; } function addReservedAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedAdd(reservedAmount, int(amount)); return reservedAmount; } function subReservedAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedSub(reservedAmount, int(amount)); return reservedAmount; } function updateSignedReservedAmount(int256 amount) onlyBifiContract circuitBreaker external override returns (int256) { reservedAmount = signedAdd(reservedAmount, amount); return reservedAmount; } function addDepositTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = add(depositTotalAmount, amount); return depositTotalAmount; } function subDepositTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = sub(depositTotalAmount, amount); return depositTotalAmount; } function addBorrowTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { borrowTotalAmount = add(borrowTotalAmount, amount); return borrowTotalAmount; } function subBorrowTotalAmount(uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { borrowTotalAmount = sub(borrowTotalAmount, amount); return borrowTotalAmount; } function addUserIntraDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraDepositAmount = add(intraUsers[userAddr].intraDepositAmount, amount); return intraUsers[userAddr].intraDepositAmount; } function subUserIntraDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraDepositAmount = sub(intraUsers[userAddr].intraDepositAmount, amount); return intraUsers[userAddr].intraDepositAmount; } function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraBorrowAmount = add(intraUsers[userAddr].intraBorrowAmount, amount); return intraUsers[userAddr].intraBorrowAmount; } function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (uint256) { intraUsers[userAddr].intraBorrowAmount = sub(intraUsers[userAddr].intraBorrowAmount, amount); return intraUsers[userAddr].intraBorrowAmount; } function addDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { depositTotalAmount = add(depositTotalAmount, amount); intraUsers[userAddr].intraDepositAmount = add(intraUsers[userAddr].intraDepositAmount, amount); } function addBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { borrowTotalAmount = add(borrowTotalAmount, amount); intraUsers[userAddr].intraBorrowAmount = add(intraUsers[userAddr].intraBorrowAmount, amount); } function subDepositAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { depositTotalAmount = sub(depositTotalAmount, amount); intraUsers[userAddr].intraDepositAmount = sub(intraUsers[userAddr].intraDepositAmount, amount); } function subBorrowAmount(address payable userAddr, uint256 amount) onlyBifiContract circuitBreaker external override returns (bool) { borrowTotalAmount = sub(borrowTotalAmount, amount); intraUsers[userAddr].intraBorrowAmount = sub(intraUsers[userAddr].intraBorrowAmount, amount); } function getUserAmount(address payable userAddr) external view override returns (uint256, uint256) { return (intraUsers[userAddr].intraDepositAmount, intraUsers[userAddr].intraBorrowAmount); } function getHandlerAmount() external view override returns (uint256, uint256) { return (depositTotalAmount, borrowTotalAmount); } function setAmount(address payable userAddr, uint256 _depositTotalAmount, uint256 _borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) onlyBifiContract circuitBreaker external override returns (uint256) { depositTotalAmount = _depositTotalAmount; borrowTotalAmount = _borrowTotalAmount; intraUsers[userAddr].intraDepositAmount = depositAmount; intraUsers[userAddr].intraBorrowAmount = borrowAmount; } function getAmount(address payable userAddr) external view override returns (uint256, uint256, uint256, uint256) { return (depositTotalAmount, borrowTotalAmount, intraUsers[userAddr].intraDepositAmount, intraUsers[userAddr].intraBorrowAmount); } function setBlocks(uint256 _lastUpdatedBlock, uint256 _inactiveActionDelta) onlyBifiContract circuitBreaker external override returns (bool) { lastUpdatedBlock = _lastUpdatedBlock; inactiveActionDelta = _inactiveActionDelta; return true; } function setLastUpdatedBlock(uint256 _lastUpdatedBlock) onlyBifiContract circuitBreaker external override returns (bool) { lastUpdatedBlock = _lastUpdatedBlock; return true; } function setInactiveActionDelta(uint256 _inactiveActionDelta) onlyBifiContract circuitBreaker external override returns (bool) { inactiveActionDelta = _inactiveActionDelta; return true; } function syncActionEXR() onlyBifiContract circuitBreaker external override returns (bool) { actionDepositEXR = globalDepositEXR; actionBorrowEXR = globalBorrowEXR; return true; } function getActionEXR() external view override returns (uint256, uint256) { return (actionDepositEXR, actionBorrowEXR); } function setActionEXR(uint256 _actionDepositEXR, uint256 _actionBorrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { actionDepositEXR = _actionDepositEXR; actionBorrowEXR = _actionBorrowEXR; return true; } function setEXR(address payable userAddr, uint256 _globalDepositEXR, uint256 _globalBorrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { globalDepositEXR = _globalDepositEXR; globalBorrowEXR = _globalBorrowEXR; intraUsers[userAddr].userDepositEXR = _globalDepositEXR; intraUsers[userAddr].userBorrowEXR = _globalBorrowEXR; return true; } function getUserEXR(address payable userAddr) external view override returns (uint256, uint256) { return (intraUsers[userAddr].userDepositEXR, intraUsers[userAddr].userBorrowEXR); } function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) onlyBifiContract circuitBreaker external override returns (bool) { intraUsers[userAddr].userDepositEXR = depositEXR; intraUsers[userAddr].userBorrowEXR = borrowEXR; return true; } function getGlobalEXR() external view override returns (uint256, uint256) { return (globalDepositEXR, globalBorrowEXR); } function setMarketHandlerAddr(address _marketHandlerAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; return true; } function setInterestModelAddr(address _interestModelAddr) onlyOwner external override returns (bool) { interestModelAddr = _interestModelAddr; return true; } function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; interestModelAddr = _interestModelAddr; return true; } function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) onlyOwner external override returns (bool) { marketHandlerAddr = _marketHandlerAddr; interestModelAddr = _interestModelAddr; return true; } /* total Borrow Function */ function getBorrowTotalAmount() external view override returns (uint256) { return borrowTotalAmount; } /* Global: lastUpdated function */ function getLastUpdatedBlock() external view override returns (uint256) { return lastUpdatedBlock; } /* User Accessed Function */ function getUserAccessed(address payable userAddr) external view override returns (bool) { return intraUsers[userAddr].userAccessed; } /* total Deposit Function */ function getDepositTotalAmount() external view override returns (uint256) { return depositTotalAmount; } /* intra Borrow Function */ function getUserIntraBorrowAmount(address payable userAddr) external view override returns (uint256) { return intraUsers[userAddr].intraBorrowAmount; } /* intra Deposit Function */ function getUserIntraDepositAmount(address payable userAddr) external view override returns (uint256) { return intraUsers[userAddr].intraDepositAmount; } /* Global: inactiveActionDelta function */ function getInactiveActionDelta() external view override returns (uint256) { return inactiveActionDelta; } /* Action: ExchangeRate Function */ function getGlobalBorrowEXR() external view override returns (uint256) { return globalBorrowEXR; } /* Global: ExchangeRate Function */ function getGlobalDepositEXR() external view override returns (uint256) { return globalDepositEXR; } function getMarketHandlerAddr() external view override returns (address) { return marketHandlerAddr; } function getInterestModelAddr() external view override returns (address) { return interestModelAddr; } function _initializeEXR() internal { uint256 currectBlockNumber = _blockContext(); actionDepositEXR = unifiedPoint; actionBorrowEXR = unifiedPoint; globalDepositEXR = unifiedPoint; globalBorrowEXR = unifiedPoint; lastUpdatedBlock = currectBlockNumber - 1; inactiveActionDelta = lastUpdatedBlock; } function getLimit() external view override returns (uint256, uint256) { return (interestParams.borrowLimit, interestParams.marginCallLimit); } function getBorrowLimit() external view override returns (uint256) { return interestParams.borrowLimit; } function getMarginCallLimit() external view override returns (uint256) { return interestParams.marginCallLimit; } function getMinimumInterestRate() external view override returns (uint256) { return interestParams.minimumInterestRate; } function getLiquiditySensitivity() external view override returns (uint256) { return interestParams.liquiditySensitivity; } function setBorrowLimit(uint256 _borrowLimit) onlyOwner external override returns (bool) { interestParams.borrowLimit = _borrowLimit; return true; } function setMarginCallLimit(uint256 _marginCallLimit) onlyOwner external override returns (bool) { interestParams.marginCallLimit = _marginCallLimit; return true; } function setMinimumInterestRate(uint256 _minimumInterestRate) onlyOwner external override returns (bool) { interestParams.minimumInterestRate = _minimumInterestRate; return true; } function setLiquiditySensitivity(uint256 _liquiditySensitivity) onlyOwner external override returns (bool) { interestParams.liquiditySensitivity = _liquiditySensitivity; return true; } function getLiquidityLimit() external view override returns (uint256) { return liquidityLimit; } function setLiquidityLimit(uint256 _liquidityLimit) onlyOwner external override returns (bool) { liquidityLimit = _liquidityLimit; return true; } function getLimitOfAction() external view override returns (uint256) { return limitOfAction; } function setLimitOfAction(uint256 _limitOfAction) onlyOwner external override returns (bool) { limitOfAction = _limitOfAction; return true; } /* ******************* Safe Math ******************* */ // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(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; } function signedSub(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; } }
BiFi's market handler data storage interface BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)/
interface IMarketHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); pragma solidity 0.6.12; }
15,333,282
./full_match/80001/0x8c9F2c3B36939583Ecd3511aC8826aE258eD6f8E/sources/contracts/smart-wallet/utils/UserOperation.sol
read sender from userOp, which is first userOp member (saves 800 gas...)
function getSender(UserOperation calldata userOp) internal pure returns (address) { address data; assembly { data := calldataload(userOp) } return address(uint160(data)); }
5,560,831
./full_match/4/0x26DBF89Fe796dD5Ff0a78D898F72d8bFE26198f8/sources/contracts/dob.sol
A distinct URI (RFC 3986) for a given NFT. _tokenId Id for which we want uri. return URI of _tokenId./
function tokenURI(uint256 _tokenId) external override view validNFToken(_tokenId) returns (string memory) { return string(abi.encodePacked(baseURI,idToUri[_tokenId])); }
784,922
// SPDX-License-Identifier: MIT /****************************************************************************/ /* Written by Oliver Straszynski */ /* https://github.com/broliver12/ */ /****************************************************************************/ pragma solidity ^0.8.11; import '@openzeppelin/contracts/utils/Counters.sol'; import './OwnableERC721.sol'; /**************************************************************************** /* Core ERC721 Contract. /* Functionality: /* - Ownership /* - Withdraw /* - Enable/Disable minting /* - Metadata control: /* - Pre reveal URI /* - Base URI /* - Override URI for token (1-to-1 upgrade) /* - Max Supply /* - Free mint (still pay gas) for owner ****************************************************************************/ contract CoreERC721 is OwnableERC721 { // Counter used to reduce supply, and increase IDs using Counters for Counters.Counter; Counters.Counter private idCounter; function current() internal view returns (uint256) { return idCounter.current(); } // Total Supply for entire mint. Ensures that no matter what, only totalSupply NFTs are minted. // Can only be set in constructor. If an invalid value is provided, defaults to 10000. // Note: This is a limited mint contract. // If you want the option to mint unlimited NFTs from your contract, use UnlimitedERC721.sol uint256 public totalSupply = 10000; // Action control variables bool public mintingEnabled; // Metadata control variables bool private revealed; string private baseURI; string private notRevealedURI; string private baseExtension = '.json'; mapping(uint256 => string) private _customizedUris; // Override this to implement custom mint option logic function validMintOption(uint256 mintOption) internal pure virtual returns (bool) { if (mintOption <= 20) { return true; } return false; } // Override this to implement custom price logic function getPrice(uint256 quantity) internal view virtual returns (uint256) { return 0; } // Constructor - Creates the ERC721 contract // Arguments: NFT name, NFT symbol, max supply constructor( string memory _name, string memory _symbol, uint256 _maxSupply ) OwnableERC721(_name, _symbol) { if (_maxSupply > 0 && _maxSupply <= 1000000) totalSupply = _maxSupply; } // Checks that the inputs meet the requirements // Mints the specified number of NFTs, and sends them to the recipient function mint(address recipient, uint256 mintOption) public payable virtual { require(validMintOption(mintOption), 'Illegal quantity.'); require(mintingEnabled, 'Minting not enabled.'); require(msg.value >= getPrice(mintOption), 'Not enough ETH.'); require(checkRemainingSupply() >= mintOption, 'Not enough remainging supply.'); uint256 newItemId; for (uint256 i = 0; i < mintOption; i++) { idCounter.increment(); newItemId = idCounter.current(); _safeMint(recipient, newItemId); } } // Override virtual tokenURI() function; enable baseURI, notRevealedURI, and overwriting for 1-to-1s function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'URI query for nonexistent token'); if (revealed == false) { return notRevealedURI; } if (compareStrings(_customizedUris[tokenId], '') == false) { return _customizedUris[tokenId]; } return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenId), baseExtension)) : ''; } // Returns the price for the requested mintOption in wei function getMintPriceInWei(uint256 mintOption) external view returns (uint256) { require(validMintOption(mintOption), 'Illegal quantity.'); require(checkRemainingSupply() >= mintOption, 'Not enough remainging supply.'); return getPrice(mintOption); } // Check remaining mint supplypublic function checkRemainingSupply() public view returns (uint256) { return totalSupply - idCounter.current(); } // Sets token uri to whatever is passed in. function _setUriForToken(string memory _tokenURI, uint256 tokenId) public onlyOwner { require(_exists(tokenId), 'URIset of nonexistent token'); _customizedUris[tokenId] = _tokenURI; } // Set revealed to true (displays baseURI instead of notRevealedURI on metamask/opensea) function reveal(bool _revealed) public onlyOwner { revealed = _revealed; } /*Change token URIs if something fatal happens to initial URIs*/ function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedURI = _notRevealedURI; } // Enables or disables minting function enableMinting(bool _enabled) public onlyOwner { mintingEnabled = _enabled; } // Allows the owner to mint NFTs for free to the specified recipient. // Owner still pays gas (obviously) // Used for giveaways. // NFTs minted through this method are still subtracted from the total supply.. function freeMint(address recipient, uint256 mintOption) external onlyOwner { require(validMintOption(mintOption), 'Illegal quantity.'); require(checkRemainingSupply() >= mintOption, 'Not enough remainging supply.'); for (uint256 i = 0; i < mintOption; i++) { idCounter.increment(); _safeMint(recipient, idCounter.current()); } } }
Override this to implement custom price logic
function getPrice(uint256 quantity) internal view virtual returns (uint256) { return 0; } string memory _name, string memory _symbol, uint256 _maxSupply
5,362,462
/* solhint-disable-next-line compiler-fixed */ pragma solidity ^0.4.23; // Copyright 2017 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // Value chain: OpenSTValue // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./SafeMath.sol"; import "./Hasher.sol"; import "./OpsManaged.sol"; import "./EIP20Interface.sol"; import "./CoreInterface.sol"; import "./ProtocolVersioned.sol"; // value chain contracts import "./SimpleStake.sol"; import "./ProofLib.sol"; /// @title OpenSTValue - value staking contract for OpenST contract OpenSTValue is OpsManaged, Hasher { using SafeMath for uint256; /* * Events */ event UtilityTokenRegistered(bytes32 indexed _uuid, address indexed stake, string _symbol, string _name, uint8 _decimals, uint256 _conversionRate, uint8 _conversionRateDecimals, uint256 _chainIdUtility, address indexed _stakingAccount); event StakingIntentDeclared(bytes32 indexed _uuid, address indexed _staker, uint256 _stakerNonce, bytes32 _intentKeyHash, address _beneficiary, uint256 _amountST, uint256 _amountUT, uint256 _unlockHeight, bytes32 _stakingIntentHash, uint256 _chainIdUtility); event ProcessedStake(bytes32 indexed _uuid, bytes32 indexed _stakingIntentHash, address _stake, address _staker, uint256 _amountST, uint256 _amountUT, bytes32 _unlockSecret); event RevertedStake(bytes32 indexed _uuid, bytes32 indexed _stakingIntentHash, address _staker, uint256 _amountST, uint256 _amountUT); event RedemptionIntentConfirmed(bytes32 indexed _uuid, bytes32 _redemptionIntentHash, address _redeemer, address _beneficiary, uint256 _amountST, uint256 _amountUT, uint256 _expirationHeight); event ProcessedUnstake(bytes32 indexed _uuid, bytes32 indexed _redemptionIntentHash, address stake, address _redeemer, address _beneficiary, uint256 _amountST, bytes32 _unlockSecret); event RevertedUnstake(bytes32 indexed _uuid, bytes32 indexed _redemptionIntentHash, address _redeemer, address _beneficiary, uint256 _amountST); /* * Constants */ uint8 public constant TOKEN_DECIMALS = 18; uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS); // 2 weeks in seconds uint256 private constant TIME_TO_WAIT_LONG = 1209600; // 1hour in seconds uint256 private constant TIME_TO_WAIT_SHORT = 3600; // indentified index position of redemptionIntents mapping in storage (in OpenSTUtility) // positions 0-3 are occupied by public state variables in OpsManaged and Owned // private constants do not occupy the storage of a contract uint8 internal constant intentsMappingStorageIndexPosition = 4; // storage for staking intent hash of active staking intents mapping(bytes32 /* hashIntentKey */ => bytes32 /* stakingIntentHash */) public stakingIntents; // register the active stakes and unstakes mapping(bytes32 /* hashStakingIntent */ => Stake) public stakes; mapping(uint256 /* chainIdUtility */ => CoreInterface) internal cores; mapping(bytes32 /* uuid */ => UtilityToken) public utilityTokens; /// nonce makes the staking process atomic across the two-phased process /// and protects against replay attack on (un)staking proofs during the process. /// On the value chain nonces need to strictly increase by one; on the utility /// chain the nonce need to strictly increase (as one value chain can have multiple /// utility chains) mapping(address /* (un)staker */ => uint256) internal nonces; mapping(bytes32 /* hashRedemptionIntent */ => Unstake) public unstakes; /* * Storage */ uint256 public chainIdValue; EIP20Interface public valueToken; address public registrar; uint256 public blocksToWaitShort; uint256 public blocksToWaitLong; bytes32[] public uuids; /* * Structures */ struct UtilityToken { string symbol; string name; uint256 conversionRate; uint8 conversionRateDecimals; uint8 decimals; uint256 chainIdUtility; SimpleStake simpleStake; address stakingAccount; } struct Stake { bytes32 uuid; address staker; address beneficiary; uint256 nonce; uint256 amountST; uint256 amountUT; uint256 unlockHeight; bytes32 hashLock; } struct Unstake { bytes32 uuid; address redeemer; address beneficiary; uint256 amountST; // @dev consider removal of amountUT uint256 amountUT; uint256 expirationHeight; bytes32 hashLock; } /* * Modifiers */ modifier onlyRegistrar() { // for now keep unique registrar require(msg.sender == registrar); _; } constructor( uint256 _chainIdValue, EIP20Interface _eip20token, address _registrar, uint256 _valueChainBlockGenerationTime) public OpsManaged() { require(_chainIdValue != 0); require(_eip20token != address(0)); require(_registrar != address(0)); require(_valueChainBlockGenerationTime != 0); blocksToWaitShort = TIME_TO_WAIT_SHORT.div(_valueChainBlockGenerationTime); blocksToWaitLong = TIME_TO_WAIT_LONG.div(_valueChainBlockGenerationTime); chainIdValue = _chainIdValue; valueToken = _eip20token; // registrar cannot be reset // TODO: require it to be a contract registrar = _registrar; } /* * External functions */ /// @dev In order to stake the tx.origin needs to set an allowance /// for the OpenSTValue contract to transfer to itself to hold /// during the staking process. function stake( bytes32 _uuid, uint256 _amountST, address _beneficiary, bytes32 _hashLock, address _staker) external returns ( uint256 amountUT, uint256 nonce, uint256 unlockHeight, bytes32 stakingIntentHash) /* solhint-disable-next-line function-max-lines */ { /* solhint-disable avoid-tx-origin */ // check the staking contract has been approved to spend the amount to stake // OpenSTValue needs to be able to transfer the stake into its balance for // keeping until the two-phase process is completed on both chains. require(_amountST > uint256(0)); require(utilityTokens[_uuid].simpleStake != address(0)); require(_beneficiary != address(0)); require(_staker != address(0)); UtilityToken storage utilityToken = utilityTokens[_uuid]; // if the staking account is set to a non-zero address, // then all stakes have come (from/over) the staking account if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount); require(valueToken.transferFrom(msg.sender, address(this), _amountST)); amountUT = (_amountST.mul(utilityToken.conversionRate)) .div(10**uint256(utilityToken.conversionRateDecimals)); unlockHeight = block.number + blocksToWaitLong; nonces[_staker]++; nonce = nonces[_staker]; stakingIntentHash = hashStakingIntent( _uuid, _staker, nonce, _beneficiary, _amountST, amountUT, unlockHeight, _hashLock ); stakes[stakingIntentHash] = Stake({ uuid: _uuid, staker: _staker, beneficiary: _beneficiary, nonce: nonce, amountST: _amountST, amountUT: amountUT, unlockHeight: unlockHeight, hashLock: _hashLock }); // store the staking intent hash directly in storage of OpenSTValue // so that a Merkle proof can be generated for active staking intents bytes32 intentKeyHash = hashIntentKey(_staker, nonce); stakingIntents[intentKeyHash] = stakingIntentHash; emit StakingIntentDeclared(_uuid, _staker, nonce, intentKeyHash, _beneficiary, _amountST, amountUT, unlockHeight, stakingIntentHash, utilityToken.chainIdUtility); return (amountUT, nonce, unlockHeight, stakingIntentHash); /* solhint-enable avoid-tx-origin */ } function processStaking( bytes32 _stakingIntentHash, bytes32 _unlockSecret) external returns (address stakeAddress) { require(_stakingIntentHash != ""); Stake storage stakeItem = stakes[_stakingIntentHash]; // present the secret to unlock the hashlock and continue process require(stakeItem.hashLock == keccak256(abi.encodePacked(_unlockSecret))); // as this bears the cost, there is no need to require // that the stakeItem.unlockHeight is not yet surpassed // as is required on processMinting UtilityToken storage utilityToken = utilityTokens[stakeItem.uuid]; // if the staking account is set to a non-zero address, // then all stakes have come (from/over) the staking account if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount); stakeAddress = address(utilityToken.simpleStake); require(stakeAddress != address(0)); assert(valueToken.balanceOf(address(this)) >= stakeItem.amountST); require(valueToken.transfer(stakeAddress, stakeItem.amountST)); emit ProcessedStake(stakeItem.uuid, _stakingIntentHash, stakeAddress, stakeItem.staker, stakeItem.amountST, stakeItem.amountUT, _unlockSecret); // remove from stakingIntents mapping delete stakingIntents[hashIntentKey(stakeItem.staker, stakeItem.nonce)]; delete stakes[_stakingIntentHash]; return stakeAddress; } function revertStaking( bytes32 _stakingIntentHash) external returns ( bytes32 uuid, uint256 amountST, address staker) { require(_stakingIntentHash != ""); Stake storage stakeItem = stakes[_stakingIntentHash]; UtilityToken storage utilityToken = utilityTokens[stakeItem.uuid]; // if the staking account is set to a non-zero address, // then all stakes have come (from/over) the staking account if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount); // require that the stake is unlocked and exists require(stakeItem.unlockHeight > 0); require(stakeItem.unlockHeight <= block.number); assert(valueToken.balanceOf(address(this)) >= stakeItem.amountST); // revert the amount that was intended to be staked back to staker require(valueToken.transfer(stakeItem.staker, stakeItem.amountST)); uuid = stakeItem.uuid; amountST = stakeItem.amountST; staker = stakeItem.staker; emit RevertedStake(stakeItem.uuid, _stakingIntentHash, stakeItem.staker, stakeItem.amountST, stakeItem.amountUT); // remove from stakingIntents mapping delete stakingIntents[hashIntentKey(stakeItem.staker, stakeItem.nonce)]; delete stakes[_stakingIntentHash]; return (uuid, amountST, staker); } /** * @notice Confirm redemption intent on value chain. * * @dev RedemptionIntentHash is generated in Utility chain, the paramerters are that were used for hash generation * is passed in this function along with rpl encoded parent nodes of merkle pactritia tree proof * for RedemptionIntentHash. * * @param _uuid UUID for utility token * @param _redeemer Redeemer address * @param _redeemerNonce Nonce for redeemer account * @param _beneficiary Beneficiary address * @param _amountUT Amount of utility token * @param _redemptionUnlockHeight Unlock height for redemption * @param _hashLock Hash lock * @param _blockHeight Block height at which the Merkle proof was generated * @param _rlpParentNodes RLP encoded parent nodes for proof verification * * @return bytes32 amount of OST * @return uint256 expiration height */ function confirmRedemptionIntent( bytes32 _uuid, address _redeemer, uint256 _redeemerNonce, address _beneficiary, uint256 _amountUT, uint256 _redemptionUnlockHeight, bytes32 _hashLock, uint256 _blockHeight, bytes _rlpParentNodes) external returns ( uint256 amountST, uint256 expirationHeight) { UtilityToken storage utilityToken = utilityTokens[_uuid]; require(utilityToken.simpleStake != address(0)); require(_amountUT > 0); require(_beneficiary != address(0)); // later core will provide a view on the block height of the // utility chain require(_redemptionUnlockHeight > 0); require(cores[utilityToken.chainIdUtility].safeUnlockHeight() < _redemptionUnlockHeight); nonces[_redeemer]++; require(nonces[_redeemer] == _redeemerNonce); bytes32 redemptionIntentHash = hashRedemptionIntent( _uuid, _redeemer, _redeemerNonce, _beneficiary, _amountUT, _redemptionUnlockHeight, _hashLock ); expirationHeight = block.number + blocksToWaitShort; // minimal precision to unstake 1 STWei require(_amountUT >= (utilityToken.conversionRate.div(10**uint256(utilityToken.conversionRateDecimals)))); amountST = (_amountUT .mul(10**uint256(utilityToken.conversionRateDecimals))).div(utilityToken.conversionRate); require(valueToken.balanceOf(address(utilityToken.simpleStake)) >= amountST); require(verifyRedemptionIntent( _uuid, _redeemer, _redeemerNonce, _blockHeight, redemptionIntentHash, _rlpParentNodes), "RedemptionIntentHash storage verification failed"); unstakes[redemptionIntentHash] = Unstake({ uuid: _uuid, redeemer: _redeemer, beneficiary: _beneficiary, amountUT: _amountUT, amountST: amountST, expirationHeight: expirationHeight, hashLock: _hashLock }); emit RedemptionIntentConfirmed(_uuid, redemptionIntentHash, _redeemer, _beneficiary, amountST, _amountUT, expirationHeight); return (amountST, expirationHeight); } /** * @notice Verify storage of redemption intent hash * * @param _uuid UUID for utility token * @param _redeemer Redeemer address * @param _redeemerNonce Nonce for redeemer account * @param _blockHeight Block height at which the Merkle proof was generated * @param _rlpParentNodes RLP encoded parent nodes for proof verification * * @return true if successfully verifies, otherwise throws an exception. */ function verifyRedemptionIntent( bytes32 _uuid, address _redeemer, uint256 _redeemerNonce, uint256 _blockHeight, bytes32 _redemptionIntentHash, bytes _rlpParentNodes) internal view returns (bool /* verification status */) { // get storageRoot from core for the given block height bytes32 storageRoot = CoreInterface(cores[utilityTokens[_uuid].chainIdUtility]).getStorageRoot(_blockHeight); // storageRoot cannot be 0 require(storageRoot != bytes32(0), "storageRoot not found for given blockHeight"); require(ProofLib.verifyIntentStorage( intentsMappingStorageIndexPosition, _redeemer, _redeemerNonce, _redemptionIntentHash, _rlpParentNodes, storageRoot), "RedemptionIntentHash storage verification failed"); return true; } function processUnstaking( bytes32 _redemptionIntentHash, bytes32 _unlockSecret) external returns ( address stakeAddress) { require(_redemptionIntentHash != ""); Unstake storage unstake = unstakes[_redemptionIntentHash]; // present secret to unlock hashlock and proceed require(unstake.hashLock == keccak256(abi.encodePacked(_unlockSecret))); // as the process unstake results in a gain for the caller // it needs to expire well before the process redemption can // be reverted in OpenSTUtility require(unstake.expirationHeight > block.number); UtilityToken storage utilityToken = utilityTokens[unstake.uuid]; stakeAddress = address(utilityToken.simpleStake); require(stakeAddress != address(0)); require(utilityToken.simpleStake.releaseTo(unstake.beneficiary, unstake.amountST)); emit ProcessedUnstake(unstake.uuid, _redemptionIntentHash, stakeAddress, unstake.redeemer, unstake.beneficiary, unstake.amountST, _unlockSecret); delete unstakes[_redemptionIntentHash]; return stakeAddress; } function revertUnstaking( bytes32 _redemptionIntentHash) external returns ( bytes32 uuid, address redeemer, address beneficiary, uint256 amountST) { require(_redemptionIntentHash != ""); Unstake storage unstake = unstakes[_redemptionIntentHash]; // require that the unstake has expired and that the redeemer has not // processed the unstaking, ie unstake has not been deleted require(unstake.expirationHeight > 0); require(unstake.expirationHeight <= block.number); uuid = unstake.uuid; redeemer = unstake.redeemer; beneficiary = unstake.beneficiary; amountST = unstake.amountST; delete unstakes[_redemptionIntentHash]; emit RevertedUnstake(uuid, _redemptionIntentHash, redeemer, beneficiary, amountST); return (uuid, redeemer, beneficiary, amountST); } function core( uint256 _chainIdUtility) external view returns (address /* core address */ ) { return address(cores[_chainIdUtility]); } /* * Public view functions */ function getNextNonce( address _account) public view returns (uint256 /* nextNonce */) { return (nonces[_account] + 1); } /// @dev Returns size of uuids /// @return size function getUuidsSize() public view returns (uint256) { return uuids.length; } /* * Registrar functions */ function addCore( CoreInterface _core) public onlyRegistrar returns (bool /* success */) { require(address(_core) != address(0)); // on value chain core only tracks a remote utility chain uint256 chainIdUtility = _core.chainIdRemote(); require(chainIdUtility != 0); // cannot overwrite core for given chainId require(cores[chainIdUtility] == address(0)); cores[chainIdUtility] = _core; return true; } function registerUtilityToken( string _symbol, string _name, uint256 _conversionRate, uint8 _conversionRateDecimals, uint256 _chainIdUtility, address _stakingAccount, bytes32 _checkUuid) public onlyRegistrar returns (bytes32 uuid) { require(bytes(_name).length > 0); require(bytes(_symbol).length > 0); require(_conversionRate > 0); require(_conversionRateDecimals <= 5); address openSTRemote = cores[_chainIdUtility].openSTRemote(); require(openSTRemote != address(0)); uuid = hashUuid( _symbol, _name, chainIdValue, _chainIdUtility, openSTRemote, _conversionRate, _conversionRateDecimals); require(uuid == _checkUuid); require(address(utilityTokens[uuid].simpleStake) == address(0)); SimpleStake simpleStake = new SimpleStake( valueToken, address(this), uuid); utilityTokens[uuid] = UtilityToken({ symbol: _symbol, name: _name, conversionRate: _conversionRate, conversionRateDecimals: _conversionRateDecimals, decimals: TOKEN_DECIMALS, chainIdUtility: _chainIdUtility, simpleStake: simpleStake, stakingAccount: _stakingAccount }); uuids.push(uuid); emit UtilityTokenRegistered(uuid, address(simpleStake), _symbol, _name, TOKEN_DECIMALS, _conversionRate, _conversionRateDecimals, _chainIdUtility, _stakingAccount); return uuid; } /** * @notice Initiates protocol transfer. * * @param _protocolVersioned The address of the current protocol. * @param _proposedProtocol The address of the proposed protocol. * * @return bool true in case of success, otherwise throws an exception. */ function initiateProtocolTransfer( ProtocolVersioned _protocolVersioned, address _proposedProtocol) public onlyAdmin returns (bool) { _protocolVersioned.initiateProtocolTransfer(_proposedProtocol); return true; } /** * @notice Revokes protocol transfer. * * @param _protocolVersioned The address of the current protocol. * * @return bool true in case of success, otherwise throws an exception. */ function revokeProtocolTransfer( ProtocolVersioned _protocolVersioned) public onlyAdmin returns (bool) { _protocolVersioned.revokeProtocolTransfer(); return true; } function getStakerAddress( bytes32 _stakingIntentHash) view external returns (address /* staker */) { require(_stakingIntentHash != ""); Stake storage stakeItem = stakes[_stakingIntentHash]; return stakeItem.staker; } }
if the staking account is set to a non-zero address, then all stakes have come (from/over) the staking account require that the stake is unlocked and exists revert the amount that was intended to be staked back to staker remove from stakingIntents mapping
function revertStaking( bytes32 _stakingIntentHash) external returns ( bytes32 uuid, uint256 amountST, address staker) { require(_stakingIntentHash != ""); Stake storage stakeItem = stakes[_stakingIntentHash]; UtilityToken storage utilityToken = utilityTokens[stakeItem.uuid]; if (utilityToken.stakingAccount != address(0)) require(msg.sender == utilityToken.stakingAccount); require(stakeItem.unlockHeight > 0); require(stakeItem.unlockHeight <= block.number); assert(valueToken.balanceOf(address(this)) >= stakeItem.amountST); require(valueToken.transfer(stakeItem.staker, stakeItem.amountST)); uuid = stakeItem.uuid; amountST = stakeItem.amountST; staker = stakeItem.staker; emit RevertedStake(stakeItem.uuid, _stakingIntentHash, stakeItem.staker, stakeItem.amountST, stakeItem.amountUT); delete stakingIntents[hashIntentKey(stakeItem.staker, stakeItem.nonce)]; delete stakes[_stakingIntentHash]; return (uuid, amountST, staker); }
1,821,042
./full_match/1/0x18d9244DC85306DBc0AAE16cF8FAE9aEFAee7530/sources/ForbitswapRouter.sol
LIBRARY FUNCTIONS
function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public virtual override pure returns (uint256 amountB) { return ForbitswapLibrary.quote(amountA, reserveA, reserveB); }
9,783,521
./full_match/4/0xDBD82a63aAA7ED8F7EaC95740C5b100b5649E53F/sources/contracts/streams/ERC721/extensions/ERC721EmissionReleaseExtension.sol
Intentionally rounded down:
function releasedAmountUntil(uint64 calcUntil) public view virtual returns (uint256) { return emissionRate * ((calcUntil - emissionStart) / emissionTimeUnit); }
817,418
// File: contracts/utils/StorageSlot.sol pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File: contracts/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"); // console.log("==================="); // console.log("targettargettarget: ", target); // console.log("data :", string(data)); // console.log("msg.senderererer: ", msg.sender); (bool success, bytes memory returndata) = target.delegatecall(data); // console.log("===================111"); // console.log(success); 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); } } } } // File: contracts/utils/IBeacon.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File: contracts/proxy/ERC1967Upgrade.sol pragma solidity ^0.8.0; abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( Address.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlot .getAddressSlot(_IMPLEMENTATION_SLOT) .value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot .getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require( oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades" ); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require( newAdmin != address(0), "ERC1967: new admin is the zero address" ); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall( IBeacon(newBeacon).implementation(), data ); } } } // File: contracts/proxy/Proxy.sol pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall( gas(), implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // File: contracts/proxy/ERC1967Proxy.sol pragma solidity ^0.8.0; /** * @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. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @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) payable { assert( _IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1) ); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // File: contracts/proxy/TransparentUpgradeableProxy.sol pragma solidity ^0.8.0; /** * @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 ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { assert( _ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1) ); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } 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_ = _getAdmin(); } /** * @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 virtual ifAdmin { _changeAdmin(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 { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @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 { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/utils/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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(msg.sender); } /** * @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() == msg.sender, "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 { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/callAgent.sol pragma solidity ^0.8.0; interface SafeGuardWhiteList { function isWhiteListed(address callee) external view returns (bool); } contract CallAgent is Ownable { address constant NULL = 0x0000000000000000000000000000000000000000; bool private initialized = false; address private _admin; // If white list contract is null. local whitelist filter will be used. address public whiteListContract = NULL; mapping(address => bool) filter; // todo add method to modify signaturedb mapping(bytes4 => uint256) signatures; // When operator changed. event adminChanged(address newAdmin); // When operator triggered emergency event paused(); // When switched to white list contract. event whiteListChanged(address newWhiteList); modifier requireAdmin() { require(owner() == msg.sender || admin() == msg.sender, "denied"); _; } function ChangeAdmin(address newAdmin) public onlyOwner { _admin = newAdmin; emit adminChanged(newAdmin); } function ChangeWhiteList(address newWhiteList) public onlyOwner { // todo: check if the external contract is legal whitelist. whiteListContract = newWhiteList; emit whiteListChanged(newWhiteList); } // Add local target address. // Available when whitelist contract is null function addLocalWhiteList(address[] memory callee) public onlyOwner { for (uint256 i = 0; i < callee.length; i++) { filter[callee[i]] = true; } } function removeLocalWhiteList(address[] memory callee) public onlyOwner { for (uint256 i = 0; i < callee.length; i++) { filter[callee[i]] = false; } } function checkWhiteList(address callee) public view returns (bool) { if(whiteListContract == NULL) { return filter[callee]; } return SafeGuardWhiteList(whiteListContract).isWhiteListed(callee); } function initialize(address owner, address admin_) public { require(!initialized, "Already Initialized"); Ownable._transferOwnership(owner); _admin = admin_; initialized = true; } function admin() public view returns (address) { return _admin; } // Owner withdrawal ethereum. function withdrawEth(uint256 amount, address payable out) public onlyOwner { out.transfer(amount); } function withdrawErc20(uint256 amount, address erc20, address out) public onlyOwner { IERC20(erc20).transfer(out, amount); } function emergencyPause() public requireAdmin { _admin = 0x0000000000000000000000000000000000000000; emit paused(); } // Add filtered signatures // src: function signature // address_filter: where address begins // Example: // src: 0xa9059cbb(Transfer) // address_filter: 4 (in ABI Encode of transfer(address, uint256), address begins at hex 0x4 location) function addSignature(bytes4[] memory src, uint256[] memory address_filter) public onlyOwner { for (uint256 i = 0; i < src.length; i++) { signatures[src[i]] = address_filter[i]; } } function removeSignature(bytes4[] memory src) public onlyOwner { for (uint256 i = 0; i < src.length; i++) { signatures[src[i]] = 0; } } function toBytes4(bytes memory payload) internal pure returns (bytes4 b) { assembly { b := mload(add(payload, 0x20)) } } function toAddress(bytes memory payload) internal pure returns (address b) { assembly { b := mload(add(payload, 0x20)) } } function callAgent(address callee, uint256 ethAmount, bytes calldata payload) public requireAdmin returns (bool, bytes memory) { if(ethAmount != 0) { if(!checkWhiteList(callee)) { revert("no whitelist"); } } else { bytes4 signature = toBytes4(payload[:4]); uint256 p = signatures[signature]; if(p > 0) { address addr = toAddress(payload[p:p + 32]); if(!checkWhiteList(addr)) { revert("no whitelist"); } } } return callee.call{value: ethAmount}(payload); } receive() external payable {} fallback() external payable {} } // File: contracts/deployFactory.sol pragma solidity ^0.8.0; contract DeployFactory is Ownable { address public currentImplemtation; mapping(address => address) public walletAddress; event UpdateImplemtation(address oldImplementation, address newImplementation); function updateImplemtation(address newImplementation) external onlyOwner { address oldImplementation = currentImplemtation; currentImplemtation = newImplementation; emit UpdateImplemtation(oldImplementation, newImplementation); } function newFilter(address admin, bool reCreate) public returns(address) { if(!reCreate && walletAddress[msg.sender] != 0x0000000000000000000000000000000000000000) { return 0x0000000000000000000000000000000000000000; } TransparentUpgradeableProxy c = new TransparentUpgradeableProxy(currentImplemtation, msg.sender, abi.encodeWithSignature("initialize(address,address)", msg.sender, admin)); walletAddress[msg.sender] = address(c); return address(c); } }
Transfers ownership of the contract to a new account (`newOwner`). Internal function without access restriction./
function _transferOwnership(address newOwner) internal { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); }
1,545,387
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract WhiteListedBasic { function addWhiteListed(address[] addrs) external; function removeWhiteListed(address addr) external; function isWhiteListed(address addr) external view returns (bool); } contract OperatableBasic { function setMinter (address addr) external; function setWhiteLister (address addr) external; } contract Operatable is Claimable, OperatableBasic { address public minter; address public whiteLister; address public launcher; event NewMinter(address newMinter); event NewWhiteLister(address newwhiteLister); modifier canOperate() { require(msg.sender == minter || msg.sender == whiteLister || msg.sender == owner); _; } constructor() public { minter = owner; whiteLister = owner; launcher = owner; } function setMinter (address addr) external onlyOwner { minter = addr; emit NewMinter(minter); } function setWhiteLister (address addr) external onlyOwner { whiteLister = addr; emit NewWhiteLister(whiteLister); } modifier ownerOrMinter() { require ((msg.sender == minter) || (msg.sender == owner)); _; } modifier onlyLauncher() { require (msg.sender == launcher); _; } modifier onlyWhiteLister() { require (msg.sender == whiteLister); _; } } contract Salvageable is Operatable { // Salvage other tokens that are accidentally sent into this token function emergencyERC20Drain(ERC20 oddToken, uint amount) public onlyLauncher { if (address(oddToken) == address(0)) { launcher.transfer(amount); return; } oddToken.transfer(launcher, amount); } } contract WhiteListed is Operatable, WhiteListedBasic, Salvageable { uint public count; mapping (address => bool) public whiteList; event Whitelisted(address indexed addr, uint whitelistedCount, bool isWhitelisted); function addWhiteListed(address[] addrs) external canOperate { uint c = count; for (uint i = 0; i < addrs.length; i++) { if (!whiteList[addrs[i]]) { whiteList[addrs[i]] = true; c++; emit Whitelisted(addrs[i], count, true); } } count = c; } function removeWhiteListed(address addr) external canOperate { require(whiteList[addr]); whiteList[addr] = false; count--; emit Whitelisted(addr, count, false); } function isWhiteListed(address addr) external view returns (bool) { return whiteList[addr]; } } contract GoConfig { string public constant NAME = "GOeureka"; string public constant SYMBOL = "GOT"; uint8 public constant DECIMALS = 18; uint public constant DECIMALSFACTOR = 10 ** uint(DECIMALS); uint public constant TOTALSUPPLY = 1000000000 * DECIMALSFACTOR; } contract GOeureka is Salvageable, PausableToken, GoConfig { using SafeMath for uint; string public name = NAME; string public symbol = SYMBOL; uint8 public decimals = DECIMALS; bool public mintingFinished = false; event Mint(address indexed to, uint amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } constructor() public { paused = true; } function mint(address _to, uint _amount) ownerOrMinter canMint public returns (bool) { require(totalSupply_.add(_amount) <= TOTALSUPPLY); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() ownerOrMinter canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function sendBatchCS(address[] _recipients, uint[] _values) external ownerOrMinter returns (bool) { require(_recipients.length == _values.length); uint senderBalance = balances[msg.sender]; for (uint i = 0; i < _values.length; i++) { uint value = _values[i]; address to = _recipients[i]; require(senderBalance >= value); senderBalance = senderBalance - value; balances[to] += value; emit Transfer(msg.sender, to, value); } balances[msg.sender] = senderBalance; return true; } // Lifted from ERC827 /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall( address _to, uint256 _value, bytes _data ) public payable whenNotPaused returns (bool) { require(_to != address(this)); super.transfer(_to, _value); // solium-disable-next-line security/no-call-value require(_to.call.value(msg.value)(_data)); return true; } } contract gotTokenSaleConfig is GoConfig { uint public constant MIN_PRESALE = 10 ether; uint public constant VESTING_AMOUNT = 100000000 * DECIMALSFACTOR; address public constant VESTING_WALLET = 0xf0cf34Be9cAB4354b228193FF4F6A2C61DdE95f4; // <<============================ uint public constant RESERVE_AMOUNT = 300000000 * DECIMALSFACTOR; address public constant RESERVE_WALLET = 0x83Fee7D53b6A5B5fD0d60b772c2B56b02D8835da; // <<============================ uint public constant PRESALE_START = 1529035246; // Friday, June 15, 2018 12:00:46 PM GMT+08:00 uint public constant SALE_START = PRESALE_START + 4 weeks; uint public constant SALE_CAP = 600000000 * DECIMALSFACTOR; address public constant MULTISIG_ETH = RESERVE_WALLET; } contract GOeurekaSale is Claimable, gotTokenSaleConfig, Pausable, Salvageable { using SafeMath for uint256; // The token being sold GOeureka public token; WhiteListedBasic public whiteListed; // start and end block where investments are allowed uint256 public presaleStart; uint256 public presaleEnd; uint256 public week1Start; uint256 public week1End; uint256 public week2End; uint256 public week3End; // Caps are in ETHER not tokens - need to back calculate to get token cap uint256 public presaleCap; uint256 public week1Cap; uint256 public week2Cap; uint256 public week3Cap; // Minimum contribution is now calculated uint256 public minContribution; uint public currentCap; //uint256[] public cap; // address where funds are collected address public multiSig; // amount of raised funds in wei from private, presale and main sale uint256 public weiRaised; // amount of raised tokens uint256 public tokensRaised; // number of participants mapping(address => uint256) public contributions; uint256 public numberOfContributors = 0; // for rate uint public basicRate; // EVENTS event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event SaleClosed(); event HardcapReached(); event NewCapActivated(uint256 newCap); // CONSTRUCTOR constructor(GOeureka token_, WhiteListedBasic _whiteListed) public { calcDates(PRESALE_START, SALE_START); // Continuous sale basicRate = 3000; // TokensPerEther calculateRates(); multiSig = MULTISIG_ETH; // NOTE - toke token = token_; whiteListed = _whiteListed; } bool allocated = false; function mintAllocations() external onlyOwner { require(!allocated); allocated = true; token.mint(VESTING_WALLET,VESTING_AMOUNT); token.mint(RESERVE_WALLET,RESERVE_AMOUNT); } function setDates(uint presaleStart_, uint saleStart) external onlyOwner { calcDates(presaleStart_, saleStart); } function calcDates(uint presaleStart_, uint saleStart) internal { require(weiRaised == 0); require(now < presaleStart_); require(presaleStart_ < saleStart); presaleStart = presaleStart_; week1Start = saleStart; presaleEnd = saleStart; week1End = week1Start + 1 weeks; week2End = week1Start + 2 weeks; week3End = week1Start + 4 weeks; } function setWallet(address _newWallet) public onlyOwner { multiSig = _newWallet; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { if (now > week3End) return true; if (tokensRaised >= SALE_CAP) return true; // if we reach the tokensForSale return false; } // Buyer must be whitelisted function isWhiteListed(address beneficiary) internal view returns (bool) { return whiteListed.isWhiteListed(beneficiary); } modifier onlyAuthorised(address beneficiary) { require(isWhiteListed(beneficiary),"Not authorised"); require (now >= presaleStart,"too early"); require (!hasEnded(),"ended"); require (multiSig != 0x0,"MultiSig empty"); require ((msg.value > minContribution) || (weiRaised.add(minContribution) > week3Cap),"Value too small"); _; } function setNewRate(uint newRate) onlyOwner public { require(weiRaised == 0); require(0 < newRate && newRate < 5000); basicRate = newRate; calculateRates(); } function calculateRates() internal { presaleCap = uint(150000000 * DECIMALSFACTOR).div(basicRate); week1Cap = presaleCap.add(uint(100000000 * DECIMALSFACTOR).div(basicRate)); week2Cap = week1Cap.add(uint(100000000 * DECIMALSFACTOR).div(basicRate)); week3Cap = week2Cap.add(uint(200000000 * DECIMALSFACTOR).div(basicRate)); minContribution = uint(100 * DECIMALSFACTOR).div(basicRate); currentCap = presaleCap; } function getTokens(uint256 amountInWei) internal view returns (uint256 tokens, uint256 currentCap_) { if ((now < week1Start) && (weiRaised < presaleCap)) { require(amountInWei.add(contributions[msg.sender]) >= MIN_PRESALE); // if already sent min_presale, allow topup return (amountInWei.mul(basicRate).mul(115).div(100), presaleCap); } if ((now <= week1End) && (weiRaised < week1Cap)) { return (amountInWei.mul(basicRate).mul(110).div(100), week1Cap); } if ((now <= week2End) && (weiRaised < week2Cap)) { return (amountInWei.mul(basicRate).mul(105).div(100), week2Cap); } if ((now <= week3End) && (weiRaised < week3Cap)) { return (amountInWei.mul(basicRate), week3Cap); } revert(); } // low level token purchase function function buyTokens(address beneficiary, uint256 value) internal onlyAuthorised(beneficiary) whenNotPaused { uint256 newTokens; uint256 newestTokens; uint256 thisPhase = value; uint256 nextPhase = 0; uint256 refund = 0; if (weiRaised.add(value) > currentCap) { // exceeds current tranche? thisPhase = currentCap.sub(weiRaised); nextPhase = value.sub(thisPhase); } (newTokens, currentCap) = getTokens(thisPhase); weiRaised = weiRaised.add(thisPhase); // if we have bridged two tranches.... if (nextPhase > 0) { if (weiRaised.add(nextPhase) <= week3Cap) { // another phase to enter weiRaised = weiRaised.add(nextPhase); (newestTokens, currentCap) = getTokens(nextPhase); newTokens = newTokens.add(newestTokens); emit NewCapActivated(currentCap); } else { // sale is complete... refund = nextPhase; nextPhase = 0; emit HardcapReached(); } } if (contributions[beneficiary] == 0) { numberOfContributors++; } contributions[beneficiary] = contributions[beneficiary].add(thisPhase).add(nextPhase); tokensRaised = tokensRaised.add(newTokens); token.mint(beneficiary,newTokens); emit TokenPurchase(beneficiary, thisPhase.add(nextPhase), newTokens); multiSig.transfer(thisPhase.add(nextPhase)); if (refund > 0) { beneficiary.transfer(refund); } } function placeTokens(address beneficiary, uint256 tokens) public onlyOwner { require(now < presaleStart); tokensRaised = tokensRaised.add(tokens); token.mint(beneficiary,tokens); } // Complete the sale function finishSale() public onlyOwner { require(hasEnded()); token.finishMinting(); emit SaleClosed(); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender, msg.value); } }
return true if crowdsale event has ended
function hasEnded() public view returns (bool) { if (now > week3End) return true; if (tokensRaised >= SALE_CAP) return false; }
196,470
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IVestingVault.sol"; contract VestingVault is IVestingVault, Ownable { using SafeMath for uint256; using SafeMath for uint16; using SafeERC20 for IERC20; struct Grant { uint256 amount; uint16 vestingDuration; uint16 daysClaimed; uint256 totalClaimed; address recipient; } event GrantAdded(address indexed recipient); event GrantTokensClaimed(address indexed recipient, uint256 amountClaimed); event GrantRevoked( address recipient, uint256 amountVested, uint256 amountNotVested ); IERC20 public token; mapping(address => Grant) private tokenGrants; uint256 public totalVestingCount; uint256 public claimBeginTime = 0; uint16 public vestingDurationInDays = 10; address public tokenWallet; address public associateContract; constructor() {} function setToken(address _token) public onlyOwner returns (bool) { require(address(_token) != address(0)); token = IERC20(_token); return true; } function setClaimBeginTime(uint256 _claimBeginTime) public onlyOwner returns (bool) { require(_claimBeginTime != 0); claimBeginTime = _claimBeginTime; return true; } function setTokenWallet(address _tokenWallet) public onlyOwner returns (bool) { require(address(_tokenWallet) != address(0)); tokenWallet = _tokenWallet; return true; } function setAssociateContract(address _associateContract) public onlyOwner returns (bool) { require( _associateContract != address(0), "associateContract is the zero address" ); associateContract = _associateContract; return true; } function addTokenGrant( address _recipient, uint256 _amount ) external override onlyOwnerOrAssociateContract { require( tokenGrants[_recipient].amount == 0, "Grant already exists, must revoke first." ); uint256 amountVestedPerDay = _amount.div(vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay > 0"); // Transfer the grant tokens under the control of the vesting contract // require(token.transferFrom(owner(), address(this), _amount)); Grant memory grant = Grant({ amount: _amount, vestingDuration: vestingDurationInDays, daysClaimed: 0, totalClaimed: 0, recipient: _recipient }); tokenGrants[_recipient] = grant; emit GrantAdded(_recipient); } /// @notice Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested function claimVestedTokens() external override { require( claimBeginTime > 0 && currentTime() >= claimBeginTime, "claim has not yet started" ); uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(msg.sender); require(amountVested > 0, "Vested is 0"); Grant storage tokenGrant = tokenGrants[msg.sender]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested)); tokenGrant.totalClaimed = uint256( tokenGrant.totalClaimed.add(amountVested) ); token.safeTransferFrom(tokenWallet, tokenGrant.recipient, amountVested); emit GrantTokensClaimed(tokenGrant.recipient, amountVested); } /// @notice Terminate token grant transferring all vested tokens to the `_recipient` /// and returning all non-vested tokens to the contract owner /// Secured to the contract owner only /// @param _recipient address of the token grant recipient function revokeTokenGrant(address _recipient) external override onlyOwner { Grant storage tokenGrant = tokenGrants[_recipient]; uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_recipient); uint256 amountNotVested = (tokenGrant.amount.sub(tokenGrant.totalClaimed)).sub(amountVested); require(token.transfer(owner(), amountNotVested)); require(token.transfer(_recipient, amountVested)); tokenGrant.amount = 0; tokenGrant.vestingDuration = 0; tokenGrant.daysClaimed = 0; tokenGrant.totalClaimed = 0; tokenGrant.recipient = address(0); emit GrantRevoked(_recipient, amountVested, amountNotVested); } function getGrantAmount(address _recipient) public view returns (uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; return tokenGrant.amount; } /// @notice Calculate the vested and unclaimed months and tokens available for `_grantId` to claim /// Due to rounding errors once grant duration is reached, returns the entire left grant amount /// Returns (0, 0) if cliff has not been reached function calculateGrantClaim(address _recipient) public view returns (uint16, uint256) { Grant storage tokenGrant = tokenGrants[_recipient]; require( tokenGrant.totalClaimed < tokenGrant.amount, "Grant fully claimed" ); // For grants created with a future start date, that hasn't been reached, return 0, 0 if (claimBeginTime == 0 || currentTime() < claimBeginTime) { return (0, 0); } // Check cliff was reached uint256 elapsedDays = currentTime().sub(claimBeginTime - 1 days).div(1 days); // If over vesting duration, all tokens vested if (elapsedDays >= tokenGrant.vestingDuration) { uint256 remainingGrant = tokenGrant.amount.sub(tokenGrant.totalClaimed); return (tokenGrant.vestingDuration, remainingGrant); } else { uint16 daysVested = uint16(elapsedDays.sub(tokenGrant.daysClaimed)); uint256 amountVestedPerDay = tokenGrant.amount.div(uint256(tokenGrant.vestingDuration)); uint256 amountVested = uint256(daysVested.mul(amountVestedPerDay)); return (daysVested, amountVested); } } function currentTime() private view returns (uint256) { return block.timestamp; } modifier onlyOwnerOrAssociateContract() { require( owner() == _msgSender() || _msgSender() == associateContract, "Ownable: caller is not the owner" ); _; } }
Transfer the grant tokens under the control of the vesting contract require(token.transferFrom(owner(), address(this), _amount));
function addTokenGrant( address _recipient, uint256 _amount ) external override onlyOwnerOrAssociateContract { require( tokenGrants[_recipient].amount == 0, "Grant already exists, must revoke first." ); uint256 amountVestedPerDay = _amount.div(vestingDurationInDays); require(amountVestedPerDay > 0, "amountVestedPerDay > 0"); Grant memory grant = Grant({ amount: _amount, vestingDuration: vestingDurationInDays, daysClaimed: 0, totalClaimed: 0, recipient: _recipient }); tokenGrants[_recipient] = grant; emit GrantAdded(_recipient); }
6,414,552