// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 2 of 13: ERC20Relayer.sol
/**
* @title ERC20Relayer
* @author contact@erc-hub.com
* @notice ERC741 token standard, ERC20 & ERC721 synthetic token standard.
* Because it follows the logical rules of how it inherently works, it can take advantage of existing indexers.
* email: contact@erc-hub.com
* website: https://erc-hub.com
* github: https://github.com/erc-hub/ERC741
* twitter: https://twitter.com/ERC_Hub
* telegram: https://t.me/ERC_Hub
*/// SPDX-License-Identifier: MITpragmasolidity ^0.8.21;import"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import"@openzeppelin/contracts/utils/Context.sol";
import"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import"./ISemiFungibleERC741.sol";
contractERC20RelayerisIERC20, IERC20Metadata, Context{
ISemiFungibleERC741 public erc741;
modifieronlyNFT() {
require(
_msgSender() ==address(erc741),
"onlyNFT can call this function"
);
_;
}
constructor() {
erc741 = ISemiFungibleERC741(_msgSender());
}
functionname() externalviewoverridereturns (stringmemory) {
return erc741.name();
}
functionsymbol() externalviewoverridereturns (stringmemory) {
return erc741.symbol();
}
functiondecimals() externalviewoverridereturns (uint8) {
return erc741._decimals();
}
functiontotalSupply() externalviewoverridereturns (uint256) {
return erc741._erc20Supply();
}
functionbalanceOf(address account
) externalviewoverridereturns (uint256) {
return erc741.balanceOfERC20(account);
}
functiontransfer(address to,
uint256 amount
) externaloverridereturns (bool) {
bool status = erc741.transferERC20(_msgSender(), to, amount);
emit Transfer(_msgSender(), to, amount);
return status;
}
functionallowance(address owner,
address spender
) externalviewoverridereturns (uint256) {
return erc741.allowance(owner, spender);
}
functionapprove(address spender,
uint256 amount
) externaloverridereturns (bool) {
bool status = erc741.approveERC20(_msgSender(), spender, amount);
emit Approval(_msgSender(), spender, amount);
return status;
}
functiontransferFrom(addressfrom,
address to,
uint256 amount
) externaloverridereturns (bool) {
bool status = erc741.transferFromERC20(_msgSender(), from, to, amount);
emit Transfer(from, to, amount);
return status;
}
functionemitTransfer(addressfrom,
address to,
uint256 amount
) externalonlyNFT{
emit Transfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/functionallowance(address owner, address spender) externalviewreturns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 amount) externalreturns (bool);
}
Contract Source Code
File 6 of 13: IERC20Metadata.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)pragmasolidity ^0.8.0;import"../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/interfaceIERC20MetadataisIERC20{
/**
* @dev Returns the name of the token.
*/functionname() externalviewreturns (stringmemory);
/**
* @dev Returns the symbol of the token.
*/functionsymbol() externalviewreturns (stringmemory);
/**
* @dev Returns the decimals places of the token.
*/functiondecimals() externalviewreturns (uint8);
}
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title The interface for the Uniswap V3 Factory/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol feesinterfaceIUniswapV3Factory{
/// @notice Emitted when the owner of the factory is changed/// @param oldOwner The owner before the owner was changed/// @param newOwner The owner after the owner was changedeventOwnerChanged(addressindexed oldOwner, addressindexed newOwner);
/// @notice Emitted when a pool is created/// @param token0 The first token of the pool by address sort order/// @param token1 The second token of the pool by address sort order/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks/// @param pool The address of the created pooleventPoolCreated(addressindexed token0,
addressindexed token1,
uint24indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory/// @param fee The enabled fee, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given feeeventFeeAmountEnabled(uint24indexed fee, int24indexed tickSpacing);
/// @notice Returns the current owner of the factory/// @dev Can be changed by the current owner via setOwner/// @return The address of the factory ownerfunctionowner() externalviewreturns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee/// @return The tick spacingfunctionfeeAmountTickSpacing(uint24 fee) externalviewreturns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order/// @param tokenA The contract address of either token0 or token1/// @param tokenB The contract address of the other token/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @return pool The pool addressfunctiongetPool(address tokenA,
address tokenB,
uint24 fee
) externalviewreturns (address pool);
/// @notice Creates a pool for the given two tokens and fee/// @param tokenA One of the two tokens in the desired pool/// @param tokenB The other of the two tokens in the desired pool/// @param fee The desired fee for the pool/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments/// are invalid./// @return pool The address of the newly created poolfunctioncreatePool(address tokenA,
address tokenB,
uint24 fee
) externalreturns (address pool);
/// @notice Updates the owner of the factory/// @dev Must be called by the current owner/// @param _owner The new owner of the factoryfunctionsetOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing/// @dev Fee amounts may never be removed once enabled/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amountfunctionenableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
Contract Source Code
File 9 of 13: Math.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
enumRounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 up instead
* of rounding down.
*/functionceilDiv(uint256 a, uint256 b) internalpurereturns (uint256) {
// (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; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod0 :=mul(x, y)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// 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.require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////// 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.// Does not overflow because the denominator cannot be zero at this stage in the function.uint256 twos = denominator & (~denominator +1);
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 (rounding == Rounding.Up &&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 down.
*
* 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up &&1<< result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up &&10** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* 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 + (rounding == Rounding.Up &&1<< (result <<3) < value ? 1 : 0);
}
}
}
Contract Source Code
File 10 of 13: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 11 of 13: SemiFungibleERC741.sol
/**
* @title SemiFungibleERC741
* @author contact@erc-hub.com
* @notice ERC741 token standard, ERC20 & ERC721 synthetic token standard.
* Because it follows the logical rules of how it inherently works, it can take advantage of existing indexers.
* email: contact@erc-hub.com
* github: https://github.com/erc-hub/ERC741
*///SPDX-License-Identifier: UNLICENSEDpragmasolidity ^0.8.21;import {Strings} from"@openzeppelin/contracts/utils/Strings.sol";
import {Ownable} from"@openzeppelin/contracts/access/Ownable.sol";
import {ERC721Receiver} from"./ERC721Receiver.sol";
import {ERC20Relayer} from"./ERC20Relayer.sol";
abstractcontractSemiFungibleERC741isOwnable{
eventApproval(addressindexed owner,
addressindexed spender,
uint256 amount
);
eventTransfer(addressindexedfrom,
addressindexed to,
uint256indexed id
);
eventApprovalForAll(addressindexed owner,
addressindexed operator,
bool approved
);
// ErrorserrorTokenNotFound();
errorAlreadyExists();
errorInvalidRecipient();
errorInvalidSender();
errorUnsafeRecipient();
errorInvalidId();
errorIdNotAssigned();
errorPoolIsEmpty();
errorInvalidSetWhitelistCondition();
errorUnauthorized();
errorInvalidOwner();
// Metadata/// @dev Token namestringpublic name;
/// @dev Token symbolstringpublic symbol;
/// @dev Decimals for fractional representationuint8publicimmutable _decimals =18;
/// @dev Total supply in fractionalized representationuint256publicimmutable _erc20Supply;
/// NFT Metadata/// @dev Base URI for token metadatastringpublic baseTokenURI;
/// max supply of native tokensuint256public erc721totalSupply;
/// @dev Array of available idsuint256[] public tokenIdPool;
/// @dev Current mint counter, monotonically increasing to ensure accurate ownershipuint256public maxMintedId;
/// @dev erc20 relayer contract interface
ERC20Relayer public erc20Relayer;
// Mappings/// @dev Mapping to check if id is assignedmapping(uint256=>bool) private idAssigned;
/// @dev Balance of user in fractional representationmapping(address=>uint256) public _balance;
/// @dev Allowance of user in fractional representationmapping(address=>mapping(address=>uint256)) public allowance;
/// @dev Approval in native representaionmapping(uint256=>address) public getApproved;
/// @dev Approval for all in native representationmapping(address=>mapping(address=>bool)) public isApprovedForAll;
/// @dev Owner of id in native representationmapping(uint256=>address) internal _ownerOf;
/// @dev Array of owned ids in native representationmapping(address=>uint256[]) internal _owned;
/// @dev Tracks indices for the _owned mappingmapping(uint256=>uint256) internal _ownedIndex;
/// @dev Addresses ignoreNFT from minting / burning for gas savings (pairs, routers, etc)mapping(address=>bool) public excludeNFT;
modifieronlyRelayer() {
if (_msgSender() !=address(erc20Relayer)) {
revert Unauthorized();
}
_;
}
// Constructorconstructor(stringmemory _name, stringmemory _symbol) {
name = _name;
symbol = _symbol;
erc20Relayer =new ERC20Relayer();
}
functiontotalSupply() publicviewreturns (uint256) {
return erc721totalSupply;
}
/// @notice Initialization function to set pairs / etc/// saving gas by avoiding mint / burn on unnecessary targetsfunctionsetExcludeNFT(address target, bool state) publiconlyOwner{
/// only can set whitelist when target has no balanceif (_balance[target] >0) {
revert InvalidSetWhitelistCondition();
}
excludeNFT[target] = state;
}
/// @notice Function to find owner of a given native tokenfunctionownerOf(uint256 id) publicviewreturns (address owner) {
owner = _ownerOf[id];
if (owner ==address(0)) {
revert TokenNotFound();
}
}
functionsetTokenURI(stringmemory _tokenURI) publiconlyOwner{
baseTokenURI = _tokenURI;
}
functiontokenURI(uint256 id) publicvirtualreturns (stringmemory) {
if (id >= erc721totalSupply || id <=0) {
revert InvalidId();
}
returnstring.concat(baseTokenURI, Strings.toString(id));
}
/// @notice Function for token approvals/// @dev This function assumes id / native if amount less than or equal to current max idfunctionapprove(address spender, uint256 tokenId) publicreturns (bool) {
address owner = _ownerOf[tokenId];
if (_msgSender() != owner &&!isApprovedForAll[owner][_msgSender()]) {
revert Unauthorized();
}
getApproved[tokenId] = spender;
emit Approval(owner, spender, tokenId);
returntrue;
}
/// @notice Function native approvalsfunctionsetApprovalForAll(address operator, bool approved) public{
isApprovedForAll[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/// @notice Function for mixed transfers/// @dev This function assumes id / native if amount less than or equal to current max idfunctiontransferFrom(addressfrom, address to, uint256 tokenId) public{
if (from!= _ownerOf[tokenId]) {
revert InvalidSender();
}
if (to ==address(0)) {
revert InvalidRecipient();
}
if (
_msgSender() !=from&&!isApprovedForAll[from][_msgSender()] &&
_msgSender() != getApproved[tokenId]
) {
revert Unauthorized();
}
_balance[from] -= _getUnit();
unchecked {
_balance[to] += _getUnit();
}
_ownerOf[tokenId] = to;
delete getApproved[tokenId];
// update _owned for senderuint256 updatedId = _owned[from][_owned[from].length-1];
_owned[from][_ownedIndex[tokenId]] = updatedId;
// pop
_owned[from].pop();
// update index for the moved id
_ownedIndex[updatedId] = _ownedIndex[tokenId];
// push token to to owned
_owned[to].push(tokenId);
// update index for to owned
_ownedIndex[tokenId] = _owned[to].length-1;
erc20Relayer.emitTransfer(from, to, _getUnit());
emit Transfer(from, to, tokenId);
}
/// @notice Function for native transfers with contract support and callback datafunctionsafeTransferFrom(addressfrom,
address to,
uint256 id,
bytescalldata data
) public{
transferFrom(from, to, id);
if (
to.code.length!=0&&
ERC721Receiver(to).onERC721Received(_msgSender(), from, id, data) !=
ERC721Receiver.onERC721Received.selector
) {
revert UnsafeRecipient();
}
}
/// @notice Internal function for fractional transfersfunction_transfer(addressfrom,
address to,
uint256 amount
) internalreturns (bool) {
uint256 unit = _getUnit();
uint256 balanceBeforeSender = _balance[from];
uint256 balanceBeforeReceiver = _balance[to];
_balance[from] -= amount;
unchecked {
_balance[to] += amount;
}
// Skip burn for certain addresses to save gasif (!excludeNFT[from]) {
uint256 tokens_to_burn = (balanceBeforeSender / unit) -
(_balance[from] / unit);
for (uint256 i =0; i < tokens_to_burn; i++) {
_burn(from);
}
}
// Skip minting for certain addresses to save gasif (!excludeNFT[to]) {
uint256 tokens_to_mint = (_balance[to] / unit) -
(balanceBeforeReceiver / unit);
for (uint256 i =0; i < tokens_to_mint; i++) {
_mint(to);
}
}
returntrue;
}
functionbalanceOf(address account) publicviewreturns (uint256) {
return _balance[account] / _getUnit();
}
// Internal utility logicfunction_getUnit() internalpurereturns (uint256) {
return10** _decimals;
}
function_getIdFromPool() privatereturns (uint256) {
if (tokenIdPool.length==0) {
revert PoolIsEmpty();
}
uint256 randomIndex =uint256(
keccak256(
abi.encodePacked(
block.timestamp,
_msgSender(),
tokenIdPool.length
)
)
) % tokenIdPool.length;
uint256 id = tokenIdPool[randomIndex];
tokenIdPool[randomIndex] = tokenIdPool[tokenIdPool.length-1];
tokenIdPool.pop();
idAssigned[id] =true;
return id;
}
function_returnIdToPool(uint256 id) private{
if (!idAssigned[id]) {
revert IdNotAssigned();
}
tokenIdPool.push(id);
idAssigned[id] =false;
}
function_mint(address to) internal{
if (to ==address(0)) {
revert InvalidRecipient();
}
uint256 id;
if (maxMintedId < erc721totalSupply) {
maxMintedId++;
id = maxMintedId;
idAssigned[id] =true;
} elseif (tokenIdPool.length>0) {
id = _getIdFromPool();
} else {
revert PoolIsEmpty();
}
_ownerOf[id] = to;
_owned[to].push(id);
_ownedIndex[id] = _owned[to].length-1;
emit Transfer(address(0), to, id);
}
function_burn(addressfrom) internal{
if (from==address(0)) {
revert InvalidSender();
}
uint256 id = _owned[from][_owned[from].length-1];
_returnIdToPool(id);
_owned[from].pop();
delete _ownedIndex[id];
delete _ownerOf[id];
delete getApproved[id];
emit Transfer(from, address(0), id);
}
/// @notice Function for native transfers with contract supportfunctionsafeTransferFrom(addressfrom, address to, uint256 id) public{
transferFrom(from, to, id);
if (
to.code.length!=0&&
ERC721Receiver(to).onERC721Received(_msgSender(), from, id, "") !=
ERC721Receiver.onERC721Received.selector
) {
revert UnsafeRecipient();
}
}
functiontokenOfOwnerByIndex(address owner,
uint256 index
) publicviewreturns (uint256) {
return _owned[owner][index];
}
/// @notice Function for ERC20 transfers, only callable by the ERC20RelayerfunctiontransferERC20(address sender,
address to,
uint256 amount
) externalonlyRelayerreturns (bool) {
return _transfer(sender, to, amount);
}
/// @notice Function for ERC20 balance, only callable by the ERC20RelayerfunctionbalanceOfERC20(address account) publicviewreturns (uint256) {
return _balance[account];
}
/// @notice Function for ERC20 allowance, only callable by the ERC20RelayerfunctiontransferFromERC20(address sender,
addressfrom,
address to,
uint256 amount
) externalonlyRelayerreturns (bool) {
uint256 allowed = allowance[from][sender];
if (allowed !=type(uint256).max)
allowance[from][sender] = allowed - amount;
return _transfer(from, to, amount);
}
/// @notice Function for ERC20 approval, only callable by the ERC20RelayerfunctionapproveERC20(address sender,
address spender,
uint256 amount
) externalonlyRelayerreturns (bool) {
allowance[sender][spender] = amount;
returntrue;
}
}
Contract Source Code
File 12 of 13: SignedMath.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)pragmasolidity ^0.8.0;/**
* @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 13 of 13: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)pragmasolidity ^0.8.0;import"./math/Math.sol";
import"./math/SignedMath.sol";
/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _SYMBOLS ="0123456789abcdef";
uint8privateconstant _ADDRESS_LENGTH =20;
/**
* @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), _SYMBOLS))
}
value /=10;
if (value ==0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/functiontoString(int256 value) internalpurereturns (stringmemory) {
returnstring(abi.encodePacked(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) {
bytesmemory buffer =newbytes(2* length +2);
buffer[0] ="0";
buffer[1] ="x";
for (uint256 i =2* length +1; i >1; --i) {
buffer[i] = _SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
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) {
returnkeccak256(bytes(a)) ==keccak256(bytes(b));
}
}