// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)pragmasolidity ^0.8.20;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/errorAddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/errorAddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/errorFailedInnerCall();
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
if (address(this).balance< amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/functionfunctionCallWithValue(address target, bytesmemory data, uint256 value) internalreturns (bytesmemory) {
if (address(this).balance< value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/functionfunctionStaticCall(address target, bytesmemory data) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata
) internalviewreturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty// otherwise we already know that it was a contractif (returndata.length==0&& target.code.length==0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/functionverifyCallResult(bool success, bytesmemory returndata) internalpurereturns (bytesmemory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/function_revert(bytesmemory returndata) 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 FailedInnerCall();
}
}
}
Contract Source Code
File 2 of 20: Arrays.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Arrays.sol)pragmasolidity ^0.8.20;import {StorageSlot} from"./StorageSlot.sol";
import {Math} from"./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/libraryArrays{
usingStorageSlotforbytes32;
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/functionfindUpperBound(uint256[] storage array, uint256 element) internalviewreturns (uint256) {
uint256 low =0;
uint256 high = array.length;
if (high ==0) {
return0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)// because Math.average rounds towards zero (it does integer division with truncation).if (unsafeAccess(array, mid).value> element) {
high = mid;
} else {
low = mid +1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.if (low >0&& unsafeAccess(array, low -1).value== element) {
return low -1;
} else {
return low;
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/functionunsafeAccess(address[] storage arr, uint256 pos) internalpurereturns (StorageSlot.AddressSlot storage) {
bytes32 slot;
// We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`// following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays./// @solidity memory-safe-assemblyassembly {
mstore(0, arr.slot)
slot :=add(keccak256(0, 0x20), pos)
}
return slot.getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/functionunsafeAccess(bytes32[] storage arr, uint256 pos) internalpurereturns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
// We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`// following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays./// @solidity memory-safe-assemblyassembly {
mstore(0, arr.slot)
slot :=add(keccak256(0, 0x20), pos)
}
return slot.getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/functionunsafeAccess(uint256[] storage arr, uint256 pos) internalpurereturns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
// We use assembly to calculate the storage slot of the element at index `pos` of the dynamic array `arr`// following https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays./// @solidity memory-safe-assemblyassembly {
mstore(0, arr.slot)
slot :=add(keccak256(0, 0x20), pos)
}
return slot.getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/functionunsafeMemoryAccess(uint256[] memory arr, uint256 pos) internalpurereturns (uint256 res) {
assembly {
res :=mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/functionunsafeMemoryAccess(address[] memory arr, uint256 pos) internalpurereturns (address res) {
assembly {
res :=mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
}
Contract Source Code
File 3 of 20: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)pragmasolidity ^0.8.20;/**
* @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;
}
function_contextSuffixLength() internalviewvirtualreturns (uint256) {
return0;
}
}
Contract Source Code
File 4 of 20: ERC1155.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/ERC1155.sol)pragmasolidity ^0.8.20;import {IERC1155} from"./IERC1155.sol";
import {IERC1155Receiver} from"./IERC1155Receiver.sol";
import {IERC1155MetadataURI} from"./extensions/IERC1155MetadataURI.sol";
import {Context} from"../../utils/Context.sol";
import {IERC165, ERC165} from"../../utils/introspection/ERC165.sol";
import {Arrays} from"../../utils/Arrays.sol";
import {IERC1155Errors} from"../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*/abstractcontractERC1155isContext, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors{
usingArraysforuint256[];
usingArraysforaddress[];
mapping(uint256 id =>mapping(address account =>uint256)) private _balances;
mapping(address account =>mapping(address operator =>bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.jsonstringprivate _uri;
/**
* @dev See {_setURI}.
*/constructor(stringmemory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC1155).interfaceId||
interfaceId ==type(IERC1155MetadataURI).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/functionuri(uint256/* id */) publicviewvirtualreturns (stringmemory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*/functionbalanceOf(address account, uint256 id) publicviewvirtualreturns (uint256) {
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/functionbalanceOfBatch(address[] memory accounts,
uint256[] memory ids
) publicviewvirtualreturns (uint256[] memory) {
if (accounts.length!= ids.length) {
revert ERC1155InvalidArrayLength(ids.length, accounts.length);
}
uint256[] memory batchBalances =newuint256[](accounts.length);
for (uint256 i =0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtual{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/functionisApprovedForAll(address account, address operator) publicviewvirtualreturns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom, address to, uint256 id, uint256 value, bytesmemory data) publicvirtual{
address sender = _msgSender();
if (from!= sender &&!isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeTransferFrom(from, to, id, value, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory values,
bytesmemory data
) publicvirtual{
address sender = _msgSender();
if (from!= sender &&!isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeBatchTransferFrom(from, to, ids, values, data);
}
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
* (or `to`) is the zero address.
*
* Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
* or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
* - `ids` and `values` must have the same length.
*
* NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
*/function_update(addressfrom, address to, uint256[] memory ids, uint256[] memory values) internalvirtual{
if (ids.length!= values.length) {
revert ERC1155InvalidArrayLength(ids.length, values.length);
}
address operator = _msgSender();
for (uint256 i =0; i < ids.length; ++i) {
uint256 id = ids.unsafeMemoryAccess(i);
uint256 value = values.unsafeMemoryAccess(i);
if (from!=address(0)) {
uint256 fromBalance = _balances[id][from];
if (fromBalance < value) {
revert ERC1155InsufficientBalance(from, fromBalance, value, id);
}
unchecked {
// Overflow not possible: value <= fromBalance
_balances[id][from] = fromBalance - value;
}
}
if (to !=address(0)) {
_balances[id][to] += value;
}
}
if (ids.length==1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
emit TransferSingle(operator, from, to, id, value);
} else {
emit TransferBatch(operator, from, to, ids, values);
}
}
/**
* @dev Version of {_update} that performs the token acceptance check by calling
* {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
* contains code (eg. is a smart contract at the moment of execution).
*
* IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
* update to the contract state after this function would break the check-effect-interaction pattern. Consider
* overriding {_update} instead.
*/function_updateWithAcceptanceCheck(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory values,
bytesmemory data
) internalvirtual{
_update(from, to, ids, values);
if (to !=address(0)) {
address operator = _msgSender();
if (ids.length==1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
_doSafeTransferAcceptanceCheck(operator, from, to, id, value, data);
} else {
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, values, data);
}
}
}
/**
* @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/function_safeTransferFrom(addressfrom, address to, uint256 id, uint256 value, bytesmemory data) internal{
if (to ==address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from==address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
* - `ids` and `values` must have the same length.
*/function_safeBatchTransferFrom(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory values,
bytesmemory data
) internal{
if (to ==address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from==address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the values in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/function_setURI(stringmemory newuri) internalvirtual{
_uri = newuri;
}
/**
* @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/function_mint(address to, uint256 id, uint256 value, bytesmemory data) internal{
if (to ==address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/function_mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytesmemory data) internal{
if (to ==address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev Destroys a `value` amount of tokens of type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
*/function_burn(addressfrom, uint256 id, uint256 value) internal{
if (from==address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
* - `ids` and `values` must have the same length.
*/function_burnBatch(addressfrom, uint256[] memory ids, uint256[] memory values) internal{
if (from==address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/function_setApprovalForAll(address owner, address operator, bool approved) internalvirtual{
if (operator ==address(0)) {
revert ERC1155InvalidOperator(address(0));
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Performs an acceptance check by calling {IERC1155-onERC1155Received} on the `to` address
* if it contains code at the moment of execution.
*/function_doSafeTransferAcceptanceCheck(address operator,
addressfrom,
address to,
uint256 id,
uint256 value,
bytesmemory data
) private{
if (to.code.length>0) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
// Tokens rejectedrevert ERC1155InvalidReceiver(to);
}
} catch (bytesmemory reason) {
if (reason.length==0) {
// non-ERC1155Receiver implementerrevert ERC1155InvalidReceiver(to);
} else {
/// @solidity memory-safe-assemblyassembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/**
* @dev Performs a batch acceptance check by calling {IERC1155-onERC1155BatchReceived} on the `to` address
* if it contains code at the moment of execution.
*/function_doSafeBatchTransferAcceptanceCheck(address operator,
addressfrom,
address to,
uint256[] memory ids,
uint256[] memory values,
bytesmemory data
) private{
if (to.code.length>0) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
// Tokens rejectedrevert ERC1155InvalidReceiver(to);
}
} catch (bytesmemory reason) {
if (reason.length==0) {
// non-ERC1155Receiver implementerrevert ERC1155InvalidReceiver(to);
} else {
/// @solidity memory-safe-assemblyassembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/**
* @dev Creates an array in memory with only one value for each of the elements provided.
*/function_asSingletonArrays(uint256 element1,
uint256 element2
) privatepurereturns (uint256[] memory array1, uint256[] memory array2) {
/// @solidity memory-safe-assemblyassembly {
// Load the free memory pointer
array1 :=mload(0x40)
// Set array length to 1mstore(array1, 1)
// Store the single element at the next word after the length (where content starts)mstore(add(array1, 0x20), element1)
// Repeat for next array locating it right after the first array
array2 :=add(array1, 0x40)
mstore(array2, 1)
mstore(add(array2, 0x20), element2)
// Update the free memory pointer by pointing after the second arraymstore(0x40, add(array2, 0x40))
}
}
}
Contract Source Code
File 5 of 20: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)pragmasolidity ^0.8.20;import {IERC165} from"./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);
* }
* ```
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualreturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 6 of 20: IERC1155.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.1) (token/ERC1155/IERC1155.sol)pragmasolidity ^0.8.20;import {IERC165} from"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*/interfaceIERC1155isIERC165{
/**
* @dev Emitted when `value` amount of tokens of 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 value 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 a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* 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 `value` 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 value, bytescalldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` 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 values,
bytescalldata data
) external;
}
Contract Source Code
File 7 of 20: IERC1155MetadataURI.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)pragmasolidity ^0.8.20;import {IERC1155} from"../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*/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);
}
Contract Source Code
File 8 of 20: IERC1155Receiver.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)pragmasolidity ^0.8.20;import {IERC165} from"../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/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 9 of 20: IERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)pragmasolidity ^0.8.20;/**
* @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 10 of 20: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.20;/**
* @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 value of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) externalreturns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) externalreturns (bool);
}
Contract Source Code
File 11 of 20: IERC20Permit.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)pragmasolidity ^0.8.20;/**
* @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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/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].
*
* CAUTION: See Security Considerations above.
*/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 12 of 20: Math.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)pragmasolidity ^0.8.20;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
/**
* @dev Muldiv operation overflow.
*/errorMathOverflowedMulDiv();
enumRounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/functiontryAdd(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/functiontrySub(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/functiontryMul(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the// benefit is lost if 'b' is also tested.// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522if (a ==0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/functiontryDiv(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b ==0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/functiontryMod(uint256 a, uint256 b) internalpurereturns (bool, uint256) {
unchecked {
if (b ==0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/functionmax(uint256 a, uint256 b) internalpurereturns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/functionmin(uint256 a, uint256 b) internalpurereturns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/functionaverage(uint256 a, uint256 b) internalpurereturns (uint256) {
// (a + b) / 2 can overflow.return (a & b) + (a ^ b) /2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
if (b ==0) {
// Guarantee the same behavior as in a regular Solidity division.return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.return a ==0 ? 0 : (a -1) / b +1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2^256 + prod0.uint256 prod0 = x * y; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.// The surrounding unchecked block does not change this fact.// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.uint256 twos = denominator & (0- denominator);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also// works in modular arithmetic, doubling the correct bits in each step.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internalpurereturns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) &&mulmod(x, y, denominator) >0) {
result +=1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/functionsqrt(uint256 a) internalpurereturns (uint256) {
if (a ==0) {
return0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.//// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.//// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`//// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.uint256 result =1<< (log2(a) >>1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision// into the expected uint128 result.unchecked {
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
result = (result + a / result) >>1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/functionsqrt(uint256 a, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/functionlog2(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=128;
}
if (value >>64>0) {
value >>=64;
result +=64;
}
if (value >>32>0) {
value >>=32;
result +=32;
}
if (value >>16>0) {
value >>=16;
result +=16;
}
if (value >>8>0) {
value >>=8;
result +=8;
}
if (value >>4>0) {
value >>=4;
result +=4;
}
if (value >>2>0) {
value >>=2;
result +=2;
}
if (value >>1>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog2(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result =log2(value);
return result + (unsignedRoundsUp(rounding) &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/functionlog10(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >=10**64) {
value /=10**64;
result +=64;
}
if (value >=10**32) {
value /=10**32;
result +=32;
}
if (value >=10**16) {
value /=10**16;
result +=16;
}
if (value >=10**8) {
value /=10**8;
result +=8;
}
if (value >=10**4) {
value /=10**4;
result +=4;
}
if (value >=10**2) {
value /=10**2;
result +=2;
}
if (value >=10**1) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog10(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) &&10** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/functionlog256(uint256 value) internalpurereturns (uint256) {
uint256 result =0;
unchecked {
if (value >>128>0) {
value >>=128;
result +=16;
}
if (value >>64>0) {
value >>=64;
result +=8;
}
if (value >>32>0) {
value >>=32;
result +=4;
}
if (value >>16>0) {
value >>=16;
result +=2;
}
if (value >>8>0) {
result +=1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/functionlog256(uint256 value, Rounding rounding) internalpurereturns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) &&1<< (result <<3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/functionunsignedRoundsUp(Rounding rounding) internalpurereturns (bool) {
returnuint8(rounding) %2==1;
}
}
Contract Source Code
File 13 of 20: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)pragmasolidity ^0.8.20;import {Context} from"../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.
*
* The initial owner is set to the address provided by the deployer. 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;
/**
* @dev The caller account is not authorized to perform an operation.
*/errorOwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/errorOwnableInvalidOwner(address owner);
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/constructor(address initialOwner) {
if (initialOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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{
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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{
if (newOwner ==address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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 14 of 20: Ownable2Step.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)pragmasolidity ^0.8.20;import {Ownable} from"./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/abstractcontractOwnable2StepisOwnable{
addressprivate _pendingOwner;
eventOwnershipTransferStarted(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/functionpendingOwner() publicviewvirtualreturns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualoverrideonlyOwner{
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtualoverride{
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/functionacceptOwnership() publicvirtual{
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
Contract Source Code
File 15 of 20: SafeERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)pragmasolidity ^0.8.20;import {IERC20} from"../IERC20.sol";
import {IERC20Permit} from"../extensions/IERC20Permit.sol";
import {Address} from"../../../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 An operation with an ERC20 token failed.
*/errorSafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/errorSafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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.encodeCall(token.transfer, (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.encodeCall(token.transferFrom, (from, to, 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);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/functionsafeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal{
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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);
if (returndata.length!=0&&!abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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(token).code.length>0;
}
}
Contract Source Code
File 16 of 20: SignedMath.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)pragmasolidity ^0.8.20;/**
* @dev Standard signed math utilities missing in the Solidity language.
*/librarySignedMath{
/**
* @dev Returns the largest of two signed numbers.
*/functionmax(int256 a, int256 b) internalpurereturns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/functionmin(int256 a, int256 b) internalpurereturns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/functionaverage(int256 a, int256 b) internalpurereturns (int256) {
// Formula from the book "Hacker's Delight"int256 x = (a & b) + ((a ^ b) >>1);
return x + (int256(uint256(x) >>255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/functionabs(int256 n) internalpurereturns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`returnuint256(n >=0 ? n : -n);
}
}
}
Contract Source Code
File 17 of 20: StorageSlot.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.pragmasolidity ^0.8.20;/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/libraryStorageSlot{
structAddressSlot {
address value;
}
structBooleanSlot {
bool value;
}
structBytes32Slot {
bytes32 value;
}
structUint256Slot {
uint256 value;
}
structStringSlot {
string value;
}
structBytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/functiongetAddressSlot(bytes32 slot) internalpurereturns (AddressSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/functiongetBooleanSlot(bytes32 slot) internalpurereturns (BooleanSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/functiongetBytes32Slot(bytes32 slot) internalpurereturns (Bytes32Slot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/functiongetUint256Slot(bytes32 slot) internalpurereturns (Uint256Slot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/functiongetStringSlot(bytes32 slot) internalpurereturns (StringSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/functiongetStringSlot(stringstorage store) internalpurereturns (StringSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/functiongetBytesSlot(bytes32 slot) internalpurereturns (BytesSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/functiongetBytesSlot(bytesstorage store) internalpurereturns (BytesSlot storage r) {
/// @solidity memory-safe-assemblyassembly {
r.slot:= store.slot
}
}
}
Contract Source Code
File 18 of 20: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)pragmasolidity ^0.8.20;import {Math} from"./math/Math.sol";
import {SignedMath} from"./math/SignedMath.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant HEX_DIGITS ="0123456789abcdef";
uint8privateconstant ADDRESS_LENGTH =20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/errorStringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
uint256 length = Math.log10(value) +1;
stringmemory buffer =newstring(length);
uint256 ptr;
/// @solidity memory-safe-assemblyassembly {
ptr :=add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assemblyassembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/functiontoStringSigned(int256 value) internalpurereturns (stringmemory) {
returnstring.concat(value <0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, Math.log256(value) +1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/functiontoHexString(uint256 value, uint256 length) internalpurereturns (stringmemory) {
uint256 localValue = value;
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = HEX_DIGITS[localValue &0xf];
localValue >>=4;
}
if (localValue !=0) {
revert StringsInsufficientHexLength(value, length);
}
returnstring(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/functiontoHexString(address addr) internalpurereturns (stringmemory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/functionequal(stringmemory a, stringmemory b) internalpurereturns (bool) {
returnbytes(a).length==bytes(b).length&&keccak256(bytes(a)) ==keccak256(bytes(b));
}
}
Contract Source Code
File 19 of 20: Wildcard.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity ^0.8.24;import {IERC20} from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import"@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import"@openzeppelin/contracts/utils/Strings.sol";
import"@openzeppelin/contracts/utils/Context.sol";
import"@openzeppelin/contracts/access/Ownable2Step.sol";
import"@openzeppelin/contracts/utils/math/Math.sol";
// import "@openzeppelin/contracts/utils/Address.sol";import"@openzeppelin/contracts/utils/introspection/IERC165.sol";
contractWildcardisERC1155, Ownable2Step{
usingStringsforuint256;
usingSafeERC20forIERC20;
// Constants ================================================================================stringpublic name ="Wildcard";
stringpublic symbol ="WC";
// Lowest chunk that we break intouint256publicconstant TICKET_DECIMALS =3;
uint256publicconstant SINGLE_TICKET_CHUNKS =10** TICKET_DECIMALS; // 1Kuint256publicconstant PRICE_DENOMINATOR =10000* SINGLE_TICKET_CHUNKS *1000;
uint32publicconstant ONE_PERCENT_PRECISION_MULTIPLIER =1000000; // 1%// Private vars (token related) =============================================================// keeps the count of tokens issued by the contractuint256private _tokenIdCount;
// supply of given tokenId at any given momentmapping(uint256=>uint256) private _totalSupply;
mapping(uint256=>uint256) private _mintableToSocialIdOwner;
mapping(uint256=>uint256) private _ethForSocialIdOwner;
// platformId => "Name of the platform"// eg. 1 => "Twitter"// eg. 2 => "Farcaster"mapping(uint32=>string) private _platformNameById;
// tokenId by SocialId// SocialId = (platformId, platformUserId)// platformId => { platformUserId => tokenId }// Vitalik's Farcaster = TokenId 1// 2 => { 5650 => 1 }mapping(uint32=>mapping(uint256=>uint256)) private _tokenIdBySocialId;
// token id to fee address for that tokenIdmapping(uint256=>address) private _socialIdOwners;
// Token Metadata =============================================================================// metadata urls for tokens is constructed as prefix + tokenId + suffix// the prefix of the metadata url for tokensstring metadataBaseUrlPrefix;
// the suffix of the metadata url for tokensstring metadataBaseUrlSuffix;
// Contract Metadata -----------------------------------------------------string contractMetadataUrl; // the metadata url of the contract// Vars (Fee related) ==========================================================================// For every buy and sell of a ticket there is a fee// for both the protocol and the subject// The fee is a percentage of the price of the ticket// 10^6 denominationuint32public protocolFeePercent = ONE_PERCENT_PRECISION_MULTIPLIER; // 1% protocol's feeuint32public socialIdFeePercent = ONE_PERCENT_PRECISION_MULTIPLIER; // 1% subject's fee// The destination of the protocol fee. Owner by defaultaddresspublic protocolFeeDestination =msg.sender;
// Private vars (misc) ========================================================================// admin roleaddressprivate _admin =msg.sender;
// to pause the contractboolpublic isPaused;
// Event (socialId related)/* Whenever a social owner address is updated
Args:
platformId, platformUserId: socialId who's ticket is being released
socialIdOwnerAddr: owner address to which this fid will map to
*/eventSocialUserAddress(uint32indexed platformId,
uint256indexed platformUserId,
addressindexed socialIdOwnerAddr
);
// Events (tokenId related) ==================================================================/* Whenever a ticket is released
Args:
platformId, platformUserId: socialId who's ticket is being released
tokenId: token id of the ticket being released
amountPurchased: amount of tickets purchased
amountBurned: amount of tickets burned
*/eventRelease(uint32indexed platformId,
uint256indexed platformUserId,
uint256indexed tokenId
);
// When tokens are sent from address(0) to socialIdFeeAddresseventMint(uint256indexed tokenId,
uint256 amount,
addressindexed destination
);
/* whenever tickets are bought
Args:
txnFromAddr: address who initiated
destinationAddr: where the bought tickets is being sent to
tokenId: tokenId of the tickets being bought
platformId, platformUserId: socialId who's ticket is being bought
amount: amount of the ticket bought
totalPaid: total amount paid for all the tickets being bought
protocolFeePaid: amount of the protocol's fee
socialIdFeePaid: amount of the socialId's fee
newTotalSupply: total supply of the ticket after the purchase
*/eventBuy(addressindexed txnFromAddr,
addressindexed destinationAddr,
uint256indexed tokenId,
uint256 amount,
uint256 price,
uint256 protocolFeePaid,
uint256 socialIdFeePaid,
uint256 newTotalSupply
);
/* whenever a ticket is sold.
Args:
txnFromAddr: who initiated the transaction (has to hold the ticket)
destinationAddr: where the money from the sale is sent to
tokenId: token id of the ticket being sold
platformId, platformUserId: socialId who's ticket is being bought
amount: amount of the ticket sold
totalPaidBack: total amount paid back to the subjectId
protocolFeePaid: amount of the protocol's fee
socialIdFeePaid: amount of the socialId's fee
newTotalSupply: total supply of the ticket after the sale
*/eventSell(addressindexed txnFromAddr,
addressindexed destinationAddr,
uint256indexed tokenId,
uint256 amount,
uint256 price,
uint256 protocolFeePaid,
uint256 socialIdFeePaid,
uint256 newTotalSupply
);
// Events (others) =============================================================================// protocol fee changedeventProtocolFeePercentChanged(uint32 oldValue, uint32 newValue);
// subject fee changedeventSocialIdFeePercentChanged(uint32 oldValue, uint32 newValue);
// token is paused or unpausedeventToggledPause(bool oldPauseState, bool newPauseState, address caller);
// batch metadata updatedeventBatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId);
// Errors and Modifiers ========================================================================// when the contract is pausederrorWildCard__ContractIsPaused();
// when the caller is not the adminerrorWildCard_OnlyAdmin();
// Ensures that the contract is not in a paused state.modifierwhenNotPaused() {
if (isPaused) revert WildCard__ContractIsPaused();
_;
}
// Ensueres that msg.sender is adminmodifieronlyAdmin() {
if (msg.sender!= _admin) revert WildCard_OnlyAdmin();
_;
}
// Constructor ================================================================================constructor(address _owner,
stringmemory _name,
stringmemory _symbol,
stringmemory _metadataBaseUrlPrefix,
stringmemory _metadataBaseUrlSuffix,
stringmemory _contractMetadataUrl,
address _protocolFeeDestination
) Ownable(_owner) ERC1155(contractMetadataUrl) {
name = _name;
symbol = _symbol;
metadataBaseUrlPrefix = _metadataBaseUrlPrefix;
metadataBaseUrlSuffix = _metadataBaseUrlSuffix;
contractMetadataUrl = _contractMetadataUrl;
protocolFeeDestination = _protocolFeeDestination;
}
// URI related (readOnly) ======================================================================functionuri(uint256 tokenId) publicviewoverridereturns (stringmemory) {
// returns the metadata url of the token as `metadataBaseUrlPrefix + tokenId + metadataBaseUrlSuffix`// Tokens minted above the supply cap will not have associated metadata.if (tokenId > _tokenIdCount || tokenId ==0) {
return"";
}
returnstring(
abi.encodePacked(
metadataBaseUrlPrefix,
Strings.toString(tokenId),
metadataBaseUrlSuffix
)
);
}
functioncontractURI() publicviewreturns (stringmemory) {
return contractMetadataUrl;
}
// Setters (owner only) ---------------------------------------------------functionsetAdmin(address newAddress) publiconlyOwner{
require(newAddress !=address(0), "Invalid address");
_admin = newAddress;
}
functionadmin() publicviewreturns (address) {
return _admin;
}
functionsetMetadataBaseUrlPrefix(stringmemory newValue) publiconlyOwner{
metadataBaseUrlPrefix = newValue;
emit BatchMetadataUpdate(0, _tokenIdCount);
}
functionsetMetadataBaseUrlSuffix(stringmemory newValue) publiconlyOwner{
metadataBaseUrlSuffix = newValue;
emit BatchMetadataUpdate(0, _tokenIdCount);
}
functionsetContractMetadataUrl(stringmemory newValue) publiconlyOwner{
// NOTE(0xdost): Should we update ERC1155 also?
contractMetadataUrl = newValue;
}
functionsetProtocolFeePercent(uint32 newValue) publiconlyOwner{
require(newValue <=10* ONE_PERCENT_PRECISION_MULTIPLIER, "Value must be between 0 and 10%");
emit ProtocolFeePercentChanged(protocolFeePercent, newValue);
protocolFeePercent = newValue;
}
functionsetSocialIdFeePercent(uint32 newValue) publiconlyOwner{
require(newValue <=10* ONE_PERCENT_PRECISION_MULTIPLIER, "Value must be between 0 and 10%");
emit SocialIdFeePercentChanged(socialIdFeePercent, newValue);
socialIdFeePercent = newValue;
}
functionsetProtocolFeeDestination(address newAddress
) publiconlyOwnerreturns (address) {
require(newAddress !=address(0), "Invalid address");
protocolFeeDestination = newAddress;
return protocolFeeDestination;
}
functionsetPause(bool state) publiconlyOwner{
emit ToggledPause(isPaused, state, msg.sender);
isPaused = state;
}
// Price related (Pure functions) =========================================================================functioncalculatePrice(uint256 supply, uint256 amount) publicpurereturns (uint256) {
// Prices are quantized within SINGLE_TICKET_CHUNKS// Get the price until we hit that quantization// Price of n+0.001 == price of n + 1uint256 price;
/* Ticket computation is separated into three parts
* - x are integral ticket number points
*
* supply
* | amount
* | |
* |------------------------------------------|
* ---o--------x------------x------------x-------o
* | | | | |
* ---------x-------------------------x-------x
* | | |
* part 1 part 2 part 3
*
*
* Notes and optimizations
* - if supply is at an integral ticket point,
* part 1 will consume upto the next integral ticket or amount, whichever is smaller
* - if there is exactly one ticket left after processing part 1, it is handled by part 3 (cheaper compute)
* - if amount ends at an integral point otherwise, part 3 is zero
*/// part 1uint256 currentN = Math.ceilDiv(supply +1, SINGLE_TICKET_CHUNKS);
uint256 leftAtThisPrice = SINGLE_TICKET_CHUNKS - supply % SINGLE_TICKET_CHUNKS;
uint256 takenAtThisPrice = Math.min(leftAtThisPrice, amount);
price += takenAtThisPrice * singleTicketPrice(currentN);
amount -= takenAtThisPrice;
if (amount ==0) return price;
// Part 2// Find perfect multiples of SINGLE_TICKET_CHUNKS, and add them to the price
currentN +=1;
// If there is *exactly* one ticket left, it will be handled by part 3if (amount > SINGLE_TICKET_CHUNKS) {
uint256 numPerfectMultiples = (amount / SINGLE_TICKET_CHUNKS);
if (numPerfectMultiples ==1) {
price += singleTicketPrice(currentN) * SINGLE_TICKET_CHUNKS;
} else {
price += ticketPrice(currentN, currentN + numPerfectMultiples -1) * SINGLE_TICKET_CHUNKS;
}
amount -= numPerfectMultiples * SINGLE_TICKET_CHUNKS;
currentN += numPerfectMultiples;
}
// Part 3if (amount >0) {
price += amount * singleTicketPrice(currentN);
}
return price;
}
functiongetBuyPrice(uint256 tokenId,
uint256 amount
) publicviewreturns (uint256) {
return calculatePrice(_totalSupply[tokenId], amount);
}
functiongetTicketBuyPriceBySocialId(uint32 platformId,
uint256 platformUserId,
uint256 amount
) publicviewreturns (uint256) {
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
if(tokenId ==0) {
return calculatePrice(0, amount);
}
return getBuyPrice(tokenId, amount);
}
functiongetSellPrice(uint256 tokenId,
uint256 amount
) publicviewreturns (uint256) {
// to get the sell price of amount tickets at current token supply// we calculate the buy price of amount tickets at (current token supply - amount)// if you sell 2 tickets at 20 supply// sell price for these two = buy price for 19th and 20th ticket at 20 supplyreturn calculatePrice(_totalSupply[tokenId] - amount, amount);
}
functiongetTicketSellPriceBySocialId(uint32 platformId,
uint256 platformUserId,
uint256 amount
) publicviewreturns (uint256) {
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
if(tokenId==0){
return0;
}
return getSellPrice(tokenId, amount);
}
functiongetBuyPriceAfterFee(uint256 tokenId,
uint256 amount
) publicviewreturns (uint256) {
uint256 price = getBuyPrice(tokenId, amount);
// add protocol fee and subject fee to the price when buyingreturn price + _getFee(price);
}
functiongetTicketBuyPriceAfterTaxBySocialId(uint32 platformId,
uint256 platformUserId,
uint256 amount
) publicviewreturns (uint256) {
uint256 price = getTicketBuyPriceBySocialId(platformId, platformUserId, amount);
return price + _getFee(price);
}
functiongetSellPriceAfterFee(uint256 tokenId,
uint256 amount
) publicviewreturns (uint256) {
uint256 price = getSellPrice(tokenId, amount);
// subtract protocol fee and subject fee from the price when sellingreturn price - _getFee(price);
}
functiongetTicketSellPriceAfterTaxBySocialId(uint32 platformId,
uint256 platformUserId,
uint256 amount
) publicviewreturns (uint256) {
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
if(tokenId==0){
return0;
}
return getSellPriceAfterFee(tokenId, amount);
}
// Socials: getters ======================================================functiongetSocialIdOwner(uint256 tokenId) publicviewreturns (address) {
return _socialIdOwners[tokenId];
}
functiongetSocialIdOwnerBySocialId(uint32 platformId,
uint256 platformUserId
) publicviewreturns (address) {
return _socialIdOwners[_tokenIdBySocialId[platformId][platformUserId]];
}
functiongetTokenIdBySocialId(uint32 platformId,
uint256 platformUserId
) publicviewreturns (uint256) {
return _tokenIdBySocialId[platformId][platformUserId];
}
functiongetReleaseSupply(uint256 tokenId) publicviewreturns (uint256) {
return _totalSupply[tokenId];
}
functiongetReleaseSupplyBySocialId(uint32 platformId,
uint256 platformUserId
) publicviewreturns (uint256) {
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
return _totalSupply[tokenId];
}
functiongetSocialPlatform(uint32 platformId) publicviewreturns (stringmemory) {
return _platformNameById[platformId];
}
functiongetSocialIdPurchaseDetailsMulti(uint32 platformId,
uint256 platformUserId,
uint256[] memory amounts
) publicviewreturns (uint256[] memory tokenIds,
uint256[] memory buyPrices,
uint256[] memory sellPrices,
uint256[] memory buyPricesWithFee,
uint256[] memory sellPricesWithFee,
uint256[] memory supplies
) {
tokenIds =newuint256[](amounts.length);
buyPrices =newuint256[](amounts.length);
sellPrices =newuint256[](amounts.length);
buyPricesWithFee =newuint256[](amounts.length);
sellPricesWithFee =newuint256[](amounts.length);
supplies =newuint256[](amounts.length);
for (uint256 i =0; i < amounts.length; i++) {
(
tokenIds[i],
buyPrices[i],
sellPrices[i],
buyPricesWithFee[i],
sellPricesWithFee[i],
supplies[i]
) = getSocialIdPurchaseDetails(platformId, platformUserId, amounts[i]);
}
return (
tokenIds,
buyPrices,
sellPrices,
buyPricesWithFee,
sellPricesWithFee,
supplies
);
}
functiongetSocialIdPurchaseDetailsBulk(uint32[] memory platformIds,
uint256[] memory platformUserIds,
uint256[] memory amounts
) publicviewreturns (uint256[] memory tokenIds,
uint256[] memory buyPrices,
uint256[] memory sellPrices,
uint256[] memory buyPricesWithFee,
uint256[] memory sellPricesWithFee,
uint256[] memory supplies
) {
tokenIds =newuint256[](amounts.length);
buyPrices =newuint256[](amounts.length);
sellPrices =newuint256[](amounts.length);
buyPricesWithFee =newuint256[](amounts.length);
sellPricesWithFee =newuint256[](amounts.length);
supplies =newuint256[](amounts.length);
for (uint256 i =0; i < amounts.length; i++) {
(
tokenIds[i],
buyPrices[i],
sellPrices[i],
buyPricesWithFee[i],
sellPricesWithFee[i],
supplies[i]
) = getSocialIdPurchaseDetails(platformIds[i], platformUserIds[i], amounts[i]);
}
return (
tokenIds,
buyPrices,
sellPrices,
buyPricesWithFee,
sellPricesWithFee,
supplies
);
}
functiongetSocialIdPurchaseDetails(uint32 platformId,
uint256 platformUserId,
uint256 amount
) publicviewreturns (uint256 tokenId,
uint256 buyPrice,
uint256 sellPrice,
uint256 buyPriceWithFee,
uint256 sellPriceWithFee,
uint256 supply
) {
tokenId = _tokenIdBySocialId[platformId][platformUserId];
supply = _totalSupply[tokenId];
if (tokenId ==0) {
// first ticket is free and is given to the socialId owner// hence calculating with supply as SINGLE_TICKET_CHUNKS// sell price is 0
buyPrice = calculatePrice(SINGLE_TICKET_CHUNKS, amount);
sellPrice =0;
} else {
buyPrice = getBuyPrice(tokenId, amount);
if (amount > supply){
sellPrice = getSellPrice(tokenId, supply);
}else{
sellPrice = getSellPrice(tokenId, amount);
}
}
uint256 feePercent = protocolFeePercent + socialIdFeePercent;
buyPriceWithFee = buyPrice * (ONE_PERCENT_PRECISION_MULTIPLIER *100+ feePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100);
sellPriceWithFee = sellPrice * (ONE_PERCENT_PRECISION_MULTIPLIER *100- feePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100);
return (
tokenId,
buyPrice,
sellPrice,
buyPriceWithFee,
sellPriceWithFee,
supply
);
}
// Socials: Setters ======================================================functionaddSocialPlatform(uint32 platformId,
stringcalldata platformName
) publiconlyOwner{
require(bytes(_platformNameById[platformId]).length==0, "Social platform already set");
require(bytes(platformName).length>0, "Platform name cannot be empty");
_platformNameById[platformId] = platformName;
}
// Admin can update the socialIdOwnerAddr for a socialId// Release the socialId if it isn't already released// mint the tokens to socialIdOwnerAddr if _mintableToSocialIdOwner[tokenId]// send the collected fee if _ethForSocialIdOwner[tokenId] functionupdateSocialOwnerAddressAndDisperse(uint32 platformId,
uint256 platformUserId,
address socialIdOwnerAddr
) publiconlyAdminreturns (uint256) {
uint256 tokenId = _getOrReleaseTokenId(platformId, platformUserId);
_socialIdOwners[tokenId] = socialIdOwnerAddr;
uint256 tokensToDisperse = _mintableToSocialIdOwner[tokenId];
uint256 ethToDisperse = _ethForSocialIdOwner[tokenId];
if (ethToDisperse >0){
delete _ethForSocialIdOwner[tokenId];
}
// disperse the tokenif (tokensToDisperse >0){
delete _mintableToSocialIdOwner[tokenId];
}
if (ethToDisperse >0){
(bool success, ) = socialIdOwnerAddr.call{value: ethToDisperse}("");
require(success, "Unable to send funds");
}
if (tokensToDisperse >0){
_mint(socialIdOwnerAddr, tokenId, tokensToDisperse, "");
}
emit SocialUserAddress(platformId, platformUserId, socialIdOwnerAddr);
return tokenId;
}
functionDisperseEthToSocialIdOwner(uint32 platformId,
uint256 platformUserId
) publiconlyAdmin{
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
require (tokenId !=0, "Invalid social");
address socialIdOwnerAddr = _socialIdOwners[tokenId];
require(socialIdOwnerAddr !=address(0), "Social id owner not set");
uint256 ethToDisperse = _ethForSocialIdOwner[tokenId];
if (ethToDisperse >0){
delete _ethForSocialIdOwner[tokenId];
}
if (ethToDisperse >0){
(bool success, ) = socialIdOwnerAddr.call{value: ethToDisperse}("");
require(success, "Unable to send funds");
}
}
// Trading functions ======================================================// wrapper for buy function for socialId// this function will get the token id of the socialId and call the buy functionfunctionbuySocialId(address _to,
uint32 platformId,
uint256 platformUserId,
uint256 amount
)
publicpayablewhenNotPausedreturns (uint256 price,
uint256 protocolFeePaid,
uint256 socialIdFeePaid
)
{
uint256 tokenId = _getOrReleaseTokenId(platformId, platformUserId);
return buy(_to, tokenId, amount);
}
// wrapper for sell function for socialId// this function will get the token id of the socialId and call the sell functionfunctionsellSocialId(address refundRecipient,
uint32 platformId,
uint256 platformUserId,
uint256 amount,
uint256 minExpectedPrice // minimum expected price for the sell after fees)
publicwhenNotPausedreturns (uint256 price,
uint256 protocolFee,
uint256 subjectFee
)
{
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
require(tokenId >0, "SocialId invalid or not released");
return sell(refundRecipient, tokenId, amount, minExpectedPrice);
}
functionbuy(address _to,
uint256 tokenId,
uint256 amountToBuy
)
publicpayablewhenNotPausedreturns (uint256 price,
uint256 protocolFee,
uint256 socialIdFee
)
{
uint256 supply = _totalSupply[tokenId];
require(supply >0, "Ticket not released");
require(amountToBuy >0, "Minimum amount is 1");
price = getBuyPrice(tokenId, amountToBuy);
protocolFee = ((price * protocolFeePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100));
socialIdFee = ((price * socialIdFeePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100));
uint256 ethConsumed = price + protocolFee + socialIdFee;
require(
msg.value>= ethConsumed,
string.concat("Insufficient payment, need ", Strings.toString(ethConsumed), " wei")
);
uint256 ethLeft =msg.value- ethConsumed;
// Update total supply and mint tokensuint256 newSupply = _totalSupply[tokenId] += amountToBuy;
address _socialIdOwner = _socialIdOwners[tokenId];
if (_socialIdOwner ==address(0)){
_ethForSocialIdOwner[tokenId] += socialIdFee;
}else{
(bool success2, ) = _socialIdOwner.call{value: socialIdFee}("");
if (!success2) {
_ethForSocialIdOwner[tokenId] += socialIdFee;
}
}
(bool success1, ) = protocolFeeDestination.call{value: protocolFee}("");
require(success1, "Unable to send funds (protocolFee)");
_mint(_to, tokenId, amountToBuy, "");
emit Buy(
msg.sender,
_to,
tokenId,
amountToBuy,
price,
protocolFee,
socialIdFee,
newSupply
);
if (ethLeft >0) {
(bool success, ) =payable(msg.sender).call{value: ethLeft}("");
require(success, "Failed to refund excess Ether");
}
}
functionsell(address refundRecipient,
uint256 tokenId,
uint256 amount,
uint256 minExpectedPrice // minimum expected price for the sell after fees)
publicwhenNotPausedreturns (uint256 price,
uint256 protocolFee,
uint256 socialIdFee
)
{
_canSellOrTransferPre(tokenId, amount);
price = getSellPrice(tokenId, amount);
protocolFee = ((price * protocolFeePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100));
socialIdFee = ((price * socialIdFeePercent) / (ONE_PERCENT_PRECISION_MULTIPLIER *100));
price = price - protocolFee - socialIdFee;
// final amount being sent to the seller should be// greater than or equal to the minExpectedPricerequire(price >= minExpectedPrice, "Slippage too high");
// Update total supplyuint256 supply = _totalSupply[tokenId] -= amount;
// burn tokens
_burn(msg.sender, tokenId, amount);
address _socialIdOwner = _socialIdOwners[tokenId];
if (_socialIdOwner ==address(0)){
_ethForSocialIdOwner[tokenId] += socialIdFee;
}else{
(bool success2, ) = _socialIdOwner.call{value: socialIdFee}("");
if (!success2) {
_ethForSocialIdOwner[tokenId] += socialIdFee;
}
}
(bool success1, ) = refundRecipient.call{value: price }("");
require(success1, "Unable to send funds (feeRefund)");
(bool success3, ) = protocolFeeDestination.call{value: protocolFee}("");
require(success3, "Unable to send funds (protocolFee)");
emit Sell(
msg.sender,
refundRecipient,
tokenId,
amount,
price,
protocolFee,
socialIdFee,
supply
);
_canSellOrTransferPost(msg.sender, tokenId);
}
// ERC1155 overrides ======================================================functionsafeTransferFrom(addressfrom,
address to,
uint256 id,
uint256 value,
bytesmemory data
) publicoverridewhenNotPaused{
_canSellOrTransferPre(id, value);
super.safeTransferFrom(from, to, id, value, data);
_canSellOrTransferPost(from, id);
}
functionsafeBatchTransferFrom(addressfrom,
address to,
uint256[] memory ids,
uint256[] memory values,
bytesmemory data
) publicoverridewhenNotPaused{
_canSellOrTransferPreBulk(ids, values);
super.safeBatchTransferFrom(from, to, ids, values, data);
for (uint256 i =0; i < ids.length; i++) {
_canSellOrTransferPost(from, ids[i]);
}
}
functionsetApprovalForAll(address operator, bool approved) publicoverridewhenNotPaused{
super.setApprovalForAll(operator, approved);
}
// Ownable overrides ============================================functionrenounceOwnership() publicviewoverrideonlyOwner{
revert("disabled");
}
// Utils: Pricing ===============================================functionfirstNTicketPrice(uint256 n) privatepurereturns (uint256) {
// Price of ticket t is t + t ^ 3 / 10,000// Cumulate price is (n*(n+1)) / 2 + (n*(n+1) / 2) ^ 2 / 10,000// First ticket always belongs to the user themselves// And is supposed to be free. So, we offset n by 1if (n <=1) return0;
n -=1;
uint256 sumOfN = (n * (n +1)) /2;
uint256 sumOfNSquared = sumOfN * sumOfN;
return ((10000* sumOfN + sumOfNSquared) *1ether) / PRICE_DENOMINATOR;
}
/*
Calculate the price of a ticket at a given supply
Args:
startTicketNum: the ticket number at which the price calculation starts (inclusive)
endTicketNum: the ticket number at which the price calculation ends (inclusive)
Returns:
cumulative price of one part of the ticket from startTicketNum to endTicketNum
*/functionticketPrice(uint256 startTicketNum,
uint256 endTicketNum
) privatepurereturns (uint256) {
if (endTicketNum < startTicketNum) return0;
uint256 startTicketPriceBefore = startTicketNum ==0 ? 0 : firstNTicketPrice(startTicketNum -1);
return firstNTicketPrice(endTicketNum) - startTicketPriceBefore;
}
functionsingleTicketPrice(uint256 n
) privatepurereturns (uint256) {
if (n <=1) return0;
n -=1;
// n + n ^ 3 / 10,000 scaled by 1 ether / 1e6// Equivalent to return ticketPrice(n, n);, but optimizes for gas costreturn ((n * (10000+ n * n)) *1ether) / PRICE_DENOMINATOR;
}
function_getFee(uint256 price) internalviewreturns (uint256) {
return (price * (protocolFeePercent + socialIdFeePercent)) / (ONE_PERCENT_PRECISION_MULTIPLIER *100);
}
// Utils: Trading ================================================function_getOrReleaseTokenId(uint32 platformId, uint256 platformUserId) internalreturns (uint256) {
uint256 tokenId = _tokenIdBySocialId[platformId][platformUserId];
if (tokenId ==0){
tokenId = _release(platformId, platformUserId);
}
return tokenId;
}
function_canSellOrTransferPre(uint256 tokenId, uint256 amount) internalview{
require(_totalSupply[tokenId] >0, "Ticket not released");
require(amount >0, "Minimum amount is 1");
}
function_canSellOrTransferPreBulk(uint256[] memory tokenIds, uint256[] memory amounts) internalview{
for (uint256 i =0; i < tokenIds.length; i++) {
require(_totalSupply[tokenIds[i]] >0, "Ticket not released");
}
for(uint256 i =0; i < amounts.length; i++) {
require(amounts[i] >0, "Minimum amount is 1");
}
}
function_canSellOrTransferPost(addressfrom, uint256 tokenId) internalview{
address socialIdOwner = _socialIdOwners[tokenId];
//TODO(): if we can update the socialIdOwner, this check is uselessif (from== socialIdOwner) {
uint256 balance = balanceOf(from, tokenId);
require(balance >= SINGLE_TICKET_CHUNKS, "Cannot sell or transfer last ticket");
}
}
function_release(uint32 platformId,
uint256 platformUserId
) internalreturns (uint256) {
// check if platform is validrequire(bytes(_platformNameById[platformId]).length>0, "Invalid Social Platform");
// check if platformUserId is already registered on the platformrequire(_tokenIdBySocialId[platformId][platformUserId] ==0, "socialId has already been released");
// generate new token id and assign it to the given socialIduint256 count = _tokenIdCount +=1;
_tokenIdBySocialId[platformId][platformUserId] = count;
_totalSupply[count] += SINGLE_TICKET_CHUNKS;
_mintableToSocialIdOwner[count] = SINGLE_TICKET_CHUNKS;
emit Release(
platformId,
platformUserId,
count
);
return count;
}
}
Contract Source Code
File 20 of 20: draft-IERC6093.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)pragmasolidity ^0.8.20;/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/interfaceIERC20Errors{
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/errorERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/errorERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/errorERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/interfaceIERC721Errors{
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/errorERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/errorERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/errorERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/errorERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/errorERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/interfaceIERC1155Errors{
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/errorERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/errorERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/errorERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/errorERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/errorERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/errorERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/errorERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}