// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)pragmasolidity ^0.8.1;/**
* @dev Collection of functions related to the address type
*/libraryAddress{
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0// for contracts in construction, since the code is only stored at the end// of the constructor execution.return account.code.length>0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/functionsendValue(addresspayable recipient, uint256 amount) internal{
require(address(this).balance>= amount, 'Address: insufficient balance');
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/functionfunctionCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value
) internalreturns (bytesmemory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/functionfunctionCallWithValue(address target,
bytesmemory data,
uint256 value,
stringmemory errorMessage
) internalreturns (bytesmemory) {
require(address(this).balance>= value, 'Address: insufficient balance for call');
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data
) internalviewreturns (bytesmemory) {
return functionStaticCall(target, data, 'Address: low-level static call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/functionfunctionStaticCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target, bytesmemory data) internalreturns (bytesmemory) {
return functionDelegateCall(target, data, 'Address: low-level delegate call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/functionfunctionDelegateCall(address target,
bytesmemory data,
stringmemory errorMessage
) internalreturns (bytesmemory) {
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/functionverifyCallResultFromTarget(address target,
bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalviewreturns (bytesmemory) {
if (success) {
if (returndata.length==0) {
// only check isContract if the call was successful and the return data is empty// otherwise we already know that it was a contractrequire(isContract(target), 'Address: call to non-contract');
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function_revert(bytesmemory returndata, stringmemory errorMessage) privatepure{
// Look for revert reason and bubble it up if presentif (returndata.length>0) {
// The easiest way to bubble the revert reason is using memory via assembly/// @solidity memory-safe-assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
Contract Source Code
File 2 of 19: Context.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^0.8.0;/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 3 of 19: DexfaiINFT.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.19;import"DexfaiPool.sol";
import"ERC721Enumerable.sol";
import"IDexfaiINFT.sol";
import"IERC20.sol";
import"IDexfaiFactory.sol";
import"IWETH.sol";
/**
* @title Xfai's Infinity NFT contract
* @author Xfai
* @notice DexfaiINFT is responsible for minting, boosting, and harvesting INFTs
*/contractDexfaiINFTisIDexfaiINFT, ERC721Enumerable{
/**
* @notice The WETH address.
* @dev In the case of a chain ID other than Ethereum, the wrapped ERC20 token address of the chain's native coin
*/addressprivate WETH;
/**
* @notice The ERC20 token used as the underlying token for the INFT
*/addressprivate underlyingToken;
/**
* @notice The Factory address of the DEX
*/addressprivate dexfaiFactory;
stringprivate baseURI;
uintprivate counter;
/**
* @notice The reserve of underlyingToken within the INFT contract
*/uintpublicoverride reserve;
/**
* @notice Total amount of issued shares
*/uintpublicoverride totalSharesIssued;
/**
* @notice Initial reserve set at during deployment. Does count as part of INFT reserve
*/uintpublicoverride initialReserve;
uintprivateconstant NOT_ENTERED =1;
uintprivateconstant ENTERED =2;
uintprivate status;
uintprivate expectedMints;
/**
* @notice Mapping from token address to harvested amounts. harvestedBalance shows how much of a token has been harvested so far from the contract.
*/mapping(address=>uint) publicoverride harvestedBalance;
/**
* @notice Mapping from token ID to share
*/mapping(uint=>uint) publicoverride INFTShares;
/**
* @notice Mapping from token address to token ID to token share
*/mapping(address=>mapping(uint=>uint)) publicoverride sharesHarvestedByPool;
/**
* @notice Mapping from token address to total share for a token
*/mapping(address=>uint) publicoverride totalSharesHarvestedByPool;
/**
* @notice Functions with the onlyOwner modifier can be called only by the factory owner
*/modifieronlyOwner() {
require(msg.sender== IDexfaiFactory(dexfaiFactory).getOwner(), 'DexfaiINFT: NOT_OWNER');
_;
}
/**
* @notice Functions with the lock modifier can be called only once within a transaction
*/modifierlock() {
require(status != ENTERED, 'DexfaiINFT: REENTRANT_CALL');
status = ENTERED;
_;
status = NOT_ENTERED;
}
/**
* @notice Construct Xfai's DEX Factory
* @param _dexfaiFactory The address of the DexfaiFactory contract
* @param _underlyingToken The address of the ERC20 token used as the underlying token for the INFT
* @param _initialReserve The initial reserve used during deployment
* @param _expectedMints The number of pre-mints before minting is available
*/constructor(address _dexfaiFactory,
address _WETH,
address _underlyingToken,
uint _initialReserve,
uint _expectedMints
) ERC721('Infinity-NFT', 'INFT') {
status = NOT_ENTERED;
dexfaiFactory = _dexfaiFactory;
WETH = _WETH;
underlyingToken = _underlyingToken;
initialReserve = _initialReserve;
expectedMints = _expectedMints;
totalSharesIssued =1; // permanently lock one share to prevent zero divisions
}
receive() externalpayable{
assert(msg.sender== WETH); // only accept ETH via fallback from the WETH contract
}
/**
* @notice preMint is used to mint the legacy NFTs before minting is enabled
* @dev Can only be called by the owner
* @param _legacyLNFTHolders the address array of the legacy nft holders
* @param _initialShares the share array of the legacy nft holders
*/functionpremint(address[] memory _legacyLNFTHolders,
uint[] memory _initialShares
) externaloverrideonlyOwner{
require(counter < expectedMints, 'DexfaiINFT: PREMINTS_ENDED');
require(_initialShares.length== _legacyLNFTHolders.length, 'DexfaiINFT: INVALID_VALUES');
for (uint i =0; i < _initialShares.length; i++) {
counter +=1;
_safeMint(_legacyLNFTHolders[i], counter);
INFTShares[counter] = _initialShares[i];
totalSharesIssued += _initialShares[i];
}
}
/**
* @notice Function used to set the baseURI of the NFT
* @dev setBaseURI can be called only by the contract owner
* @param _newBaseURI the new baseURI string for the NFT
*/functionsetBaseURI(stringmemory _newBaseURI) externaloverrideonlyOwner{
baseURI = _newBaseURI;
}
function_baseURI() internalviewoverridereturns (stringmemory) {
return baseURI;
}
/**
* @notice Function used to fetch contract states
* @return The reserve used during contract initialization, the reserve of the underlying token, and the total number of shares issued
*/functiongetStates() externalviewoverridereturns (uint, uint, uint) {
return (initialReserve, reserve, totalSharesIssued);
}
/**
* @notice Computes the amount of _token fees collected for a given _tokenID
* @param _tokenID The token ID of an INFT
* @param _token the address of an ERC20 token
* @return share2amount The total amount of _token that a given _tokenID can harvest
* @return inftShare The share of an INFT
* @return harvestedShares The amount of shares harvested for a given pool
*/functionshareToTokenAmount(uint _tokenID,
address _token
) externalviewoverridereturns (uint share2amount, uint inftShare, uint harvestedShares) {
inftShare = INFTShares[_tokenID];
harvestedShares = sharesHarvestedByPool[_token][_tokenID];
uint tokenBalance = IERC20(_token).balanceOf(address(this));
uint share = inftShare - harvestedShares;
uint totalShare = totalSharesIssued - totalSharesHarvestedByPool[_token];
share2amount = (tokenBalance * share) / totalShare; // zero divisions not possible
}
/**
* @notice Creates a new INFT, the share of which is determined by the amount of the underlying token sent to the DexfaiFactory
* @dev This low-level function should be called from a contract which performs important safety checks
* @param _to The address to which the newly minted INFT should be sent to
* @return tokenID The id of the newly minted INFT
* @return share The share value of the INFT
*/functionmint(address _to) externaloverridelockreturns (uint tokenID, uint share) {
require(counter >= expectedMints, 'DexfaiINFT: PREMINTS_ONGOING');
uint amount = IERC20(underlyingToken).balanceOf(dexfaiFactory) - reserve;
require(amount !=0, 'DexfaiINFT: INSUFICIENT_AMOUNT');
counter +=1;
tokenID = counter;
reserve += amount;
share = (1e18* amount) / (reserve + initialReserve);
INFTShares[tokenID] = share;
totalSharesIssued += share;
_safeMint(_to, tokenID);
emit Mint(msg.sender, _to, share, tokenID);
}
/**
* @notice Boosts the share value of an INFT, the share of which is determined by the amount of the underlying token sent to the DexfaiFactory
* @dev This low-level function should be called from a contract which performs important safety checks
* @param _tokenID The token ID of an INFT
* @return share The share value added to an INFT
*/functionboost(uint _tokenID) externaloverridelockreturns (uint share) {
require(_tokenID <= counter, 'DexfaiINFT: Inexistent_ID');
uint amount = IERC20(underlyingToken).balanceOf(dexfaiFactory) - reserve;
require(amount !=0, 'DexfaiINFT: INSUFICIENT_AMOUNT');
reserve += amount;
share = (1e18* amount) / (reserve + initialReserve);
INFTShares[_tokenID] += share;
totalSharesIssued += share;
emit Boost(msg.sender, share, _tokenID);
}
/**
* @notice Harvests the fees (in terms of a given ERC20 token) for a given INFT.
* @param _token An ERC20 token address
* @param _tokenID The token ID of an INFT
* @param _amount The amount of _token to harvest
*/function_harvest(address _token,
uint _tokenID,
uint _amount
) privatereturns (uint harvestedTokenShare) {
require(ownerOf(_tokenID) ==msg.sender, 'DexfaiINFT: NOT_INFT_OWNER');
uint tokenBalance = IERC20(_token).balanceOf(address(this));
uint share = INFTShares[_tokenID] - sharesHarvestedByPool[_token][_tokenID];
uint totalShare = totalSharesIssued - totalSharesHarvestedByPool[_token];
uint share2amount = (tokenBalance * share) / totalShare; // zero divisions not possiblerequire(_amount <= share2amount, 'DexfaiINFT: AMOUNT_EXCEEDS_SHARE');
harvestedTokenShare = (share * _amount) / share2amount;
sharesHarvestedByPool[_token][_tokenID] += harvestedTokenShare;
totalSharesHarvestedByPool[_token] += harvestedTokenShare;
harvestedBalance[_token] += _amount;
}
/**
* @notice Harvests INFT fees from the INFT contract
* @param _token The address of an ERC20 token
* @param _tokenID The ID of the INFT
* @param _amount The amount to harvest
*/functionharvestToken(address _token,
uint _tokenID,
uint _amount
) externaloverridelockreturns (uint) {
uint harvestedTokenShare = _harvest(_token, _tokenID, _amount);
_safeTransfer(_token, ownerOf(_tokenID), _amount);
emit HarvestToken(_token, _amount, harvestedTokenShare, _tokenID);
return _amount;
}
/**
* @notice Harvests INFT fees from the INFT contract
* @param _tokenID The ID of the INFT
* @param _amount The amount to harvest
*/functionharvestETH(uint _tokenID, uint _amount) externaloverridelockreturns (uint) {
uint harvestedTokenShare = _harvest(WETH, _tokenID, _amount);
IWETH(WETH).withdraw(_amount);
_safeTransferETH(ownerOf(_tokenID), _amount);
emit HarvestETH(_amount, harvestedTokenShare, _tokenID);
return _amount;
}
function_safeTransfer(address _token, address _to, uint256 _value) internal{
require(_token.code.length>0, 'DexfaiINFT: TRANSFER_FAILED');
(bool success, bytesmemory data) = _token.call(
abi.encodeWithSelector(IERC20.transfer.selector, _to, _value)
);
require(
success && (data.length==0||abi.decode(data, (bool))),
'DexfaiINFT: TRANSFER_FAILED'
);
}
function_safeTransferETH(address _to, uint _value) internal{
(bool success, ) = _to.call{value: _value}(newbytes(0));
require(success, 'DexfaiINFT: ETH_TRANSFER_FAILED');
}
}
Contract Source Code
File 4 of 19: DexfaiPool.sol
// SPDX-License-Identifier: GPL-3.0-or-laterpragmasolidity ^0.8.19;import"IDexfaiPool.sol";
import"IERC20.sol";
import"IDexfaiFactory.sol";
/**
* @title Xfai's Dexfai Pools
* @author Xfai
* @notice DexfaiPool are contracts that get generated by the DexfaiFactory. Every hosted token has one unique pool that holds the state (i.e. pool reserve, balance, weights) for the given token.
*/contractDexfaiPoolisIDexfaiPool{
/**
* @notice The ERC20 token name for the LP token
*/stringpublicoverride name;
/**
* @notice The ERC20 token symbol for the LP token
*/stringpublicoverride symbol;
/**
* @notice The ERC20 token decimals for the LP token
*/uint8publicconstantoverride decimals =18;
/**
* @notice Structure to capture time period obervations every 15 minutes, used for local oracles
*/structObservation {
uint rCumulative;
uint wCumulative;
uint timestamp;
}
/**
* @notice The amount of time within a period.
* @dev Used to capture oracle reading every 15 minutes
*/uintprivateconstant PERIOD_SIZE =900;
/**
* @notice The total size of the ring buffer
* @dev Stores every PERIOD_SIZE a new record. The buffer can store up to 1 week of data
*/uintprivateconstant RING_SIZE =672;
/**
* @notice The ring buffer counter
* @dev Used to determine the latest index within the ring buffer
*/uintpublic ringBufferNonce =0;
/**
* @notice The ring buffer array
*/
Observation[RING_SIZE] publicoverride observations;
/**
* @notice The pool reserve
*/uintprivate r;
/**
* @notice Pool weight
* @dev w is used to compute the exchange value of a token
*/uintprivate w;
/**
* @notice The last block timestamp
*/uintprivate blockTimestampLast;
/**
* @notice The cumulative reserve value
* @dev used to compute TWAPs
*/uintprivate rCumulativeLast;
/**
* @notice The cumulative w value
* @dev used to compute TWAPs
*/uintprivate wCumulativeLast;
/**
* @notice The total supply of LP tokens
*/uintpublicoverride totalSupply =0;
uintprivate seeded =1;
IDexfaiFactory private dexfaiFactory;
/**
* @notice The ERC20 token address for which the pool was created. Not the same with the LP token address
*/addresspublicoverride poolToken;
/**
* @notice the domain seperator. Used for permits
*/bytes32publicoverride DOMAIN_SEPARATOR;
/**
* @notice the permit typehash. Used for permits
* @dev keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
*/bytes32publicconstantoverride PERMIT_TYPEHASH =0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/**
* @notice mapping used to determine the nonce of an address. Used for permits
*/mapping(address=>uint) publicoverride nonces;
/**
* @notice mapping used to determine the allowance of an address for another address
*/mapping(address=>mapping(address=>uint)) publicoverride allowance;
/**
* @notice mapping used to determine the LP token balance of an address
*/mapping(address=>uint) publicoverride balanceOf;
modifierlinked() {
address core = getDexfaiCore();
require(msg.sender== core, 'DexfaiPool: NOT_CORE');
_;
}
/**
* @notice Construct the DexfaiPool
* @dev The parameters of the pool are omitted in the construct and are instead specified via the initialize function
*/constructor() {
write(0, 0, block.timestamp);
DOMAIN_SEPARATOR =keccak256(
abi.encode(
keccak256(
'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'
),
keccak256(bytes(name)),
keccak256('1'),
block.chainid,
address(this)
)
);
}
// **** Oracle Functions ****/**
* @notice Computes the latest index within the ring buffer
* @dev The returned index will point at the latest 'empty' position within the ring buffer, i.e. the index for which the time period has not yet been reached
* @return index The current index within the price oracle ring bufffer
*/functiongetCurrentIndex() publicviewoverridereturns (uint16 index) {
index =uint16(ringBufferNonce % RING_SIZE);
}
functionwrite(uint _r, uint _w, uint _blockTimestamp) privatereturns (uint16 index) {
index = getCurrentIndex();
observations[index] = Observation(_r, _w, _blockTimestamp);
ringBufferNonce +=1;
emit Write(_r, _w, _blockTimestamp);
}
/**
* @notice Fetches the N-th latest stored observation from the ring buffer
* @dev E.g. If _n = 1, getNthObservation returns the lastest observation. If _n = 2, getNthObservation returns the previous (2nd lastest) observation
* @param _n The N-th observation that one wants to fetch
* @return rCumulative The rCumulative of the N-th observation
* @return wCumulative The wCumulative of the N-th observation
* @return timestamp The timestamp of the N-th observation
*/functiongetNthObservation(uint _n
) publicviewoverridereturns (uint rCumulative, uint wCumulative, uint timestamp) {
require(ringBufferNonce >= _n, 'DexfaiPool: INEXISTENT_HISTORY');
require(_n < RING_SIZE, 'DexfaiPool: OVERRIDDEN_HISTORY');
uint16 index =uint16((ringBufferNonce - _n) % RING_SIZE);
Observation memory point = observations[index];
rCumulative = point.rCumulative;
wCumulative = point.wCumulative;
timestamp = point.timestamp;
}
/**
* @notice Fetches the latest cummulativeLast values of the pool
* @return rCumulativeLast The cummulative r of the pool
* @return wCumulativeLast The cummulative w of the pool
* @return blockTimestampLast The cummulative timestamp of the pool
*/functiongetCumulativeLast() publicviewoverridereturns (uint, uint, uint) {
return (rCumulativeLast, wCumulativeLast, blockTimestampLast);
}
// **** Pool Functions ****/**
* @notice Called once by the factory at time of deployment
* @param _token The ERC20 token address of the pool
* @param _dexfaiFactory The Dexfai Factory of the pool
*/functioninitialize(address _token, address _dexfaiFactory) externaloverride{
require(seeded ==1, 'DexfaiPool: DEX_SEEDED');
poolToken = _token;
dexfaiFactory = IDexfaiFactory(_dexfaiFactory);
name =string(abi.encodePacked(IERC20(_token).name(), '-Xfai'));
symbol =string(abi.encodePacked(IERC20(_token).symbol(), '-Xfai'));
seeded =2;
}
/**
* @notice Get the current Dexfai Core that is allowed to modify the pool state
*/functiongetDexfaiCore() publicviewoverridereturns (address) {
return dexfaiFactory.getDexfaiCore();
}
/**
* @notice Get the current reserve, weight, and last block timestamp of the pool
*/functiongetStates() externalviewoverridereturns (uint, uint, uint) {
return (r, w, blockTimestampLast);
}
/**
* @notice Updates the reserve and weight. On the first call per block updates cumulative states.
* @dev This function is linked. Only the latest Dexfai core can call it
* @param _balance The latest balance of the pool
* @param _r The latest reserve of the pool
* @param _w The latest w weight of the pool
*/functionupdate(uint _balance, uint _r, uint _w) externaloverridelinked{
uint blockTimestamp =block.timestamp;
uint timeElapsed = blockTimestamp - blockTimestampLast;
if (timeElapsed >0&& _r !=0) {
unchecked {
rCumulativeLast += _r * timeElapsed;
wCumulativeLast += _w * timeElapsed;
}
}
(, , uint timestamp) = getNthObservation(1);
timeElapsed = blockTimestamp - timestamp; // compare the last observation with current timestamp, if greater than 15 minutes, record a new eventif (timeElapsed > PERIOD_SIZE && _r !=0) {
write(rCumulativeLast, wCumulativeLast, blockTimestamp);
}
r = _balance;
w = _w;
blockTimestampLast = blockTimestamp;
emit Sync(_balance, _w);
}
/**
* @notice transfer the pool's ERC20 token (not LP token)
* @dev This function is linked. Only the latest Dexfai core can call it
* @param _token The pool's ERC20 token address
* @param _to The recipient of the tokens
* @param _value The amount of tokens
*/functionsafeTransfer(address _token, address _to, uint256 _value) externaloverridelinked{
require(_token.code.length>0, 'DexfaiPool: TRANSFER_FAILED');
(bool success, bytesmemory data) = _token.call(
abi.encodeWithSelector(IERC20.transfer.selector, _to, _value)
);
require(
success && (data.length==0||abi.decode(data, (bool))),
'DexfaiPool: TRANSFER_FAILED'
);
}
// **** ERC20 Functions ****/**
* @notice This function mints new ERC20 LP tokens
* @dev This function is linked. Only the latest Dexfai core can call it
* @param _to The recipient of the tokens
* @param _amount The amount of tokens
*/functionmint(address _to, uint _amount) publicoverridelinked{
_mint(_to, _amount);
}
/**
* @notice This function burns existing ERC20 LP tokens
* @dev This function is linked. Only the latest Dexfai core can call it
* @param _to The recipient whose tokens get burned
* @param _amount The amount of tokens burned
*/functionburn(address _to, uint _amount) publicoverridelinked{
_burn(_to, _amount);
}
function_mint(address _dst, uint _amount) internal{
totalSupply += _amount;
balanceOf[_dst] += _amount;
emit Transfer(address(0), _dst, _amount);
}
function_burn(address _dst, uint _amount) internal{
totalSupply -= _amount;
balanceOf[_dst] -= _amount;
emit Transfer(_dst, address(0), _amount);
}
/**
* @notice The ERC20 standard approve function
*/functionapprove(address _spender, uint _amount) externaloverridereturns (bool) {
allowance[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
returntrue;
}
/**
* @notice The ERC20 standard permit function
*/functionpermit(address _owner,
address _spender,
uint _value,
uint _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) externaloverride{
require(_deadline >=block.timestamp, 'DexfaiPool: EXPIRED');
bytes32 digest =keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(
abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _deadline)
)
)
);
address recoveredAddress =ecrecover(digest, _v, _r, _s);
require(recoveredAddress !=address(0), 'DexfaiPool: INVALID_SIGNATURE');
require(recoveredAddress == _owner, 'DexfaiPool: INVALID_SIGNATURE');
allowance[_owner][_spender] = _value;
emit Approval(_owner, _spender, _value);
}
/**
* @notice The ERC20 standard transfer function
*/functiontransfer(address _dst, uint _amount) externaloverridereturns (bool) {
_transferTokens(msg.sender, _dst, _amount);
returntrue;
}
/**
* @notice The ERC20 standard transferFrom function
*/functiontransferFrom(address _src, address _dst, uint _amount) externaloverridereturns (bool) {
address spender =msg.sender;
uint spenderAllowance = allowance[_src][spender];
if (spender != _src && spenderAllowance !=type(uint).max) {
uint newAllowance = spenderAllowance - _amount;
allowance[_src][spender] = newAllowance;
emit Approval(_src, spender, newAllowance);
}
_transferTokens(_src, _dst, _amount);
returntrue;
}
function_transferTokens(address _src, address _dst, uint _amount) internal{
balanceOf[_src] -= _amount;
balanceOf[_dst] += _amount;
emit Transfer(_src, _dst, _amount);
}
}
Contract Source Code
File 5 of 19: ERC165.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)pragmasolidity ^0.8.0;import"IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/abstractcontractERC165isIERC165{
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId) publicviewvirtualoverridereturns (bool) {
return interfaceId ==type(IERC165).interfaceId;
}
}
Contract Source Code
File 6 of 19: ERC721.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)pragmasolidity ^0.8.0;import"IERC721.sol";
import"IERC721Receiver.sol";
import"IERC721Metadata.sol";
import"Address.sol";
import"Context.sol";
import"Strings.sol";
import"ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/contractERC721isContext, ERC165, IERC721, IERC721Metadata{
usingAddressforaddress;
usingStringsforuint256;
// Token namestringprivate _name;
// Token symbolstringprivate _symbol;
// Mapping from token ID to owner addressmapping(uint256=>address) private _owners;
// Mapping owner address to token countmapping(address=>uint256) private _balances;
// Mapping from token ID to approved addressmapping(uint256=>address) private _tokenApprovals;
// Mapping from owner to operator approvalsmapping(address=>mapping(address=>bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/constructor(stringmemory name_, stringmemory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId
) publicviewvirtualoverride(ERC165, IERC165) returns (bool) {
return
interfaceId ==type(IERC721).interfaceId||
interfaceId ==type(IERC721Metadata).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/functionbalanceOf(address owner) publicviewvirtualoverridereturns (uint256) {
require(owner !=address(0), 'ERC721: address zero is not a valid owner');
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
address owner = _ownerOf(tokenId);
require(owner !=address(0), 'ERC721: invalid token ID');
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/functionname() publicviewvirtualoverridereturns (stringmemory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/functionsymbol() publicviewvirtualoverridereturns (stringmemory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/functiontokenURI(uint256 tokenId) publicviewvirtualoverridereturns (stringmemory) {
_requireMinted(tokenId);
stringmemory baseURI = _baseURI();
returnbytes(baseURI).length>0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/function_baseURI() internalviewvirtualreturns (stringmemory) {
return'';
}
/**
* @dev See {IERC721-approve}.
*/functionapprove(address to, uint256 tokenId) publicvirtualoverride{
address owner = ERC721.ownerOf(tokenId);
require(to != owner, 'ERC721: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721: approve caller is not token owner or approved for all'
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/functionisApprovedForAll(address owner,
address operator
) publicviewvirtualoverridereturns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/functiontransferFrom(addressfrom, address to, uint256 tokenId) publicvirtualoverride{
//solhint-disable-next-line max-line-lengthrequire(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: caller is not token owner or approved'
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId) publicvirtualoverride{
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytesmemory data
) publicvirtualoverride{
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: caller is not token owner or approved'
);
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeTransfer(addressfrom,
address to,
uint256 tokenId,
bytesmemory data
) internalvirtual{
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/function_ownerOf(uint256 tokenId) internalviewvirtualreturns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/function_exists(uint256 tokenId) internalviewvirtualreturns (bool) {
return _ownerOf(tokenId) !=address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/function_isApprovedOrOwner(address spender,
uint256 tokenId
) internalviewvirtualreturns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
isApprovedForAll(owner, spender) ||
getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeMint(address to, uint256 tokenId) internalvirtual{
_safeMint(to, tokenId, '');
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/function_safeMint(address to, uint256 tokenId, bytesmemory data) internalvirtual{
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/function_mint(address to, uint256 tokenId) internalvirtual{
require(to !=address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hookrequire(!_exists(tokenId), 'ERC721: token already minted');
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.// Given that tokens are minted one by one, it is impossible in practice that// this ever happens. Might change if we allow batch minting.// The ERC fails to describe this case.
_balances[to] +=1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvalsdelete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred// out than the owner initially received through minting and transferring in.
_balances[owner] -=1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom, address to, uint256 tokenId) internalvirtual{
require(ERC721.ownerOf(tokenId) ==from, 'ERC721: transfer from incorrect owner');
require(to !=address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hookrequire(ERC721.ownerOf(tokenId) ==from, 'ERC721: transfer from incorrect owner');
// Clear approvals from the previous ownerdelete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:// `from`'s balance is the number of token held, which is at least one before the current// transfer.// `_balances[to]` could overflow in the conditions described in `_mint`. That would require// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -=1;
_balances[to] +=1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/function_setApprovalForAll(address owner, address operator, bool approved) internalvirtual{
require(owner != operator, 'ERC721: approve to caller');
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/function_requireMinted(uint256 tokenId) internalviewvirtual{
require(_exists(tokenId), 'ERC721: invalid token ID');
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/function_checkOnERC721Received(addressfrom,
address to,
uint256 tokenId,
bytesmemory data
) privatereturns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (
bytes4 retval
) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytesmemory reason) {
if (reason.length==0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
/// @solidity memory-safe-assemblyassembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256/* firstTokenId */,
uint256 batchSize
) internalvirtual{
if (batchSize >1) {
if (from!=address(0)) {
_balances[from] -= batchSize;
}
if (to !=address(0)) {
_balances[to] += batchSize;
}
}
}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_afterTokenTransfer(addressfrom,
address to,
uint256 firstTokenId,
uint256 batchSize
) internalvirtual{}
}
Contract Source Code
File 7 of 19: ERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)pragmasolidity ^0.8.0;import"ERC721.sol";
import"IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/abstractcontractERC721EnumerableisERC721, IERC721Enumerable{
// Mapping from owner to list of owned token IDsmapping(address=>mapping(uint256=>uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens listmapping(uint256=>uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumerationuint256[] private _allTokens;
// Mapping from token id to position in the allTokens arraymapping(uint256=>uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId
) publicviewvirtualoverride(IERC165, ERC721) returns (bool) {
return
interfaceId ==type(IERC721Enumerable).interfaceId||super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/functiontokenOfOwnerByIndex(address owner,
uint256 index
) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721.balanceOf(owner), 'ERC721Enumerable: owner index out of bounds');
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/functiontotalSupply() publicviewvirtualoverridereturns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/functiontokenByIndex(uint256 index) publicviewvirtualoverridereturns (uint256) {
require(index < ERC721Enumerable.totalSupply(), 'ERC721Enumerable: global index out of bounds');
return _allTokens[index];
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 firstTokenId,
uint256 batchSize
) internalvirtualoverride{
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
if (batchSize >1) {
// Will only trigger during construction. Batch transferring (minting) is not available afterwards.revert('ERC721Enumerable: consecutive transfers not supported');
}
uint256 tokenId = firstTokenId;
if (from==address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} elseif (from!= to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to ==address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} elseif (to !=from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/function_addTokenToOwnerEnumeration(address to, uint256 tokenId) private{
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/function_addTokenToAllTokensEnumeration(uint256 tokenId) private{
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/function_removeTokenFromOwnerEnumeration(addressfrom, uint256 tokenId) private{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and// then delete the last slot (swap and pop).uint256 lastTokenIndex = ERC721.balanceOf(from) -1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessaryif (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the arraydelete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/function_removeTokenFromAllTokensEnumeration(uint256 tokenId) private{
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and// then delete the last slot (swap and pop).uint256 lastTokenIndex = _allTokens.length-1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding// an 'if' statement (like in _removeTokenFromOwnerEnumeration)uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index// This also deletes the contents at the last position of the arraydelete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)pragmasolidity ^0.8.19;/**
* @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);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)pragmasolidity ^0.8.19;import"IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/functiontransferFrom(addressfrom, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/functionapprove(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
}
Contract Source Code
File 14 of 19: IERC721Enumerable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)pragmasolidity ^0.8.19;import"IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/interfaceIERC721EnumerableisIERC721{
/**
* @dev Returns the total amount of tokens stored by the contract.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/functiontokenOfOwnerByIndex(address owner, uint256 index) externalviewreturns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.19;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)pragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryOZMath{
enumRounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 10, 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 19 of 19: Strings.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)pragmasolidity ^0.8.0;import"OZMath.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 = OZMath.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 `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
unchecked {
return toHexString(value, OZMath.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);
}
}