// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [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.
* ====
*/functionisContract(address account) internalviewreturns (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://consensys.net/diligence/blog/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.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable 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._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, "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._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
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._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, "Address: insufficient balance for call");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
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._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
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._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 37: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 3 of 37: ERC1155Holder.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)pragmasolidity ^0.8.0;import"./ERC1155Receiver.sol";
/**
* Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*
* @dev _Available since v3.1._
*/contractERC1155HolderisERC1155Receiver{
functiononERC1155Received(address,
address,
uint256,
uint256,
bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC1155Received.selector;
}
functiononERC1155BatchReceived(address,
address,
uint256[] memory,
uint256[] memory,
bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^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.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 6 of 37: ERC721Holder.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/utils/ERC721Holder.sol)pragmasolidity ^0.8.0;import"../IERC721Receiver.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}.
*/contractERC721HolderisIERC721Receiver{
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address, address, uint256, bytesmemory) publicvirtualoverridereturns (bytes4) {
returnthis.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)pragmasolidity ^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._
*/interfaceIERC1155isIERC165{
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/eventTransferSingle(addressindexed operator, addressindexedfrom, addressindexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/eventTransferBatch(addressindexed operator,
addressindexedfrom,
addressindexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/eventApprovalForAll(addressindexed account, addressindexed 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}.
*/eventURI(string value, uint256indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/functionbalanceOf(address account, uint256 id) externalviewreturns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] calldata accounts,
uint256[] calldata ids
) externalviewreturns (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.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/functionisApprovedForAll(address account, address operator) externalviewreturns (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 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.
*/functionsafeTransferFrom(addressfrom, address to, uint256 id, uint256 amount, bytescalldata 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.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytescalldata data
) external;
}
Contract Source Code
File 10 of 37: IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)pragmasolidity ^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._
*/interfaceIERC1155MetadataURIisIERC1155{
/**
* @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.
*/functionuri(uint256 id) externalviewreturns (stringmemory);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/interfaceIERC1155ReceiverisIERC165{
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/functiononERC1155Received(address operator,
addressfrom,
uint256 id,
uint256 value,
bytescalldata data
) externalreturns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/functiononERC1155BatchReceived(address operator,
addressfrom,
uint256[] calldata ids,
uint256[] calldata values,
bytescalldata data
) externalreturns (bytes4);
}
Contract Source Code
File 13 of 37: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^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}.
*/interfaceIERC165{
/**
* @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.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 14 of 37: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/interfaceIERC20Permit{
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/functionpermit(address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/functionnonces(address owner) externalviewreturns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/// solhint-disable-next-line func-name-mixedcasefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
}
Contract Source Code
File 17 of 37: IERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)pragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId, bytescalldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must 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.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* 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.
*/functiontransferFrom(addressfrom, 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.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
// SPDX-License-Identifier: MITpragmasolidity 0.8.21;import {SubscriptionType, PayOption, Tariff, Ticket} from"../contracts/SubscriptionRegistry.sol";
interfaceISubscriptionRegistry{
/**
* @notice Add new tariff for caller
* @dev Call this method from ServiceProvider
* for setup new tariff
* using `Tariff` data type(please see above)
*
* @param _newTariff full encded Tariff object
* @return last added tariff index in Tariff[] array
* for current Service Provider (msg.sender)
*/functionregisterServiceTariff(Tariff calldata _newTariff) externalreturns(uint256);
/**
* @notice Authorize agent for caller service provider
* @dev Call this method from ServiceProvider
*
* @param _agent - address of contract that implement Agent role
* @param _serviceTariffIndexes - array of index in `availableTariffs` array
* that available for given `_agent`
* @return full array of actual tarifs for this agent
*/functionauthorizeAgentForService(address _agent,
uint256[] calldata _serviceTariffIndexes
) externalreturns (uint256[] memory);
/**
* @notice By Ticket for subscription
* @dev Call this method from Agent
*
* @param _service - Service Provider address
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @param _buyFor - address for whome this ticket would be bought
* @param _payer - address of payer for this ticket
* @return ticket structure that would be use for validate service process
*/functionbuySubscription(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex,
address _buyFor,
address _payer
) externalpayablereturns(Ticket memory ticket);
/**
* @notice Edit tariff for caller
* @dev Call this method from ServiceProvider
* for setup new tariff
* using `Tariff` data type(please see above)
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _timelockPeriod - see SubscriptionType notice above
* @param _ticketValidPeriod - see SubscriptionType notice above
* @param _counter - see SubscriptionType notice above
* @param _isAvailable - see SubscriptionType notice above
* @param _beneficiary - see SubscriptionType notice above
*/functioneditServiceTariff(uint256 _tariffIndex,
uint256 _timelockPeriod,
uint256 _ticketValidPeriod,
uint256 _counter,
bool _isAvailable,
address _beneficiary
) external;
/**
* @notice Add tariff PayOption for exact service
* @dev Call this method from ServiceProvider
* for add tariff PayOption
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _paymentToken - see PayOption notice above
* @param _paymentAmount - see PayOption notice above
* @param _agentFeePercent - see PayOption notice above
* @return last added PaymentOption index in array
* for _tariffIndex Tariff of caller Service Provider (msg.sender)
*/functionaddTariffPayOption(uint256 _tariffIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) externalreturns(uint256);
/**
* @notice Edit tariff PayOption for exact service
* @dev Call this method from ServiceProvider
* for edit tariff PayOption
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @param _paymentToken - see PayOption notice above
* @param _paymentAmount - see PayOption notice above
* @param _agentFeePercent - see PayOption notice above
* for _tariffIndex Tariff of caller Service Provider (msg.sender)
*/functioneditTariffPayOption(uint256 _tariffIndex,
uint256 _payWithIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) external;
/**
* @notice Check that `_user` have still valid ticket for this service.
* @dev Call this method from any context
*
* @param _user - address of user who has an ticket and who trying get service
* @param _service - address of Service Provider
* @return ok True in case ticket is valid
* @return needFix True in case ticket has counter > 0
*/functioncheckUserSubscription(address _user,
address _service
) externalviewreturns (bool ok, bool needFix);
/**
* @notice Check that `_user` have still valid ticket for this service.
* Decrement ticket counter in case it > 0
* @dev Call this method from ServiceProvider
*
* @param _user - address of user who has an ticket and who trying get service
* @return ok True in case ticket is valid
*/functioncheckAndFixUserSubscription(address _user) externalreturns (bool ok);
/**
* @notice Decrement ticket counter in case it > 0
* @dev Call this method from new SubscriptionRegistry in case of upgrade
*
* @param _user - address of user who has an ticket and who trying get service
* @param _serviceFromProxy - address of service from more new SubscriptionRegistry contract
*/functionfixUserSubscription(address _user, address _serviceFromProxy) external;
/**
* @notice Returns `_user` ticket for this service.
* @dev Call this method from any context
*
* @param _user - address of user who has an ticket and who trying get service
* @param _service - address of Service Provider
* @return ticket
*/functiongetUserTicketForService(address _service,
address _user
) externalviewreturns(Ticket memory);
/**
* @notice Returns array of Tariff for `_service`
* @dev Call this method from any context
*
* @param _service - address of Service Provider
* @return Tariff array
*/functiongetTariffsForService(address _service) externalviewreturns (Tariff[] memory);
/**
* @notice Returns ticket price include any fees
* @dev Call this method from any context
*
* @param _service - address of Service Provider
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @return tulpe with payment token an ticket price
*/functiongetTicketPrice(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex
) externalviewreturns (address, uint256);
/**
* @notice Returns array of Tariff for `_service` assigned to `_agent`
* @dev Call this method from any context
*
* @param _agent - address of Agent
* @param _service - address of Service Provider
* @return Tariff array
*/functiongetAvailableAgentsTariffForService(address _agent,
address _service
) externalviewreturns(Tariff[] memory);
}
// SPDX-License-Identifier: MIT// ENVELOP(NIFTSY) NFT(wNFT) Kiosk.pragmasolidity 0.8.21;import"@envelop-protocol-v1/contracts/TokenServiceExtended.sol";
import"@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import"@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import"@openzeppelin/contracts/security/ReentrancyGuard.sol";
//import "./KTypes.sol";import"../interfaces/IDisplayPriceModel.sol";
//import "./DefaultPriceModel.sol";contractNFTKioskisTokenServiceExtended,
ReentrancyGuard,
ERC721Holder,
ERC1155Holder{
uint256constantpublic DEFAULT_INDEX =0;
uint256constantpublic PERCENT_DENOMINATOR =10000;
bytes32immutablepublic DEFAULT_DISPLAY = hlpHashString('NFTKiosk');
mapping(bytes32=> KTypes.Display) public displays;
mapping(bytes32=>address[]) public displayAdmins;
// mapping from contract address & tokenId to Place(displayHash and index)mapping(address=>mapping(uint256=> KTypes.Place)) public assetAtDisplay;
eventDisplayChanged(bytes32indexed display,
addressindexed owner,
addressindexed beneficiary, // who will receive assets from saleuint256 enableAfter,
uint256 disableAfter,
address priceModel,
string name
);
eventDisplayTransfer(bytes32indexed display,
addressindexedfrom,
addressindexed newOwner
);
eventItemAddedToDisplay(bytes32indexed display,
addressindexed assetContract,
uint256indexed assetTokenId,
uint256 placeIndex
);
eventItemPriceChanged(bytes32indexed display,
addressindexed assetContract,
uint256indexed assetTokenId
);
eventEnvelopPurchase(bytes32indexed display,
addressindexed assetContract,
uint256indexed assetTokenId
);
eventEnvelopReferrer(addressindexed referrer,
addressindexed customer,
addressindexed payWithToken,
uint256 payWithAmount,
uint16 percentDiscount
);
functionsetDisplayParams(stringcalldata _name,
address _beneficiary, // who will receive assets from saleuint256 _enableAfter,
uint256 _disableAfter,
address _priceModel
) publicvirtual{
// require(// displays[DEFAULT_DISPLAY].owner != address(0),// "DEFAULT DISPLAY must be created first"// );// TODO Check that model is whitelisted.. ??Ask Alexbytes32 _displayNameHash = hlpHashString(_name);
require(
(displays[_displayNameHash].owner ==msg.sender// edit existing||displays[_displayNameHash].owner ==address(0)), // create new"Only for Display Owner"
);
_setDisplayParams(
_displayNameHash,
msg.sender,
_beneficiary, // who will receive assets from sale
_enableAfter,
_disableAfter,
_priceModel
);
emit DisplayChanged(
_displayNameHash,
msg.sender,
_beneficiary, // who will receive assets from sale
_enableAfter,
_disableAfter,
_priceModel,
_name
);
}
functiontransferDisplay(address _to, bytes32 _displayNameHash)
external{
require(displays[_displayNameHash].owner ==msg.sender, "Only for Display Owner");
displays[_displayNameHash].owner = _to;
emit DisplayTransfer(_displayNameHash, msg.sender, _to);
}
// TODO Check that display existsfunctionaddItemToDisplay(bytes32 _displayNameHash,
ETypes.AssetItem memory _assetItem,
KTypes.Price[] calldata _prices
)
publicreturns (KTypes.Place memory place)
{
// We need two checks. // 1. Only item with zero place (display and index) can be added // to exact display
KTypes.Place memory p =
assetAtDisplay[_assetItem.asset.contractAddress][_assetItem.tokenId];
require(
p.display ==bytes32(0) && p.index ==0,
"Already at display"
);
// 2. Item has been transfered to this contract// Next check is For 721 only. Because 1155 standard // has no `ownerOf` method. Hence we can't use simple (implicit)// erc1155 transfer for put item at display. // In this implementation you cant`t 'edit' display after// simple (implicit) adding item to display // if (_ownerOf(_assetItem) != address(this)) {// Do transfer to this contractrequire(_assetItem.amount
<=_transferSafe(_assetItem, msg.sender, address(this)),
"Insufficient balance after NFT transfer"
);
// }// DEFAULT_DISPLAY accept items from any addressesif (msg.sender!= displays[_displayNameHash].owner) {
require(
_displayNameHash == DEFAULT_DISPLAY,
"Only Default Display allow for any"
);
}
place = _addItemRecordAtDisplay(
_displayNameHash,
msg.sender, // Item Owner
_assetItem,
_prices
);
emit ItemAddedToDisplay(
place.display,
_assetItem.asset.contractAddress,
_assetItem.tokenId,
place.index
);
}
functionaddBatchItemsToDisplayWithSamePrice(bytes32 _displayNameHash,
ETypes.AssetItem[] memory _assetItems,
KTypes.Price[] calldata _prices
)
externalreturns (KTypes.Place[] memory)
{
// Lets calc and create array var for result
KTypes.Place[] memory pls =new KTypes.Place[](_assetItems.length);
for (uint256 i =0; i < _assetItems.length; ++i){
pls[i] = addItemToDisplay(_displayNameHash,_assetItems[i],_prices);
}
return pls;
}
functionaddAssetItemPriceAtIndex(
ETypes.AssetItem calldata _assetItem,
KTypes.Price[] calldata _prices
)
external{
KTypes.Place memory p = getAssetItemPlace(_assetItem);
// check that sender is item owner or display owner(if item owner not set)if (displays[p.display].items[p.index].owner !=msg.sender)
{
require(
displays[p.display].owner ==msg.sender,
"Only display owner can edit price"
);
}
_addItemPriceAtIndex(p.display, p.index, _prices);
emit ItemPriceChanged(
p.display,
_assetItem.asset.contractAddress,
_assetItem.tokenId
);
}
functioneditAssetItemPriceAtIndex(
ETypes.AssetItem calldata _assetItem,
uint256 _priceIndex,
KTypes.Price calldata _price
)
external{
KTypes.Place memory p = getAssetItemPlace(_assetItem);
// check that sender is item owner or display owner(if item owner not set)if (displays[p.display].items[p.index].owner !=msg.sender)
{
require(displays[p.display].owner ==msg.sender, "Only for display owner");
}
_editItemPriceAtIndex(p.display, p.index, _priceIndex ,_price);
emit ItemPriceChanged(
p.display,
_assetItem.asset.contractAddress,
_assetItem.tokenId
);
}
functionremoveLastPersonalPriceForAssetItem(
ETypes.AssetItem calldata _assetItem
)
external{
KTypes.Place memory p = getAssetItemPlace(_assetItem);
// check that sender is item owner or display owner(if item owner not set)if (displays[p.display].items[p.index].owner !=msg.sender)
{
require(displays[p.display].owner ==msg.sender, "Only for display owner");
}
KTypes.Price[] storage priceArray = displays[p.display].items[p.index].prices;
priceArray.pop();
emit ItemPriceChanged(
p.display,
_assetItem.asset.contractAddress,
_assetItem.tokenId
);
}
functionbuyAssetItem(
ETypes.AssetItem calldata _assetItem,
uint256 _priceIndex,
address _buyer,
address _referrer,
stringcalldata _promo
) externalvirtualpayablenonReentrant{
// 1.Define exact asset price with discounts
ETypes.AssetItem memory payWithItem;
{ // Against stack too deep
(KTypes.Price[] memory pArray, KTypes.Discount[] memory dArray)
= _getAssetItemPricesAndDiscounts(
_assetItem, _buyer, _referrer, hlpHashString(_promo)
);
uint256 totalDiscountPercent;
for (uint256 i =0; i < dArray.length; ++ i){
totalDiscountPercent += dArray[i].dsctPercent;
if (dArray[i].dsctType ==KTypes.DiscountType.REFERRAL){
emit EnvelopReferrer(
_referrer, msg.sender,
pArray[_priceIndex].payWith,
pArray[_priceIndex].amount,
uint16(dArray[i].dsctPercent)
);
}
}
payWithItem = ETypes.AssetItem(
ETypes.Asset(
pArray[_priceIndex].payWith ==address(0)
?ETypes.AssetType.NATIVE
:ETypes.AssetType.ERC20,
pArray[_priceIndex].payWith
),
0,
pArray[_priceIndex].amount
* (PERCENT_DENOMINATOR - totalDiscountPercent) / PERCENT_DENOMINATOR
);
}
// 2. Manage display records for different cases
KTypes.Place memory p = getAssetItemPlace(_assetItem);
address beneficiary;
// Case when NFT just transfered to kiosk contractif (p.display ==bytes32(0)) {
// isImplicitAdded = true;
beneficiary = displays[DEFAULT_DISPLAY].beneficiary;
p.display = DEFAULT_DISPLAY;
p.index = DEFAULT_INDEX;
} else {
beneficiary = displays[p.display].beneficiary;
// 2.1 remove item from display
_removeAssetItemRecord(p.display, p.index,_assetItem);
}
require(
displays[p.display].enableAfter <block.timestamp&& displays[p.display].disableAfter >=block.timestamp,
"Only in time"
);
// 3.Receive payment or buy for freeif (!_canBuyForFree(p.display, msg.sender)) {
_receivePayment(payWithItem, beneficiary);
}
// 4. Send asset to buyer
_transferSafe(_assetItem, address(this), _buyer);
emit EnvelopPurchase(p.display, _assetItem.asset.contractAddress, _assetItem.tokenId);
}
functionaddAdminToDisplay(bytes32 _displayNameHash, address _admin)
external{
require(
displays[_displayNameHash].owner ==msg.sender,
"Only display owner can add admins"
);
// Check that admin already exist or notrequire(
!_isDisplayAdmin(_displayNameHash, _admin),
"Already admin"
);
displayAdmins[_displayNameHash].push(_admin);
}
functionremoveAdminFromDisplayByIndex(bytes32 _displayNameHash, uint256 _adminIndex)
external{
require(
displays[_displayNameHash].owner ==msg.sender,
"Only display owner can add admins"
);
address[] storage admins = displayAdmins[_displayNameHash];
if (_adminIndex != admins.length-1) {
admins[_adminIndex] = admins[admins.length-1];
}
admins.pop();
}
//////////////////////////////////////////////////////////////functiongetDisplayOwner(bytes32 _displayNameHash) publicviewreturns (address) {
return displays[_displayNameHash].owner;
}
functiongetDisplay(bytes32 _displayNameHash)
publicviewreturns (KTypes.Display memory)
{
return displays[_displayNameHash];
}
functiongetAssetItemPlace(ETypes.AssetItem memory _assetItem)
publicviewreturns (KTypes.Place memory)
{
if (_assetItem.asset.assetType == ETypes.AssetType.ERC721) {
// ERC721require(
_ownerOf(_assetItem) ==address(this),
"Asset not transfered to kiosk"
);
} else {
//ERC1155 or other**require(
//_balanceOf(_assetItem, address(this)) >= _assetItem.amount,
_balanceOf(_assetItem, address(this)) >0,
"Asset not transfered to kiosk"
);
}
return assetAtDisplay[_assetItem.asset.contractAddress][_assetItem.tokenId];
}
functiongetAssetItemPricesAndDiscounts(
ETypes.AssetItem memory _assetItem,
address _buyer,
address _referrer,
stringcalldata _promo
)
externalviewreturns (KTypes.Price[] memory, KTypes.Discount[] memory)
{
return _getAssetItemPricesAndDiscounts(
_assetItem,
_buyer,
_referrer,
hlpHashString(_promo)
);
}
/// @notice Returns ONLY items that was added with `addItemToDisplay`./// @dev For obtain all items please use envelop oraclefunctiongetDisplayAssetItems(bytes32 _displayNameHash)
publicviewvirtualreturns (KTypes.ItemForSale[] memory)
{
return displays[_displayNameHash].items;
}
functiongetAssetItem(ETypes.AssetItem memory _assetItem)
publicviewreturns (KTypes.ItemForSale memory)
{
KTypes.Place memory p = getAssetItemPlace(_assetItem);
return displays[p.display].items[p.index];
}
functionhlpHashString(stringmemory _name) publicpurereturns (bytes32) {
returnkeccak256(abi.encode(_name));
}
functioncanBuyForFree(bytes32 _displayNameHash, address _who)
externalviewreturns(bool)
{
return _canBuyForFree(_displayNameHash, _who);
}
functionisDisplayAdmin(bytes32 _displayNameHash, address _who)
externalviewreturns(bool)
{
return _isDisplayAdmin(_displayNameHash, _who);
}
//////////////////////////////// Internals ///////////////////////////////function_setDisplayParams(bytes32 _displayNameHash,
address _owner,
address _beneficiary, // who will receive assets from saleuint256 _enableAfter,
uint256 _disableAfter,
address _priceModel
)
internal{
KTypes.Display storage d = displays[_displayNameHash];
d.owner = _owner;
d.beneficiary = _beneficiary;
d.enableAfter = _enableAfter;
d.disableAfter = _disableAfter;
d.priceModel = _priceModel;
}
function_addItemRecordAtDisplay(bytes32 _displayNameHash,
address _itemOwner,
ETypes.AssetItem memory _nft,
KTypes.Price[] calldata _prices
)
internalreturns (KTypes.Place memory)
{
KTypes.ItemForSale storage it = displays[_displayNameHash].items.push();
it.owner = _itemOwner;
it.nft = _nft;
if (_prices.length>0){
for (uint256 i =0; i < _prices.length; ++ i) {
it.prices.push(_prices[i]);
}
}
// add to mapping assetAtDisplay
assetAtDisplay[_nft.asset.contractAddress][_nft.tokenId] = KTypes.Place(
_displayNameHash,
displays[_displayNameHash].items.length-1
);
return assetAtDisplay[_nft.asset.contractAddress][_nft.tokenId];
}
function_addItemPriceAtIndex(bytes32 _displayNameHash,
uint256 _itemIndex,
KTypes.Price[] calldata _prices
)
internal{
KTypes.ItemForSale storage it = displays[_displayNameHash].items[_itemIndex];
for (uint256 i =0; i < _prices.length; ++ i) {
it.prices.push(_prices[i]);
}
}
function_editItemPriceAtIndex(bytes32 _displayNameHash,
uint256 _itemIndex,
uint256 _priceIndex,
KTypes.Price calldata _price
)
internal{
displays[_displayNameHash].items[_itemIndex].prices[_priceIndex] = _price;
}
function_removeAssetItemRecord(bytes32 _displayNameHash,
uint256 _itemIndex,
ETypes.AssetItem calldata _assetItem
)
internal{
// 2.1 remove item from displayif (_itemIndex != displays[_displayNameHash].items.length-1) {
// if asset item is not last array element// then replace it with last element
displays[_displayNameHash].items[_itemIndex] = displays[_displayNameHash].items[
displays[_displayNameHash].items.length-1
];
// and change last element that was moved in above string
assetAtDisplay[
displays[_displayNameHash].items[_itemIndex].nft.asset.contractAddress // address of just moved nft
][
displays[_displayNameHash].items[_itemIndex].nft.tokenId
] = KTypes.Place(
_displayNameHash,
_itemIndex
);
}
// remove last element from array
displays[_displayNameHash].items.pop();
// delete mapping elementdelete assetAtDisplay[_assetItem.asset.contractAddress][_assetItem.tokenId];
}
function_receivePayment(
ETypes.AssetItem memory _payWithItem,
address _beneficiary
) internal{
// There are two different cases: native token and erc20if (_payWithItem.asset.assetType == ETypes.AssetType.NATIVE )
//if (pArray[_priceIndex].payWith == address(0))
{
// Native token paymentrequire(_payWithItem.amount
<= _transferSafe(_payWithItem, address(this), _beneficiary),
"Insufficient balance after payment transfer"
);
// Return changeif ((msg.value- _payWithItem.amount) >0) {
addresspayable s =payable(msg.sender);
s.transfer(msg.value- _payWithItem.amount);
}
} else {
// ERC20 token paymentrequire(msg.value==0, "Only ERC20 tokens");
require(_payWithItem.amount
<=_transferSafe(_payWithItem, msg.sender, _beneficiary),
"Insufficient balance after payment transfer"
);
}
}
function_getAssetItemPricesAndDiscounts(
ETypes.AssetItem memory _assetItem,
address _buyer,
address _referrer,
bytes32 _promoHash
)
internalviewvirtualreturns(KTypes.Price[] memory, KTypes.Discount[] memory)
{
// Define current asset Place
KTypes.Place memory pl = getAssetItemPlace(_assetItem);
// implicit adding case - without call addItemToDisplay, just transfer // So get prices from modelif (pl.display ==bytes32(0) && pl.index ==0){
return (
IDisplayPriceModel(displays[DEFAULT_DISPLAY].priceModel).getItemPrices(_assetItem),
IDisplayPriceModel(displays[DEFAULT_DISPLAY].priceModel).getItemDiscounts(
_assetItem,
_buyer,
_referrer,
_promoHash
)
);
}
// If exist individual prices for exact item then return itif (displays[pl.display].items[pl.index].prices.length>0)
{
return (
displays[pl.display].items[pl.index].prices,
IDisplayPriceModel(displays[pl.display].priceModel).getItemDiscounts(
_assetItem,
_buyer,
_referrer,
_promoHash
)
);
}
// If there is no individual prices then need ask priceModel contract of displayreturn (
IDisplayPriceModel(displays[pl.display].priceModel).getItemPrices(_assetItem),
IDisplayPriceModel(displays[pl.display].priceModel).getItemDiscounts(
_assetItem,
_buyer,
_referrer,
_promoHash
)
);
}
function_canBuyForFree(bytes32 _displayNameHash, address _who)
internalviewreturns(bool _can)
{
// TODO add logikif (displays[_displayNameHash].owner == _who) {
_can =true;
}
}
function_isDisplayAdmin(bytes32 _displayNameHash, address _who)
internalviewreturns(bool _isAdmin)
{
address[] memory admins = displayAdmins[_displayNameHash];
for (uint256 i =0; i < admins.length; ++ i) {
if (admins[i] == _who) {
_isAdmin =true;
}
}
}
}
Contract Source Code
File 29 of 37: NFTKioskLazy.sol
// SPDX-License-Identifier: MIT// ENVELOP(NIFTSY) NFT(wNFT) Kiosk.pragmasolidity 0.8.21;import"./NFTKiosk.sol";
contractNFTKioskLazyisNFTKiosk{
functionbuyAssetItem(
ETypes.AssetItem calldata _assetItem,
uint256 _priceIndex,
address _buyer,
address _referrer,
stringcalldata _promo
) externaloverridepayablenonReentrant{
// 1.Define exact asset price with discounts
ETypes.AssetItem memory payWithItem;
{ // Against stack too deep
(KTypes.Price[] memory pArray, KTypes.Discount[] memory dArray)
= _getAssetItemPricesAndDiscounts(
_assetItem, _buyer, _referrer, hlpHashString(_promo)
);
uint256 totalDiscountPercent;
for (uint256 i =0; i < dArray.length; ++ i){
totalDiscountPercent += dArray[i].dsctPercent;
if (dArray[i].dsctType == KTypes.DiscountType.REFERRAL){
emit EnvelopReferrer(
_referrer, msg.sender,
pArray[_priceIndex].payWith,
pArray[_priceIndex].amount,
uint16(dArray[i].dsctPercent)
);
}
}
payWithItem = ETypes.AssetItem(
ETypes.Asset(
pArray[_priceIndex].payWith ==address(0)
?ETypes.AssetType.NATIVE
:ETypes.AssetType.ERC20,
pArray[_priceIndex].payWith
),
0,
pArray[_priceIndex].amount
* (PERCENT_DENOMINATOR - totalDiscountPercent)
* (_assetItem.amount ==0 ? 1 : _assetItem.amount) // amount of items for buy/ PERCENT_DENOMINATOR
);
}
// 2. Manage display records for different casesaddress beneficiary;
address modelAddress;
bool hasRecord;
KTypes.Place memory p = getAssetItemPlace(_assetItem);
// Case when NFT just transfered to kiosk contractif (p.display ==bytes32(0)) {
//isImplicitAdded = true;
beneficiary = displays[DEFAULT_DISPLAY].beneficiary;
p.display = DEFAULT_DISPLAY;
p.index = DEFAULT_INDEX;
modelAddress = displays[DEFAULT_DISPLAY].priceModel;
} else {
beneficiary = displays[p.display].beneficiary;
modelAddress = displays[p.display].priceModel;
hasRecord =true;
// Next row moved below to support Lazy buy case //_removeAssetItemRecord(p.display, p.index,_assetItem);
}
require(
displays[p.display].enableAfter <block.timestamp&& displays[p.display].disableAfter >=block.timestamp,
"Only in time"
);
// 3.Receive payment or buy for freeif (!_canBuyForFree(p.display, msg.sender)) {
_receivePayment(payWithItem, beneficiary);
// 4. Make some action for _buerif (IDisplayPriceModel(modelAddress).makeActionInModel(_assetItem, _buyer)) {
// in case makeActionInModel return true we need make transfer any way// this usefull for compatibility atleast both price models: simple and lazyif (hasRecord) {
// Remove record if it is not Lazy buy case
_removeAssetItemRecord(p.display, p.index,_assetItem);
}
_transferSafe(_assetItem, address(this), _buyer);
emit EnvelopPurchase(p.display, _assetItem.asset.contractAddress, _assetItem.tokenId);
}
}
else {
// 4. Send asset to buyer in case this is free payment case.if (hasRecord) {
_removeAssetItemRecord(p.display, p.index,_assetItem);
}
_transferSafe(_assetItem, address(this), _buyer);
emit EnvelopPurchase(p.display, _assetItem.asset.contractAddress, _assetItem.tokenId);
}
}
}
Contract Source Code
File 30 of 37: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^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.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
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) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 31 of 37: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)pragmasolidity ^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].
*/abstractcontractReentrancyGuard{
// 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.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _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.
*/modifiernonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function_nonReentrantBefore() private{
// On the first call to nonReentrant, _status will be _NOT_ENTEREDrequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function_nonReentrantAfter() private{
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/function_reentrancyGuardEntered() internalviewreturns (bool) {
return _status == _ENTERED;
}
}
Contract Source Code
File 32 of 37: SafeERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
import"../extensions/IERC20Permit.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.
*/librarySafeERC20{
usingAddressforaddress;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeTransfer(IERC20 token, address to, uint256 value) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/functionsafeTransferFrom(IERC20 token, addressfrom, 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.
*/functionsafeApprove(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));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal{
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/functionforceApprove(IERC20 token, address spender, uint256 value) internal{
bytesmemory approvalCall =abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/functionsafePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal{
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore +1, "SafeERC20: permit did not succeed");
}
/**
* @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, bytesmemory 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.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length==0||abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/function_callOptionalReturnBool(IERC20 token, bytesmemory data) privatereturns (bool) {
// 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 cannot use {Address-functionCall} here since this should return false// and not revert is the subcall reverts.
(bool success, bytesmemory returndata) =address(token).call(data);
return
success && (returndata.length==0||abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
Contract Source Code
File 33 of 37: ServiceProvider.sol
// SPDX-License-Identifier: MIT// ENVELOP(NIFTSY) Subscription Registry Contract V2/// The subscription platform operates with the following role model /// (it is assumed that the actor with the role is implemented as a contract)./// `Service Provider` is a contract whose services are sold by subscription./// `Agent` - a contract that sells a subscription on behalf ofservice provider. /// May receive sales commission/// `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, /// fares, ticketspragmasolidity 0.8.21;import"../interfaces/ISubscriptionRegistry.sol";
/// @title ServiceProvider abstract contract /// @author Envelop project Team/// @notice Abstract contract implements subscribing features./// For use with SubscriptionRegestry/// @dev Use this code in service provider contract that/// want use subscription. One contract = one servie/// Please see example folderabstractcontractServiceProvider{
addresspublic serviceProvider;
ISubscriptionRegistry public subscriptionRegistry;
boolpublic isEnabled =true;
constructor(address _subscrRegistry) {
require(_subscrRegistry !=address(0), 'Non zero only');
serviceProvider =address(this);
subscriptionRegistry = ISubscriptionRegistry(_subscrRegistry);
}
function_registerServiceTariff(Tariff memory _newTariff)
internalvirtualreturns(uint256)
{
return subscriptionRegistry.registerServiceTariff(_newTariff);
}
function_editServiceTariff(uint256 _tariffIndex,
uint256 _timelockPeriod,
uint256 _ticketValidPeriod,
uint256 _counter,
bool _isAvailable,
address _beneficiary
) internalvirtual{
subscriptionRegistry.editServiceTariff(
_tariffIndex,
_timelockPeriod,
_ticketValidPeriod,
_counter,
_isAvailable,
_beneficiary
);
}
function_addTariffPayOption(uint256 _tariffIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) internalvirtualreturns(uint256)
{
return subscriptionRegistry.addTariffPayOption(
_tariffIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
function_editTariffPayOption(uint256 _tariffIndex,
uint256 _payWithIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) internalvirtual{
subscriptionRegistry.editTariffPayOption(
_tariffIndex,
_payWithIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
function_authorizeAgentForService(address _agent,
uint256[] memory _serviceTariffIndexes
) internalvirtualreturns (uint256[] memory)
{
// TODO Check agentreturn subscriptionRegistry.authorizeAgentForService(
_agent,
_serviceTariffIndexes
);
}
////////////////////////////// Main USAGE //////////////////////////////function_checkAndFixSubscription(address _user)
internalreturns (bool ok)
{
if (isEnabled) {
ok = subscriptionRegistry.checkAndFixUserSubscription(
_user
);
} else {
ok =true;
}
}
function_checkUserSubscription(address _user)
internalviewreturns (bool ok, bool needFix)
{
if (isEnabled) {
(ok, needFix) = subscriptionRegistry.checkUserSubscription(
_user,
address(this)
);
} else {
ok =true;
}
}
}
Contract Source Code
File 34 of 37: ServiceProviderOwnable.sol
// SPDX-License-Identifier: MIT// ENVELOP(NIFTSY) Subscription Registry Contract V2/// The subscription platform operates with the following role model /// (it is assumed that the actor with the role is implemented as a contract)./// `Service Provider` is a contract whose services are sold by subscription./// `Agent` - a contract that sells a subscription on behalf ofservice provider. /// May receive sales commission/// `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, /// fares, ticketspragmasolidity 0.8.21;import"@openzeppelin/contracts/access/Ownable.sol";
import"./ServiceProvider.sol";
/// @title ServiceProviderOwnable contract /// @author Envelop project Team/// @notice Contract implements Ownable pattern for service providers./// @dev Inherit this code in service provider contract that/// want use subscription. contractServiceProviderOwnableisServiceProvider, Ownable{
constructor(address _subscrRegistry)
ServiceProvider(_subscrRegistry)
{
}
///////////////////////////////////////// Admin functions ///////////////////////////////////////////functionnewTariff(Tariff memory _newTariff) externalonlyOwnerreturns(uint256 tariffIndex) {
tariffIndex = _registerServiceTariff(_newTariff);
}
functionregisterServiceTariff(Tariff memory _newTariff)
externalonlyOwnerreturns(uint256)
{
return _registerServiceTariff(_newTariff);
}
functioneditServiceTariff(uint256 _tariffIndex,
uint256 _timelockPeriod,
uint256 _ticketValidPeriod,
uint256 _counter,
bool _isAvailable,
address _beneficiary
) externalonlyOwner{
_editServiceTariff(
_tariffIndex,
_timelockPeriod,
_ticketValidPeriod,
_counter,
_isAvailable,
_beneficiary
);
}
functionaddPayOption(uint256 _tariffIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) externalonlyOwnerreturns(uint256 index)
{
index = _addTariffPayOption(
_tariffIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
functioneditPayOption(uint256 _tariffIndex,
uint256 _payWithIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) externalonlyOwner{
_editTariffPayOption(
_tariffIndex,
_payWithIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
functionauthorizeAgentForService(address _agent,
uint256[] memory _serviceTariffIndexes
) externalonlyOwnerreturns (uint256[] memory actualTariffs)
{
actualTariffs = _authorizeAgentForService(
_agent,
_serviceTariffIndexes
);
}
functionsetSubscriptionRegistry(address _subscrRegistry) externalonlyOwner{
subscriptionRegistry = ISubscriptionRegistry(_subscrRegistry);
}
functionsetSubscriptionOnOff(bool _isEnable) externalonlyOwner{
isEnabled = _isEnable;
}
}
Contract Source Code
File 35 of 37: SubscriptionRegistry.sol
// SPDX-License-Identifier: MIT// ENVELOP(NIFTSY) Team. Subscription Registry Contract V2pragmasolidity 0.8.21;import"@openzeppelin/contracts/access/Ownable.sol";
import"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import"@envelop-protocol-v1/interfaces/ITrustedWrapper.sol";
import"@envelop-protocol-v1/contracts/LibEnvelopTypes.sol";
import"../interfaces/ISubscriptionRegistry.sol";
/// The subscription platform operates with the following role model /// (it is assumed that the actor with the role is implemented as a contract)./// `Service Provider` is a contract whose services are sold by subscription./// `Agent` - a contract that sells a subscription on behalf ofservice provider. /// May receive sales commission/// `Platform` - SubscriptionRegistry contract that performs processingsubscriptions, /// fares, ticketsstructSubscriptionType {
uint256 timelockPeriod; // in seconds e.g. 3600*24*30*12 = 31104000 = 1 yearuint256 ticketValidPeriod; // in seconds e.g. 3600*24*30 = 2592000 = 1 monthuint256 counter; // For case when ticket valid for N usage, e.g. for Min N NFTs bool isAvailable; // USe for stop using tariff because we can`t remove tariff from array address beneficiary; // Who will receive payment for tickets
}
structPayOption {
address paymentToken; // token contract address or zero address for native token(ETC etc)uint256 paymentAmount; // ticket price exclude any feesuint16 agentFeePercent; // 100%-10000, 20%-2000, 3%-300
}
structTariff {
SubscriptionType subscription; // link to subscriptionType
PayOption[] payWith; // payment option array. Use it for price in defferent tokens
}
// native subscribtionManager tickets formatstructTicket {
uint256 validUntil; // Unixdate, tickets not valid afteruint256 countsLeft; // for tarif with fixed use counter
}
/// @title Base contract in Envelop Subscription Platform /// @author Envelop Team/// @notice You can use this contract for make and operate any on-chain subscriptions/// @dev Contract that performs processing subscriptions, fares(tariffs), tickets/// @custom:please see example folder.contractSubscriptionRegistryisOwnable{
usingSafeERC20forIERC20;
uint256constantpublic PERCENT_DENOMINATOR =10000;
/// @notice Envelop Multisig contractaddresspublic platformOwner;
/// @notice Platform owner can receive fee from each paymentsuint16public platformFeePercent =50; // 100%-10000, 20%-2000, 3%-300/// @notice address used for wrapp & lock incoming assetsaddresspublic mainWrapper;
/// @notice Used in case upgrade this contractaddresspublic previousRegistry;
/// @notice Used in case upgrade this contractaddresspublic proxyRegistry;
/// @notice Only white listed assets can be used on platformmapping(address=>bool) public whiteListedForPayments;
/// @notice from service(=smart contract address) to tarifsmapping(address=> Tariff[]) public availableTariffs;
/// @notice from service to agent to available tarifs(tarif index);mapping(address=>mapping(address=>uint256[])) public agentServiceRegistry;
/// @notice mapping from user addres to service contract address to ticketmapping(address=>mapping(address=> Ticket)) public userTickets;
eventPlatfromFeeChanged(uint16indexed newPercent);
eventWhitelistPaymentTokenChanged(addressindexed asset, boolindexed state);
eventTariffChanged(addressindexed service, uint256indexed tariffIndex);
eventTicketIssued(addressindexed service,
addressindexed agent,
addressindexed forUser,
uint256 tariffIndex
);
constructor(address _platformOwner) {
require(_platformOwner !=address(0),'Zero platform fee receiver');
platformOwner = _platformOwner;
}
/**
* @notice Add new tariff for caller
* @dev Call this method from ServiceProvider
* for setup new tariff
* using `Tariff` data type(please see above)
*
* @param _newTariff full encded Tariff object
* @return last added tariff index in Tariff[] array
* for current Service Provider (msg.sender)
*/functionregisterServiceTariff(Tariff calldata _newTariff)
externalreturns(uint256)
{
// TODO// Tarif structure check// PayWith array whiteList checkreturn _addTariff(msg.sender, _newTariff);
}
/**
* @notice Edit tariff for caller
* @dev Call this method from ServiceProvider
* for setup new tariff
* using `Tariff` data type(please see above)
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _timelockPeriod - see SubscriptionType notice above
* @param _ticketValidPeriod - see SubscriptionType notice above
* @param _counter - see SubscriptionType notice above
* @param _isAvailable - see SubscriptionType notice above
* @param _beneficiary - see SubscriptionType notice above
*/functioneditServiceTariff(uint256 _tariffIndex,
uint256 _timelockPeriod,
uint256 _ticketValidPeriod,
uint256 _counter,
bool _isAvailable,
address _beneficiary
)
external{
// TODO// Tariff structure check// PayWith array whiteList check
_editTariff(
msg.sender,
_tariffIndex,
_timelockPeriod,
_ticketValidPeriod,
_counter,
_isAvailable,
_beneficiary
);
}
/**
* @notice Add tariff PayOption for exact service
* @dev Call this method from ServiceProvider
* for add tariff PayOption
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _paymentToken - see PayOption notice above
* @param _paymentAmount - see PayOption notice above
* @param _agentFeePercent - see PayOption notice above
* @return last added PaymentOption index in array
* for _tariffIndex Tariff of caller Service Provider (msg.sender)
*/functionaddTariffPayOption(uint256 _tariffIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) externalreturns(uint256)
{
return _addTariffPayOption(
msg.sender,
_tariffIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
/**
* @notice Edit tariff PayOption for exact service
* @dev Call this method from ServiceProvider
* for edit tariff PayOption
*
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @param _paymentToken - see PayOption notice above
* @param _paymentAmount - see PayOption notice above
* @param _agentFeePercent - see PayOption notice above
* for _tariffIndex Tariff of caller Service Provider (msg.sender)
*/functioneditTariffPayOption(uint256 _tariffIndex,
uint256 _payWithIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) external{
_editTariffPayOption(
msg.sender,
_tariffIndex,
_payWithIndex,
_paymentToken,
_paymentAmount,
_agentFeePercent
);
}
/**
* @notice Authorize agent for caller service provider
* @dev Call this method from ServiceProvider
*
* @param _agent - address of contract that implement Agent role
* @param _serviceTariffIndexes - array of index in `availableTariffs` array
* that available for given `_agent`
* @return full array of actual tarifs for this agent
*/functionauthorizeAgentForService(address _agent,
uint256[] calldata _serviceTariffIndexes
) externalvirtualreturns (uint256[] memory)
{
// remove previouse tariffsdelete agentServiceRegistry[msg.sender][_agent];
uint256[] storage currentServiceTariffsOfAgent = agentServiceRegistry[msg.sender][_agent];
// check that adding tariffs still availablefor(uint256 i; i < _serviceTariffIndexes.length; ++ i) {
if (availableTariffs[msg.sender][_serviceTariffIndexes[i]].subscription.isAvailable){
currentServiceTariffsOfAgent.push(_serviceTariffIndexes[i]);
}
}
return currentServiceTariffsOfAgent;
}
/**
* @notice By Ticket for subscription
* @dev Call this method from Agent
*
* @param _service - Service Provider address
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @param _buyFor - address for whome this ticket would be bought
* @param _payer - address of payer for this ticket
* @return ticket structure that would be use for validate service process
*/functionbuySubscription(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex,
address _buyFor,
address _payer
) externalpayablereturns(Ticket memory ticket) {
// Cant buy ticket for nobodyrequire(_buyFor !=address(0),'Cant buy ticket for nobody');
require(
availableTariffs[_service][_tariffIndex].subscription.isAvailable,
'This subscription not available'
);
// Not used in this implementation// require(// availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount > 0,// 'This Payment option not available'// );// Check that agent is authorized for purchace of this servicerequire(
_isAgentAuthorized(msg.sender, _service, _tariffIndex),
'Agent not authorized for this service tariff'
);
(bool isValid, bool needFix) = _isTicketValid(_buyFor, _service);
require(!isValid, 'Only one valid ticket at time');
//lets safe user ticket (only one ticket available in this version)
ticket = Ticket(
availableTariffs[_service][_tariffIndex].subscription.ticketValidPeriod +block.timestamp,
availableTariffs[_service][_tariffIndex].subscription.counter
);
userTickets[_buyFor][_service] = ticket;
// Lets receive payment tokens FROM senderif (availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount >0){
_processPayment(_service, _tariffIndex, _payWithIndex, _payer);
}
emit TicketIssued(_service, msg.sender, _buyFor, _tariffIndex);
}
/**
* @notice Check that `_user` have still valid ticket for this service.
* Decrement ticket counter in case it > 0
* @dev Call this method from ServiceProvider
*
* @param _user - address of user who has an ticket and who trying get service
* @return ok True in case ticket is valid
*/functioncheckAndFixUserSubscription(address _user
) externalreturns (bool ok){
address _service =msg.sender;
// Check user ticket
(bool isValid, bool needFix) = _isTicketValid(_user, msg.sender);
// Proxy to previosif (!isValid && previousRegistry !=address(0)) {
(isValid, needFix) = ISubscriptionRegistry(previousRegistry).checkUserSubscription(
_user,
_service
);
// Case when valid ticket stored in previousManagerif (isValid ) {
if (needFix){
ISubscriptionRegistry(previousRegistry).fixUserSubscription(
_user,
_service
);
}
ok =true;
return ok;
}
}
require(isValid,'Valid ticket not found');
// Fix action (for subscription with counter)if (needFix){
_fixUserSubscription(_user, msg.sender);
}
ok =true;
}
/**
* @notice Decrement ticket counter in case it > 0
* @dev Call this method from new SubscriptionRegistry in case of upgrade
*
* @param _user - address of user who has an ticket and who trying get service
* @param _serviceFromProxy - address of service from more new SubscriptionRegistry contract
*/functionfixUserSubscription(address _user,
address _serviceFromProxy
) public{
require(proxyRegistry !=address(0) &&msg.sender== proxyRegistry,
'Only for future registry'
);
_fixUserSubscription(_user, _serviceFromProxy);
}
/////////////////////////////////////////////////////////////////**
* @notice Check that `_user` have still valid ticket for this service.
* @dev Call this method from any context
*
* @param _user - address of user who has an ticket and who trying get service
* @param _service - address of Service Provider
* @return ok True in case ticket is valid
* @return needFix True in case ticket has counter > 0
*/functioncheckUserSubscription(address _user,
address _service
) externalviewreturns (bool ok, bool needFix) {
(ok, needFix) = _isTicketValid(_user, _service);
if (!ok && previousRegistry !=address(0)) {
(ok, needFix) = ISubscriptionRegistry(previousRegistry).checkUserSubscription(
_user,
_service
);
}
}
/**
* @notice Returns `_user` ticket for this service.
* @dev Call this method from any context
*
* @param _user - address of user who has an ticket and who trying get service
* @param _service - address of Service Provider
* @return ticket
*/functiongetUserTicketForService(address _service,
address _user
) publicviewreturns(Ticket memory)
{
return userTickets[_user][_service];
}
/**
* @notice Returns array of Tariff for `_service`
* @dev Call this method from any context
*
* @param _service - address of Service Provider
* @return Tariff array
*/functiongetTariffsForService(address _service) externalviewreturns (Tariff[] memory) {
return availableTariffs[_service];
}
/**
* @notice Returns ticket price include any fees
* @dev Call this method from any context
*
* @param _service - address of Service Provider
* @param _tariffIndex - index in `availableTariffs` array
* @param _payWithIndex - index in `tariff.payWith` array
* @return tulpe with payment token an ticket price
*/functiongetTicketPrice(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex
) publicviewvirtualreturns (address, uint256)
{
if (availableTariffs[_service][_tariffIndex].subscription.timelockPeriod !=0)
{
return(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
} else {
return(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
+ availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
/PERCENT_DENOMINATOR
+ availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*_platformFeePercent(_service, _tariffIndex, _payWithIndex)
/PERCENT_DENOMINATOR
);
}
}
/**
* @notice Returns array of Tariff for `_service` assigned to `_agent`
* @dev Call this method from any context
*
* @param _agent - address of Agent
* @param _service - address of Service Provider
* @return tuple with two arrays: indexes and Tariffs
*/functiongetAvailableAgentsTariffForService(address _agent,
address _service
) externalviewvirtualreturns(uint256[] memory, Tariff[] memory)
{
//First need get count of tarifs that still availableuint256 availableCount;
for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++i){
if (availableTariffs[_service][
agentServiceRegistry[_service][_agent][i]
].subscription.isAvailable
) {++availableCount;}
}
Tariff[] memory tariffs =new Tariff[](availableCount);
uint256[] memory indexes =newuint256[](availableCount);
for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++i){
if (availableTariffs[_service][
agentServiceRegistry[_service][_agent][i]
].subscription.isAvailable
)
{
tariffs[availableCount -1] = availableTariffs[_service][
agentServiceRegistry[_service][_agent][i]
];
indexes[availableCount -1] = agentServiceRegistry[_service][_agent][i];
--availableCount;
}
}
return (indexes, tariffs);
}
////////////////////////////////////////////////////////////////////////// Admins //////////////////////////////////////////////////////////////////////functionsetAssetForPaymentState(address _asset, bool _isEnable)
externalonlyOwner{
whiteListedForPayments[_asset] = _isEnable;
emit WhitelistPaymentTokenChanged(_asset, _isEnable);
}
functionsetMainWrapper(address _wrapper) externalonlyOwner{
mainWrapper = _wrapper;
}
functionsetPlatformOwner(address _newOwner) external{
require(msg.sender== platformOwner, 'Only platform owner');
require(_newOwner !=address(0),'Zero platform fee receiver');
platformOwner = _newOwner;
}
functionsetPlatformFeePercent(uint16 _newPercent) external{
require(msg.sender== platformOwner, 'Only platform owner');
platformFeePercent = _newPercent;
emit PlatfromFeeChanged(platformFeePercent);
}
functionsetPreviousRegistry(address _registry) externalonlyOwner{
previousRegistry = _registry;
}
functionsetProxyRegistry(address _registry) externalonlyOwner{
proxyRegistry = _registry;
}
/////////////////////////////////////////////////////////////////////function_processPayment(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex,
address _payer
)
internalvirtualreturns(bool)
{
// there are two payment method for this implementation.// 1. with wrap and lock in asset (no fees)// 2. simple payment (agent & platform fee enabled)if (availableTariffs[_service][_tariffIndex].subscription.timelockPeriod !=0){
require(msg.value==0, 'Ether Not accepted in this method');
// 1. with wrap and lock in asset
IERC20(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
).safeTransferFrom(
_payer,
address(this),
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
// Lets approve received for wrap
IERC20(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
).safeApprove(
mainWrapper,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
// Lets wrap with timelock and appropriate params
ETypes.INData memory _inData;
ETypes.AssetItem[] memory _collateralERC20 =new ETypes.AssetItem[](1);
ETypes.Lock[] memory timeLock =new ETypes.Lock[](1);
// Only need set timelock for this wNFT
timeLock[0] = ETypes.Lock(
0x00, // timelock
availableTariffs[_service][_tariffIndex].subscription.timelockPeriod +block.timestamp
);
_inData = ETypes.INData(
ETypes.AssetItem(
ETypes.Asset(ETypes.AssetType.EMPTY, address(0)),
0,0
), // INAssetaddress(0), // Unwrap destinition new ETypes.Fee[](0), // Fees//new ETypes.Lock[](0), // Locks
timeLock,
new ETypes.Royalty[](0), // Royalties
ETypes.AssetType.ERC721, // Out type0, // Out Balance0x0000// Rules
);
_collateralERC20[0] = ETypes.AssetItem(
ETypes.Asset(
ETypes.AssetType.ERC20,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
),
0,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
ITrustedWrapper(mainWrapper).wrap(
_inData,
_collateralERC20,
_payer
);
} else {
// 2. simple paymentif (availableTariffs[_service][_tariffIndex]
.payWith[_payWithIndex]
.paymentToken !=address(0)
)
{
// pay with erc20 require(msg.value==0, 'Ether Not accepted in this method');
// 2.1. Body payment
IERC20(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
).safeTransferFrom(
_payer,
availableTariffs[_service][_tariffIndex].subscription.beneficiary,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
// 2.2. Agent fee payment
IERC20(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
).safeTransferFrom(
_payer,
msg.sender,
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
/PERCENT_DENOMINATOR
);
// 2.3. Platform fee uint256 _pFee = _platformFeePercent(_service, _tariffIndex, _payWithIndex);
if (_pFee >0) {
IERC20(
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentToken
).safeTransferFrom(
_payer,
platformOwner, //
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*_pFee
/PERCENT_DENOMINATOR
);
}
} else {
// pay with native token(eth, bnb, etc)
(, uint256 needPay) = getTicketPrice(_service, _tariffIndex,_payWithIndex);
require(msg.value>= needPay, 'Not enough ether');
// 2.4. Body ether payment
sendValue(
payable(availableTariffs[_service][_tariffIndex].subscription.beneficiary),
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
);
// 2.5. Agent fee payment
sendValue(
payable(msg.sender),
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].agentFeePercent
/PERCENT_DENOMINATOR
);
// 2.3. Platform fee uint256 _pFee = _platformFeePercent(_service, _tariffIndex, _payWithIndex);
if (_pFee >0) {
sendValue(
payable(platformOwner),
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex].paymentAmount
*_pFee
/PERCENT_DENOMINATOR
);
}
// return changeif ((msg.value- needPay) >0) {
addresspayable s =payable(_payer);
s.transfer(msg.value- needPay);
}
}
}
}
// In this impementation params not used. // Can be ovveriden in other casesfunction_platformFeePercent(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex
) internalviewvirtualreturns(uint256)
{
return platformFeePercent;
}
function_addTariff(address _service, Tariff calldata _newTariff)
internalreturns(uint256)
{
require (_newTariff.payWith.length>0, 'No payment method');
for (uint256 i; i < _newTariff.payWith.length; ++i){
require(
whiteListedForPayments[_newTariff.payWith[i].paymentToken],
'Not whitelisted for payments'
);
}
require(
_newTariff.subscription.ticketValidPeriod >0|| _newTariff.subscription.counter >0,
'Tariff has no valid ticket option'
);
availableTariffs[_service].push(_newTariff);
emit TariffChanged(_service, availableTariffs[_service].length-1);
return availableTariffs[_service].length-1;
}
function_editTariff(address _service,
uint256 _tariffIndex,
uint256 _timelockPeriod,
uint256 _ticketValidPeriod,
uint256 _counter,
bool _isAvailable,
address _beneficiary
) internal{
availableTariffs[_service][_tariffIndex].subscription.timelockPeriod = _timelockPeriod;
availableTariffs[_service][_tariffIndex].subscription.ticketValidPeriod = _ticketValidPeriod;
availableTariffs[_service][_tariffIndex].subscription.counter = _counter;
availableTariffs[_service][_tariffIndex].subscription.isAvailable = _isAvailable;
availableTariffs[_service][_tariffIndex].subscription.beneficiary = _beneficiary;
emit TariffChanged(_service, _tariffIndex);
}
function_addTariffPayOption(address _service,
uint256 _tariffIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) internalreturns(uint256)
{
require(whiteListedForPayments[_paymentToken], 'Not whitelisted for payments');
availableTariffs[_service][_tariffIndex].payWith.push(
PayOption(_paymentToken, _paymentAmount, _agentFeePercent)
);
emit TariffChanged(_service, _tariffIndex);
return availableTariffs[_service][_tariffIndex].payWith.length-1;
}
function_editTariffPayOption(address _service,
uint256 _tariffIndex,
uint256 _payWithIndex,
address _paymentToken,
uint256 _paymentAmount,
uint16 _agentFeePercent
) internal{
require(whiteListedForPayments[_paymentToken], 'Not whitelisted for payments');
availableTariffs[_service][_tariffIndex].payWith[_payWithIndex]
= PayOption(_paymentToken, _paymentAmount, _agentFeePercent);
emit TariffChanged(_service, _tariffIndex);
}
function_fixUserSubscription(address _user,
address _service
) internal{
// Fix action (for subscription with counter)if (userTickets[_user][_service].countsLeft >0) {
-- userTickets[_user][_service].countsLeft;
}
}
function_isTicketValid(address _user, address _service)
internalviewreturns (bool isValid, bool needFix )
{
isValid = userTickets[_user][_service].validUntil >block.timestamp|| userTickets[_user][_service].countsLeft >0;
needFix = userTickets[_user][_service].countsLeft >0;
}
function_isAgentAuthorized(address _agent,
address _service,
uint256 _tariffIndex
)
internalviewreturns(bool authorized)
{
for (uint256 i; i < agentServiceRegistry[_service][_agent].length; ++ i){
if (agentServiceRegistry[_service][_agent][i] == _tariffIndex){
authorized =true;
return authorized;
}
}
}
functionsendValue(addresspayable 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");
}
}