// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @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
* ====
*/functionisContract(address account) internalviewreturns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in// construction, since the code is only stored at the end of the// constructor execution.uint256 size;
assembly {
size :=extcodesize(account)
}
return size >0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/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 functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytesmemory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytesmemory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytesmemory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/functionverifyCallResult(bool success,
bytesmemory returndata,
stringmemory errorMessage
) internalpurereturns (bytesmemory) {
if (success) {
return returndata;
} else {
// 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 assemblyassembly {
let returndata_size :=mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
Contract Source Code
File 2 of 44: AntiSnipAttack.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity 0.8.9;import {Math} from'@openzeppelin/contracts/utils/math/Math.sol';
import {MathConstantsasC} from'../../libraries/MathConstants.sol';
import {SafeCast} from'../../libraries/SafeCast.sol';
/// @title AntiSnipAttack/// @notice Contains the snipping attack mechanism implementation/// to be inherited by NFT position managerlibraryAntiSnipAttack{
usingSafeCastforuint256;
usingSafeCastforint256;
usingSafeCastforint128;
structData {
// timestamp of last action performeduint32 lastActionTime;
// average start time of lock scheduleuint32 lockTime;
// average unlock time of locked feesuint32 unlockTime;
// locked rToken qty since last updateuint256 feesLocked;
}
/// @notice Initializes values for a new position/// @return data Initialized snip attack data structurefunctioninitialize(uint32 currentTime) internalpurereturns (Data memory data) {
data.lastActionTime = currentTime;
data.lockTime = currentTime;
data.unlockTime = currentTime;
data.feesLocked =0;
}
/// @notice Credits accumulated fees to a user's existing position/// @dev The posiition should already have been initialized/// @param self The individual position to update/// @param liquidityDelta The change in pool liquidity as a result of the position update/// this value should not be zero when called/// @param isAddLiquidity true = add liquidity, false = remove liquidity/// @param feesSinceLastAction rTokens collected by position since last action performed/// in fee growth inside the tick range/// @param vestingPeriod The maximum time duration for which LP fees/// are proportionally burnt upon LP removals/// @return feesClaimable The claimable rToken amount to be sent to the user/// @return feesBurnable The rToken amount to be burntfunctionupdate(
Data storageself,
uint128 currentLiquidity,
uint128 liquidityDelta,
uint32 currentTime,
bool isAddLiquidity,
uint256 feesSinceLastAction,
uint256 vestingPeriod
) internalreturns (uint256 feesClaimable, uint256 feesBurnable) {
Data memory _self =self;
if (vestingPeriod ==0) {
// no locked fees, returnif (_self.feesLocked ==0) return (feesSinceLastAction, 0);
// unlock any locked feesself.feesLocked =0;
return (_self.feesLocked + feesSinceLastAction, 0);
}
// scoping of fee proportions to avoid stack too deep
{
// claimable proportion (in basis pts) of collected fees between last action and now// lockTime is used instead of lastActionTime because we prefer to use the entire// duration of the position as the measure, not just the duration after last action performeduint256 feesClaimableSinceLastActionFeeUnits = Math.min(
C.FEE_UNITS,
(uint256(currentTime - _self.lockTime) * C.FEE_UNITS) / vestingPeriod
);
// claimable proportion (in basis pts) of locked fees// lastActionTime is used instead of lockTime since the vested fees// from lockTime to lastActionTime have already been claimeduint256 feesClaimableVestedFeeUnits = _self.unlockTime <= _self.lastActionTime
? C.FEE_UNITS
: Math.min(
C.FEE_UNITS,
(uint256(currentTime - _self.lastActionTime) * C.FEE_UNITS) /
(_self.unlockTime - _self.lastActionTime)
);
uint256 feesLockedBeforeUpdate = _self.feesLocked;
(_self.feesLocked, feesClaimable) = calcFeeProportions(
_self.feesLocked,
feesSinceLastAction,
feesClaimableVestedFeeUnits,
feesClaimableSinceLastActionFeeUnits
);
// update unlock time// the new lock fee qty contains 2 portions:// (1) new lock fee qty from last action to now// (2) remaining lock fee qty prior to last action performed// new unlock time = proportionally weighted unlock times of the 2 portions// (1)'s unlock time = currentTime + vestingPeriod// (2)'s unlock time = current unlock time// If (1) and (2) are 0, then update to block.timestampself.unlockTime = (_self.feesLocked ==0)
? currentTime
: (((_self.lockTime + vestingPeriod) *
feesSinceLastAction *
(C.FEE_UNITS - feesClaimableSinceLastActionFeeUnits) +
_self.unlockTime *
feesLockedBeforeUpdate *
(C.FEE_UNITS - feesClaimableVestedFeeUnits)) / (_self.feesLocked * C.FEE_UNITS))
.toUint32();
}
uint256 updatedLiquidity = isAddLiquidity
? currentLiquidity + liquidityDelta
: currentLiquidity - liquidityDelta;
// adding liquidity: update average start time// removing liquidity: calculate and burn portion of locked feesif (isAddLiquidity) {
self.lockTime = Math
.ceilDiv(
Math.max(_self.lockTime, currentTime - vestingPeriod) *uint256(currentLiquidity) +uint256(uint128(liquidityDelta)) *
currentTime,
updatedLiquidity
).toUint32();
} elseif (_self.feesLocked >0) {
feesBurnable = (_self.feesLocked * liquidityDelta) /uint256(currentLiquidity);
_self.feesLocked -= feesBurnable;
}
// update other variablesself.feesLocked = _self.feesLocked;
self.lastActionTime = currentTime;
}
functioncalcFeeProportions(uint256 currentFees,
uint256 nextFees,
uint256 currentClaimableFeeUnits,
uint256 nextClaimableFeeUnits
) internalpurereturns (uint256 feesLockedNew, uint256 feesClaimable) {
uint256 totalFees = currentFees + nextFees;
feesClaimable =
(currentClaimableFeeUnits * currentFees + nextClaimableFeeUnits * nextFees) /
C.FEE_UNITS;
feesLockedNew = totalFees - feesClaimable;
}
}
// SPDX-License-Identifier: MITpragmasolidity ^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 6 of 44: DeadlineValidation.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;/// @title Validate if the transaction is still validabstractcontractDeadlineValidation{
modifieronlyNotExpired(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Expired');
_;
}
/// @dev Override this function to test easier with block timestampfunction_blockTimestamp() internalviewvirtualreturns (uint256) {
returnblock.timestamp;
}
}
Contract Source Code
File 7 of 44: ERC165.sol
// SPDX-License-Identifier: MITpragmasolidity ^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 8 of 44: ERC721.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"./IERC721.sol";
import"./IERC721Receiver.sol";
import"./extensions/IERC721Metadata.sol";
import"../../utils/Address.sol";
import"../../utils/Context.sol";
import"../../utils/Strings.sol";
import"../../utils/introspection/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: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/functionownerOf(uint256 tokenId) publicviewvirtualoverridereturns (address) {
address owner = _owners[tokenId];
require(owner !=address(0), "ERC721: owner query for nonexistent token");
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) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
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 overriden 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 owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/functiongetApproved(uint256 tokenId) publicviewvirtualoverridereturns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/functionsetApprovalForAll(address operator, bool approved) publicvirtualoverride{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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: transfer caller is not owner nor 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: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/function_safeTransfer(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 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 _owners[tokenId] !=address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/function_isApprovedOrOwner(address spender, uint256 tokenId) internalviewvirtualreturns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, 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);
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/function_burn(uint256 tokenId) internalvirtual{
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -=1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/function_transfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{
require(ERC721.ownerOf(tokenId) ==from, "ERC721: transfer of token that is not own");
require(to !=address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -=1;
_balances[to] +=1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/function_approve(address to, uint256 tokenId) internalvirtual{
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/function_checkOnERC721Received(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 {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
returntrue;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtual{}
}
Contract Source Code
File 9 of 44: ERC721Enumerable.sol
// SPDX-License-Identifier: MITpragmasolidity ^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 Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/function_beforeTokenTransfer(addressfrom,
address to,
uint256 tokenId
) internalvirtualoverride{
super._beforeTokenTransfer(from, to, tokenId);
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();
}
}
Contract Source Code
File 10 of 44: ERC721Permit.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;import {ERC721} from'@openzeppelin/contracts/token/ERC721/ERC721.sol';
import {ERC721Enumerable} from'@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import {Address} from'@openzeppelin/contracts/utils/Address.sol';
import {IERC721Permit} from'../../interfaces/periphery/IERC721Permit.sol';
import {DeadlineValidation} from'./DeadlineValidation.sol';
/// @title Interface for verifying contract-based account signatures/// @notice Interface that verifies provided signature for the data/// @dev Interface defined by EIP-1271interfaceIERC1271{
/// @notice Returns whether the provided signature is valid for the provided data/// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes./// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)./// MUST allow external calls./// @param hash Hash of the data to be signed/// @param signature Signature byte array associated with _data/// @return magicValue The bytes4 magic value 0x1626ba7efunctionisValidSignature(bytes32 hash, bytesmemory signature)
externalviewreturns (bytes4 magicValue);
}
/// @title ERC721 with permit/// @notice Nonfungible tokens that support an approve via signature, i.e. permitabstractcontractERC721PermitisDeadlineValidation, ERC721Enumerable, IERC721Permit{
/// @dev Value is equal to keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");bytes32publicconstantoverride PERMIT_TYPEHASH =0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
/// @dev The hash of the name used in the permit signature verificationbytes32privateimmutable nameHash;
/// @dev The hash of the version string used in the permit signature verificationbytes32privateimmutable versionHash;
/// @return The domain seperator used in encoding of permit signaturebytes32publicimmutableoverride DOMAIN_SEPARATOR;
/// @notice Computes the nameHash and versionHashconstructor(stringmemory name_,
stringmemory symbol_,
stringmemory version_
) ERC721(name_, symbol_) {
bytes32 _nameHash =keccak256(bytes(name_));
bytes32 _versionHash =keccak256(bytes(version_));
nameHash = _nameHash;
versionHash = _versionHash;
DOMAIN_SEPARATOR =keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
_nameHash,
_versionHash,
_getChainId(),
address(this)
)
);
}
functionpermit(address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) externaloverrideonlyNotExpired(deadline) {
bytes32 digest =keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(
abi.encode(PERMIT_TYPEHASH, spender, tokenId, _getAndIncrementNonce(tokenId), deadline)
)
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(
IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) ==0x1626ba7e,
'Unauthorized'
);
} else {
address recoveredAddress =ecrecover(digest, v, r, s);
require(recoveredAddress !=address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}
/// @dev Gets the current nonce for a token ID and then increments it, returning the original valuefunction_getAndIncrementNonce(uint256 tokenId) internalvirtualreturns (uint256);
/// @dev Gets the current chain ID/// @return chainId The current chain IDfunction_getChainId() internalviewreturns (uint256 chainId) {
assembly {
chainId :=chainid()
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/functionsupportsInterface(bytes4 interfaceId)
publicviewvirtualoverride(ERC721Enumerable, IERC721Permit)
returns (bool)
{
return
interfaceId ==type(ERC721Enumerable).interfaceId||
interfaceId ==type(IERC721Permit).interfaceId||super.supportsInterface(interfaceId);
}
}
Contract Source Code
File 11 of 44: FullMath.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.8.0;/// @title Contains 512-bit math functions/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits/// @dev Code has been modified to be compatible with sol 0.8libraryFullMath{
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0/// @param a The multiplicand/// @param b The multiplier/// @param denominator The divisor/// @return result The 256-bit result/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldivfunctionmulDivFloor(uint256 a,
uint256 b,
uint256 denominator
) internalpurereturns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b// Compute the product mod 2**256 and mod 2**256 - 1// then use the Chinese Remainder Theorem to reconstruct// the 512 bit result. The result is stored in two 256// variables such that product = prod1 * 2**256 + prod0uint256 prod0; // Least significant 256 bits of the productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(a, b, not(0))
prod0 :=mul(a, b)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 divisionif (prod1 ==0) {
require(denominator >0, '0 denom');
assembly {
result :=div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.// Also prevents denominator == 0require(denominator > prod1, 'denom <= prod1');
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0]// Compute remainder using mulmoduint256 remainder;
assembly {
remainder :=mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit numberassembly {
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator// Compute largest power of two divisor of denominator.// Always >= 1.uint256 twos = denominator & (~denominator +1);
// Divide denominator by power of twoassembly {
denominator :=div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of twoassembly {
prod0 :=div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need// to flip `twos` such that it is 2**256 / twos.// If twos is zero, then it becomes oneassembly {
twos :=add(div(sub(0, twos), twos), 1)
}
unchecked {
prod0 |= prod1 * twos;
// Invert denominator mod 2**256// Now that denominator is an odd number, it has an inverse// modulo 2**256 such that denominator * inv = 1 mod 2**256.// Compute the inverse by starting with a seed that is correct// correct for four bits. That is, denominator * inv = 1 mod 2**4uint256 inv = (3* denominator) ^2;
// Now use Newton-Raphson iteration to improve the precision.// Thanks to Hensel's lifting lemma, this also works in modular// arithmetic, doubling the correct bits in each step.
inv *=2- denominator * inv; // inverse mod 2**8
inv *=2- denominator * inv; // inverse mod 2**16
inv *=2- denominator * inv; // inverse mod 2**32
inv *=2- denominator * inv; // inverse mod 2**64
inv *=2- denominator * inv; // inverse mod 2**128
inv *=2- denominator * inv; // inverse mod 2**256// Because the division is now exact we can divide by multiplying// with the modular inverse of denominator. This will give us the// correct result modulo 2**256. Since the precoditions guarantee// that the outcome is less than 2**256, this is the final result.// We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inv;
}
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0/// @param a The multiplicand/// @param b The multiplier/// @param denominator The divisor/// @return result The 256-bit resultfunctionmulDivCeiling(uint256 a,
uint256 b,
uint256 denominator
) internalpurereturns (uint256 result) {
result = mulDivFloor(a, b, denominator);
if (mulmod(a, b, denominator) >0) {
result++;
}
}
}
Contract Source Code
File 12 of 44: IBasePositionManager.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;import {IERC721Metadata} from'@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import {IRouterTokenHelper} from'./IRouterTokenHelper.sol';
import {IBasePositionManagerEvents} from'./base_position_manager/IBasePositionManagerEvents.sol';
import {IERC721Permit} from'./IERC721Permit.sol';
interfaceIBasePositionManagerisIRouterTokenHelper, IBasePositionManagerEvents{
structPosition {
// the nonce for permitsuint96 nonce;
// the address that is approved for spending this tokenaddress operator;
// the ID of the pool with which this token is connecteduint80 poolId;
// the tick range of the positionint24 tickLower;
int24 tickUpper;
// the liquidity of the positionuint128 liquidity;
// the current rToken that the position oweduint256 rTokenOwed;
// fee growth per unit of liquidity as of the last update to liquidityuint256 feeGrowthInsideLast;
}
structPoolInfo {
address token0;
uint24 fee;
address token1;
}
/// @notice Params for the first time adding liquidity, mint new nft to sender/// @param token0 the token0 of the pool/// @param token1 the token1 of the pool/// - must make sure that token0 < token1/// @param fee the pool's fee in bps/// @param tickLower the position's lower tick/// @param tickUpper the position's upper tick/// - must make sure tickLower < tickUpper, and both are in tick distance/// @param ticksPrevious the nearest tick that has been initialized and lower than or equal to/// the tickLower and tickUpper, use to help insert the tickLower and tickUpper if haven't initialized/// @param amount0Desired the desired amount for token0/// @param amount1Desired the desired amount for token1/// @param amount0Min min amount of token 0 to add/// @param amount1Min min amount of token 1 to add/// @param recipient the owner of the position/// @param deadline time that the transaction will be expiredstructMintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
int24[2] ticksPrevious;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Params for adding liquidity to the existing position/// @param tokenId id of the position to increase its liquidity/// @param amount0Desired the desired amount for token0/// @param amount1Desired the desired amount for token1/// @param amount0Min min amount of token 0 to add/// @param amount1Min min amount of token 1 to add/// @param deadline time that the transaction will be expiredstructIncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Params for remove liquidity from the existing position/// @param tokenId id of the position to remove its liquidity/// @param amount0Min min amount of token 0 to receive/// @param amount1Min min amount of token 1 to receive/// @param deadline time that the transaction will be expiredstructRemoveLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Burn the rTokens to get back token0 + token1 as fees/// @param tokenId id of the position to burn r token/// @param amount0Min min amount of token 0 to receive/// @param amount1Min min amount of token 1 to receive/// @param deadline time that the transaction will be expiredstructBurnRTokenParams {
uint256 tokenId;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Creates a new pool if it does not exist, then unlocks if it has not been unlocked/// @param token0 the token0 of the pool/// @param token1 the token1 of the pool/// @param fee the fee for the pool/// @param currentSqrtP the initial price of the pool/// @return pool returns the pool addressfunctioncreateAndUnlockPoolIfNecessary(address token0,
address token1,
uint24 fee,
uint160 currentSqrtP
) externalpayablereturns (address pool);
functionmint(MintParams calldata params)
externalpayablereturns (uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
functionaddLiquidity(IncreaseLiquidityParams calldata params)
externalpayablereturns (uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
functionremoveLiquidity(RemoveLiquidityParams calldata params)
externalreturns (uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
functionburnRTokens(BurnRTokenParams calldata params)
externalreturns (uint256 rTokenQty,
uint256 amount0,
uint256 amount1
);
/**
* @dev Burn the token by its owner
* @notice All liquidity should be removed before burning
*/functionburn(uint256 tokenId) externalpayable;
functionpositions(uint256 tokenId)
externalviewreturns (Position memory pos, PoolInfo memory info);
functionaddressToPoolId(address pool) externalviewreturns (uint80);
functionisRToken(address token) externalviewreturns (bool);
functionnextPoolId() externalviewreturns (uint80);
functionnextTokenId() externalviewreturns (uint256);
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 13 of 44: IBasePositionManagerEvents.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;interfaceIBasePositionManagerEvents{
/// @notice Emitted when a token is minted for a given position/// @param tokenId the newly minted tokenId/// @param poolId poolId of the token/// @param liquidity liquidity minted to the position range/// @param amount0 token0 quantity needed to mint the liquidity/// @param amount1 token1 quantity needed to mint the liquidityeventMintPosition(uint256indexed tokenId,
uint80indexed poolId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when a token is burned/// @param tokenId id of the tokeneventBurnPosition(uint256indexed tokenId);
/// @notice Emitted when add liquidity/// @param tokenId id of the token/// @param liquidity the increase amount of liquidity/// @param amount0 token0 quantity needed to increase liquidity/// @param amount1 token1 quantity needed to increase liquidity/// @param additionalRTokenOwed additional rToken earnedeventAddLiquidity(uint256indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
/// @notice Emitted when remove liquidity/// @param tokenId id of the token/// @param liquidity the decease amount of liquidity/// @param amount0 token0 quantity returned when remove liquidity/// @param amount1 token1 quantity returned when remove liquidity/// @param additionalRTokenOwed additional rToken earnedeventRemoveLiquidity(uint256indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
}
Contract Source Code
File 14 of 44: IERC165.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/interfaceIERC165{
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 15 of 44: IERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address recipient, 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 `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransferFrom(address sender,
address recipient,
uint256 amount
) externalreturns (bool);
/**
* @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);
}
Contract Source Code
File 16 of 44: IERC721.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/interfaceIERC721isIERC165{
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/eventTransfer(addressindexedfrom, addressindexed to, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/eventApproval(addressindexed owner, addressindexed approved, uint256indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/eventApprovalForAll(addressindexed owner, addressindexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/functionbalanceOf(address owner) externalviewreturns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functionownerOf(uint256 tokenId) externalviewreturns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/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 Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/functiongetApproved(uint256 tokenId) externalviewreturns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/functionsetApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/functionisApprovedForAll(address owner, address operator) externalviewreturns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId,
bytescalldata data
) external;
}
Contract Source Code
File 17 of 44: IERC721Enumerable.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/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 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/functiontokenByIndex(uint256 index) externalviewreturns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;import {IERC721} from'@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC721Enumerable} from'@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
/// @title ERC721 with permit/// @notice Extension to ERC721 that includes a permit function for signature based approvalsinterfaceIERC721PermitisIERC721, IERC721Enumerable{
/// @notice The permit typehash used in the permit signature/// @return The typehash for the permitfunctionPERMIT_TYPEHASH() externalpurereturns (bytes32);
/// @notice The domain separator used in the permit signature/// @return The domain seperator used in encoding of permit signaturefunctionDOMAIN_SEPARATOR() externalviewreturns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature/// @param spender The account that is being approved/// @param tokenId The ID of the token that is being approved for spending/// @param deadline The deadline timestamp by which the call must be mined for the approve to work/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`functionpermit(address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/functionsupportsInterface(bytes4 interfaceId) externalviewreturns (bool);
}
Contract Source Code
File 20 of 44: IERC721Receiver.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
Contract Source Code
File 21 of 44: IFactory.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;/// @title KyberSwap v2 factory/// @notice Deploys KyberSwap v2 pools and manages control over government feesinterfaceIFactory{
/// @notice Emitted when a pool is created/// @param token0 First pool token by address sort order/// @param token1 Second pool token by address sort order/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units/// @param tickDistance Minimum number of ticks between initialized ticks/// @param pool The address of the created pooleventPoolCreated(addressindexed token0,
addressindexed token1,
uint24indexed swapFeeUnits,
int24 tickDistance,
address pool
);
/// @notice Emitted when a new fee is enabled for pool creation via the factory/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units/// @param tickDistance Minimum number of ticks between initialized ticks for pools created with the given feeeventSwapFeeEnabled(uint24indexed swapFeeUnits, int24indexed tickDistance);
/// @notice Emitted when vesting period changes/// @param vestingPeriod The maximum time duration for which LP fees/// are proportionally burnt upon LP removalseventVestingPeriodUpdated(uint32 vestingPeriod);
/// @notice Emitted when configMaster changes/// @param oldConfigMaster configMaster before the update/// @param newConfigMaster configMaster after the updateeventConfigMasterUpdated(address oldConfigMaster, address newConfigMaster);
/// @notice Emitted when fee configuration changes/// @param feeTo Recipient of government fees/// @param governmentFeeUnits Fee amount, in fee units,/// to be collected out of the fee charged for a pool swapeventFeeConfigurationUpdated(address feeTo, uint24 governmentFeeUnits);
/// @notice Emitted when whitelist feature is enabledeventWhitelistEnabled();
/// @notice Emitted when whitelist feature is disabledeventWhitelistDisabled();
/// @notice Returns the maximum time duration for which LP fees/// are proportionally burnt upon LP removalsfunctionvestingPeriod() externalviewreturns (uint32);
/// @notice Returns the tick distance for a specified fee./// @dev Once added, cannot be updated or removed./// @param swapFeeUnits Swap fee, in fee units./// @return The tick distance. Returns 0 if fee has not been added.functionfeeAmountTickDistance(uint24 swapFeeUnits) externalviewreturns (int24);
/// @notice Returns the address which can update the fee configurationfunctionconfigMaster() externalviewreturns (address);
/// @notice Returns the keccak256 hash of the Pool creation code/// This is used for pre-computation of pool addressesfunctionpoolInitHash() externalviewreturns (bytes32);
/// @notice Fetches the recipient of government fees/// and current government fee charged in fee unitsfunctionfeeConfiguration() externalviewreturns (address _feeTo, uint24 _governmentFeeUnits);
/// @notice Returns the status of whitelisting feature of NFT managers/// If true, anyone can mint liquidity tokens/// Otherwise, only whitelisted NFT manager(s) are allowed to mint liquidity tokensfunctionwhitelistDisabled() externalviewreturns (bool);
//// @notice Returns all whitelisted NFT managers/// If the whitelisting feature is turned on,/// only whitelisted NFT manager(s) are allowed to mint liquidity tokensfunctiongetWhitelistedNFTManagers() externalviewreturns (address[] memory);
/// @notice Checks if sender is a whitelisted NFT manager/// If the whitelisting feature is turned on,/// only whitelisted NFT manager(s) are allowed to mint liquidity tokens/// @param sender address to be checked/// @return true if sender is a whistelisted NFT manager, false otherwisefunctionisWhitelistedNFTManager(address sender) externalviewreturns (bool);
/// @notice Returns the pool address for a given pair of tokens and a swap fee/// @dev Token order does not matter/// @param tokenA Contract address of either token0 or token1/// @param tokenB Contract address of the other token/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units/// @return pool The pool address. Returns null address if it does not existfunctiongetPool(address tokenA,
address tokenB,
uint24 swapFeeUnits
) externalviewreturns (address pool);
/// @notice Fetch parameters to be used for pool creation/// @dev Called by the pool constructor to fetch the parameters of the pool/// @return factory The factory address/// @return token0 First pool token by address sort order/// @return token1 Second pool token by address sort order/// @return swapFeeUnits Fee to be collected upon every swap in the pool, in fee units/// @return tickDistance Minimum number of ticks between initialized ticksfunctionparameters()
externalviewreturns (address factory,
address token0,
address token1,
uint24 swapFeeUnits,
int24 tickDistance
);
/// @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 swapFeeUnits Desired swap fee for the pool, in fee units/// @dev Token order does not matter. tickDistance is determined from the fee./// Call will revert under any of these conditions:/// 1) pool already exists/// 2) invalid swap fee/// 3) invalid token arguments/// @return pool The address of the newly created poolfunctioncreatePool(address tokenA,
address tokenB,
uint24 swapFeeUnits
) externalreturns (address pool);
/// @notice Enables a fee amount with the given tickDistance/// @dev Fee amounts may never be removed once enabled/// @param swapFeeUnits The fee amount to enable, in fee units/// @param tickDistance The distance between ticks to be enforced for all pools created with the given fee amountfunctionenableSwapFee(uint24 swapFeeUnits, int24 tickDistance) external;
/// @notice Updates the address which can update the fee configuration/// @dev Must be called by the current configMasterfunctionupdateConfigMaster(address) external;
/// @notice Updates the vesting period/// @dev Must be called by the current configMasterfunctionupdateVestingPeriod(uint32) external;
/// @notice Updates the address receiving government fees and fee quantity/// @dev Only configMaster is able to perform the update/// @param feeTo Address to receive government fees collected from pools/// @param governmentFeeUnits Fee amount, in fee units,/// to be collected out of the fee charged for a pool swapfunctionupdateFeeConfiguration(address feeTo, uint24 governmentFeeUnits) external;
/// @notice Enables the whitelisting feature/// @dev Only configMaster is able to perform the updatefunctionenableWhitelist() external;
/// @notice Disables the whitelisting feature/// @dev Only configMaster is able to perform the updatefunctiondisableWhitelist() external;
}
Contract Source Code
File 22 of 44: IMintCallback.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;/// @title Callback for IPool#mint/// @notice Any contract that calls IPool#mint must implement this interfaceinterfaceIMintCallback{
/// @notice Called to `msg.sender` after minting liquidity via IPool#mint./// @dev This function's implementation must send pool tokens to the pool for the minted LP tokens./// The caller of this method must be checked to be a Pool deployed by the canonical Factory./// @param deltaQty0 The token0 quantity to be sent to the pool./// @param deltaQty1 The token1 quantity to be sent to the pool./// @param data Data passed through by the caller via the IPool#mint callfunctionmintCallback(uint256 deltaQty0,
uint256 deltaQty1,
bytescalldata data
) external;
}
Contract Source Code
File 23 of 44: IMulticall.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;pragmaabicoderv2;/// @title Multicall interface/// @notice Enables calling multiple methods in a single call to the contractinterfaceIMulticall{
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed/// @dev The `msg.value` should not be trusted for any method callable from multicall./// @param data The encoded function data for each of the calls to make to this contract/// @return results The results from each of the calls passed in via datafunctionmulticall(bytes[] calldata data) externalpayablereturns (bytes[] memory results);
}
Contract Source Code
File 24 of 44: INonfungibleTokenPositionDescriptor.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;import'./IBasePositionManager.sol';
/// @title Describes position NFT tokens via URIinterfaceINonfungibleTokenPositionDescriptor{
/// @notice Produces the URI describing a particular token ID for a position manager/// @dev Note this URI may be a data: URI with the JSON contents directly inlined/// @param positionManager The position manager for which to describe the token/// @param tokenId The ID of the token for which to produce a description, which may not be valid/// @return The URI of the ERC721-compliant metadatafunctiontokenURI(IBasePositionManager positionManager, uint256 tokenId)
externalviewreturns (stringmemory);
}
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;interfaceIPoolActions{
/// @notice Sets the initial price for the pool and seeds reinvestment liquidity/// @dev Assumes the caller has sent the necessary token amounts/// required for initializing reinvestment liquidity prior to calling this function/// @param initialSqrtP the initial sqrt price of the pool/// @param qty0 token0 quantity sent to and locked permanently in the pool/// @param qty1 token1 quantity sent to and locked permanently in the poolfunctionunlockPool(uint160 initialSqrtP) externalreturns (uint256 qty0, uint256 qty1);
/// @notice Adds liquidity for the specified recipient/tickLower/tickUpper position/// @dev Any token0 or token1 owed for the liquidity provision have to be paid for when/// the IMintCallback#mintCallback is called to this method's caller/// The quantity of token0/token1 to be sent depends on/// tickLower, tickUpper, the amount of liquidity, and the current price of the pool./// Also sends reinvestment tokens (fees) to the recipient for any fees collected/// while the position is in range/// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1/// @param recipient Address for which the added liquidity is credited to/// @param tickLower Recipient position's lower tick/// @param tickUpper Recipient position's upper tick/// @param ticksPrevious The nearest tick that is initialized and <= the lower & upper ticks/// @param qty Liquidity quantity to mint/// @param data Data (if any) to be passed through to the callback/// @return qty0 token0 quantity sent to the pool in exchange for the minted liquidity/// @return qty1 token1 quantity sent to the pool in exchange for the minted liquidity/// @return feeGrowthInside position's updated feeGrowthInside valuefunctionmint(address recipient,
int24 tickLower,
int24 tickUpper,
int24[2] calldata ticksPrevious,
uint128 qty,
bytescalldata data
)
externalreturns (uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
/// @notice Remove liquidity from the caller/// Also sends reinvestment tokens (fees) to the caller for any fees collected/// while the position is in range/// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1/// @param tickLower Position's lower tick for which to burn liquidity/// @param tickUpper Position's upper tick for which to burn liquidity/// @param qty Liquidity quantity to burn/// @return qty0 token0 quantity sent to the caller/// @return qty1 token1 quantity sent to the caller/// @return feeGrowthInside position's updated feeGrowthInside valuefunctionburn(int24 tickLower,
int24 tickUpper,
uint128 qty
)
externalreturns (uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
/// @notice Burns reinvestment tokens in exchange to receive the fees collected in token0 and token1/// @param qty Reinvestment token quantity to burn/// @param isLogicalBurn true if burning rTokens without returning any token0/token1/// otherwise should transfer token0/token1 to sender/// @return qty0 token0 quantity sent to the caller for burnt reinvestment tokens/// @return qty1 token1 quantity sent to the caller for burnt reinvestment tokensfunctionburnRTokens(uint256 qty, bool isLogicalBurn)
externalreturns (uint256 qty0, uint256 qty1);
/// @notice Swap token0 -> token1, or vice versa/// @dev This method's caller receives a callback in the form of ISwapCallback#swapCallback/// @dev swaps will execute up to limitSqrtP or swapQty is fully used/// @param recipient The address to receive the swap output/// @param swapQty The swap quantity, which implicitly configures the swap as exact input (>0), or exact output (<0)/// @param isToken0 Whether the swapQty is specified in token0 (true) or token1 (false)/// @param limitSqrtP the limit of sqrt price after swapping/// could be MAX_SQRT_RATIO-1 when swapping 1 -> 0 and MIN_SQRT_RATIO+1 when swapping 0 -> 1 for no limit swap/// @param data Any data to be passed through to the callback/// @return qty0 Exact token0 qty sent to recipient if < 0. Minimally received quantity if > 0./// @return qty1 Exact token1 qty sent to recipient if < 0. Minimally received quantity if > 0.functionswap(address recipient,
int256 swapQty,
bool isToken0,
uint160 limitSqrtP,
bytescalldata data
) externalreturns (int256 qty0, int256 qty1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback/// @dev The caller of this method receives a callback in the form of IFlashCallback#flashCallback/// @dev Fees collected are sent to the feeTo address if it is set in Factory/// @param recipient The address which will receive the token0 and token1 quantities/// @param qty0 token0 quantity to be loaned to the recipient/// @param qty1 token1 quantity to be loaned to the recipient/// @param data Any data to be passed through to the callbackfunctionflash(address recipient,
uint256 qty0,
uint256 qty1,
bytescalldata data
) external;
}
Contract Source Code
File 27 of 44: IPoolEvents.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;interfaceIPoolEvents{
/// @notice Emitted only once per pool when #initialize is first called/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize/// @param sqrtP The initial price of the pool/// @param tick The initial tick of the pooleventInitialize(uint160 sqrtP, int24 tick);
/// @notice Emitted when liquidity is minted for a given position/// @dev transfers reinvestment tokens for any collected fees earned by the position/// @param sender address that minted the liquidity/// @param owner address of owner of the position/// @param tickLower position's lower tick/// @param tickUpper position's upper tick/// @param qty liquidity minted to the position range/// @param qty0 token0 quantity needed to mint the liquidity/// @param qty1 token1 quantity needed to mint the liquidityeventMint(address sender,
addressindexed owner,
int24indexed tickLower,
int24indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
/// @notice Emitted when a position's liquidity is removed/// @dev transfers reinvestment tokens for any collected fees earned by the position/// @param owner address of owner of the position/// @param tickLower position's lower tick/// @param tickUpper position's upper tick/// @param qty liquidity removed/// @param qty0 token0 quantity withdrawn from removal of liquidity/// @param qty1 token1 quantity withdrawn from removal of liquidityeventBurn(addressindexed owner,
int24indexed tickLower,
int24indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
/// @notice Emitted when reinvestment tokens are burnt/// @param owner address which burnt the reinvestment tokens/// @param qty reinvestment token quantity burnt/// @param qty0 token0 quantity sent to owner for burning reinvestment tokens/// @param qty1 token1 quantity sent to owner for burning reinvestment tokenseventBurnRTokens(addressindexed owner, uint256 qty, uint256 qty0, uint256 qty1);
/// @notice Emitted for swaps by the pool between token0 and token1/// @param sender Address that initiated the swap call, and that received the callback/// @param recipient Address that received the swap output/// @param deltaQty0 Change in pool's token0 balance/// @param deltaQty1 Change in pool's token1 balance/// @param sqrtP Pool's sqrt price after the swap/// @param liquidity Pool's liquidity after the swap/// @param currentTick Log base 1.0001 of pool's price after the swapeventSwap(addressindexed sender,
addressindexed recipient,
int256 deltaQty0,
int256 deltaQty1,
uint160 sqrtP,
uint128 liquidity,
int24 currentTick
);
/// @notice Emitted by the pool for any flash loans of token0/token1/// @param sender The address that initiated the flash loan, and that received the callback/// @param recipient The address that received the flash loan quantities/// @param qty0 token0 quantity loaned to the recipient/// @param qty1 token1 quantity loaned to the recipient/// @param paid0 token0 quantity paid for the flash, which can exceed qty0 + fee/// @param paid1 token1 quantity paid for the flash, which can exceed qty0 + feeeventFlash(addressindexed sender,
addressindexed recipient,
uint256 qty0,
uint256 qty1,
uint256 paid0,
uint256 paid1
);
}
Contract Source Code
File 28 of 44: IPoolStorage.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;import {IERC20} from'@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IFactory} from'../IFactory.sol';
interfaceIPoolStorage{
/// @notice The contract that deployed the pool, which must adhere to the IFactory interface/// @return The contract addressfunctionfactory() externalviewreturns (IFactory);
/// @notice The first of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken0() externalviewreturns (IERC20);
/// @notice The second of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken1() externalviewreturns (IERC20);
/// @notice The fee to be charged for a swap in basis points/// @return The swap fee in basis pointsfunctionswapFeeUnits() externalviewreturns (uint24);
/// @notice The pool tick distance/// @dev Ticks can only be initialized and used at multiples of this value/// It remains an int24 to avoid casting even though it is >= 1./// e.g: a tickDistance of 5 means ticks can be initialized every 5th tick, i.e., ..., -10, -5, 0, 5, 10, .../// @return The tick distancefunctiontickDistance() externalviewreturns (int24);
/// @notice Maximum gross liquidity that an initialized tick can have/// @dev This is to prevent overflow the pool's active base liquidity (uint128)/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool/// @return The max amount of liquidity per tickfunctionmaxTickLiquidity() externalviewreturns (uint128);
/// @notice Look up information about a specific tick in the pool/// @param tick The tick to look up/// @return liquidityGross total liquidity amount from positions that uses this tick as a lower or upper tick/// liquidityNet how much liquidity changes when the pool tick crosses above the tick/// feeGrowthOutside the fee growth on the other side of the tick relative to the current tick/// secondsPerLiquidityOutside the seconds spent on the other side of the tick relative to the current tickfunctionticks(int24 tick)
externalviewreturns (uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside,
uint128 secondsPerLiquidityOutside
);
/// @notice Returns the previous and next initialized ticks of a specific tick/// @dev If specified tick is uninitialized, the returned values are zero./// @param tick The tick to look upfunctioninitializedTicks(int24 tick) externalviewreturns (int24 previous, int24 next);
/// @notice Returns the information about a position by the position's key/// @return liquidity the liquidity quantity of the position/// @return feeGrowthInsideLast fee growth inside the tick range as of the last mint / burn action performedfunctiongetPositions(address owner,
int24 tickLower,
int24 tickUpper
) externalviewreturns (uint128 liquidity, uint256 feeGrowthInsideLast);
/// @notice Fetches the pool's prices, ticks and lock status/// @return sqrtP sqrt of current price: sqrt(token1/token0)/// @return currentTick pool's current tick/// @return nearestCurrentTick pool's nearest initialized tick that is <= currentTick/// @return locked true if pool is locked, false otherwisefunctiongetPoolState()
externalviewreturns (uint160 sqrtP,
int24 currentTick,
int24 nearestCurrentTick,
bool locked
);
/// @notice Fetches the pool's liquidity values/// @return baseL pool's base liquidity without reinvest liqudity/// @return reinvestL the liquidity is reinvested into the pool/// @return reinvestLLast last cached value of reinvestL, used for calculating reinvestment token qtyfunctiongetLiquidityState()
externalviewreturns (uint128 baseL,
uint128 reinvestL,
uint128 reinvestLLast
);
/// @return feeGrowthGlobal All-time fee growth per unit of liquidity of the poolfunctiongetFeeGrowthGlobal() externalviewreturns (uint256);
/// @return secondsPerLiquidityGlobal All-time seconds per unit of liquidity of the pool/// @return lastUpdateTime The timestamp in which secondsPerLiquidityGlobal was last updatedfunctiongetSecondsPerLiquidityData()
externalviewreturns (uint128 secondsPerLiquidityGlobal, uint32 lastUpdateTime);
/// @notice Calculates and returns the active time per unit of liquidity until current block.timestamp/// @param tickLower The lower tick (of a position)/// @param tickUpper The upper tick (of a position)/// @return secondsPerLiquidityInside active time (multiplied by 2^96)/// between the 2 ticks, per unit of liquidity.functiongetSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
externalviewreturns (uint128 secondsPerLiquidityInside);
}
Contract Source Code
File 29 of 44: IRouterTokenHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;interfaceIRouterTokenHelper{
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH./// @dev The minAmount parameter prevents malicious contracts from stealing WETH from users./// @param minAmount The minimum amount of WETH to unwrap/// @param recipient The address receiving ETHfunctionunwrapWeth(uint256 minAmount, address recipient) externalpayable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps/// that use ether for the input amountfunctionrefundEth() externalpayable;
/// @notice Transfers the full amount of a token held by this contract to recipient/// @dev The minAmount parameter prevents malicious contracts from stealing the token from users/// @param token The contract address of the token which will be transferred to `recipient`/// @param minAmount The minimum amount of token required for a transfer/// @param recipient The destination address of the tokenfunctiontransferAllTokens(address token,
uint256 minAmount,
address recipient
) externalpayable;
}
Contract Source Code
File 30 of 44: IWETH.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;import {IERC20} from'@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Interface for WETHinterfaceIWETHisIERC20{
/// @notice Deposit ether to get wrapped etherfunctiondeposit() externalpayable;
/// @notice Withdraw wrapped ether to get etherfunctionwithdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;pragmaabicoderv2;import {LiquidityMath} from'../libraries/LiquidityMath.sol';
import {PoolAddress} from'../libraries/PoolAddress.sol';
import {TickMath} from'../../libraries/TickMath.sol';
import {IPool} from'../../interfaces/IPool.sol';
import {IFactory} from'../../interfaces/IFactory.sol';
import {IMintCallback} from'../../interfaces/callback/IMintCallback.sol';
import {RouterTokenHelper} from'./RouterTokenHelper.sol';
abstractcontractLiquidityHelperisIMintCallback, RouterTokenHelper{
constructor(address _factory, address _WETH) RouterTokenHelper(_factory, _WETH) {}
structAddLiquidityParams {
address token0;
address token1;
uint24 fee;
address recipient;
int24 tickLower;
int24 tickUpper;
int24[2] ticksPrevious;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
}
structCallbackData {
address token0;
address token1;
uint24 fee;
address source;
}
functionmintCallback(uint256 deltaQty0,
uint256 deltaQty1,
bytescalldata data
) externaloverride{
CallbackData memory callbackData =abi.decode(data, (CallbackData));
require(callbackData.token0 < callbackData.token1, 'LiquidityHelper: wrong token order');
address pool =address(_getPool(callbackData.token0, callbackData.token1, callbackData.fee));
require(msg.sender== pool, 'LiquidityHelper: invalid callback sender');
if (deltaQty0 >0)
_transferTokens(callbackData.token0, callbackData.source, msg.sender, deltaQty0);
if (deltaQty1 >0)
_transferTokens(callbackData.token1, callbackData.source, msg.sender, deltaQty1);
}
/// @dev Add liquidity to a pool given params/// @param params add liquidity params, token0, token1 should be in the correct order/// @return liquidity amount of liquidity has been minted/// @return amount0 amount of token0 that is needed/// @return amount1 amount of token1 that is needed/// @return feeGrowthInsideLast position manager's updated feeGrowthInsideLast value/// @return pool address of the poolfunction_addLiquidity(AddLiquidityParams memory params)
internalreturns (uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 feeGrowthInsideLast,
IPool pool
)
{
require(params.token0 < params.token1, 'LiquidityHelper: invalid token order');
pool = _getPool(params.token0, params.token1, params.fee);
// compute the liquidity amount
{
(uint160 currentSqrtP, , , ) = pool.getPoolState();
uint160 lowerSqrtP = TickMath.getSqrtRatioAtTick(params.tickLower);
uint160 upperSqrtP = TickMath.getSqrtRatioAtTick(params.tickUpper);
liquidity = LiquidityMath.getLiquidityFromQties(
currentSqrtP,
lowerSqrtP,
upperSqrtP,
params.amount0Desired,
params.amount1Desired
);
}
(amount0, amount1, feeGrowthInsideLast) = pool.mint(
params.recipient,
params.tickLower,
params.tickUpper,
params.ticksPrevious,
liquidity,
_callbackData(params.token0, params.token1, params.fee)
);
require(
amount0 >= params.amount0Min && amount1 >= params.amount1Min,
'LiquidityHelper: price slippage check'
);
}
function_callbackData(address token0,
address token1,
uint24 fee
) internalviewreturns (bytesmemory) {
returnabi.encode(CallbackData({token0: token0, token1: token1, fee: fee, source: msg.sender}));
}
/**
* @dev Returns the pool address for the requested token pair swap fee
* Because the function calculates it instead of fetching the address from the factory,
* the returned pool address may not be in existence yet
*/function_getPool(address tokenA,
address tokenB,
uint24 fee
) internalviewreturns (IPool) {
return IPool(PoolAddress.computeAddress(factory, tokenA, tokenB, fee, poolInitHash));
}
}
Contract Source Code
File 33 of 44: LiquidityMath.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity 0.8.9;import {MathConstantsasC} from'../../libraries/MathConstants.sol';
import {FullMath} from'../../libraries/FullMath.sol';
import {SafeCast} from'../../libraries/SafeCast.sol';
libraryLiquidityMath{
usingSafeCastforuint256;
/// @notice Gets liquidity from qty 0 and the price range/// qty0 = liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))/// => liquidity = qty0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))/// @param lowerSqrtP A lower sqrt price/// @param upperSqrtP An upper sqrt price/// @param qty0 amount of token0/// @return liquidity amount of returned liquidity to not exceed the qty0functiongetLiquidityFromQty0(uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0
) internalpurereturns (uint128) {
uint256 liq = FullMath.mulDivFloor(lowerSqrtP, upperSqrtP, C.TWO_POW_96);
unchecked {
return FullMath.mulDivFloor(liq, qty0, upperSqrtP - lowerSqrtP).toUint128();
}
}
/// @notice Gets liquidity from qty 1 and the price range/// @dev qty1 = liquidity * (sqrt(upper) - sqrt(lower))/// thus, liquidity = qty1 / (sqrt(upper) - sqrt(lower))/// @param lowerSqrtP A lower sqrt price/// @param upperSqrtP An upper sqrt price/// @param qty1 amount of token1/// @return liquidity amount of returned liquidity to not exceed to qty1functiongetLiquidityFromQty1(uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty1
) internalpurereturns (uint128) {
unchecked {
return FullMath.mulDivFloor(qty1, C.TWO_POW_96, upperSqrtP - lowerSqrtP).toUint128();
}
}
/// @notice Gets liquidity given price range and 2 qties of token0 and token1/// @param currentSqrtP current price/// @param lowerSqrtP A lower sqrt price/// @param upperSqrtP An upper sqrt price/// @param qty0 amount of token0 - at most/// @param qty1 amount of token1 - at most/// @return liquidity amount of returned liquidity to not exceed the given qtiesfunctiongetLiquidityFromQties(uint160 currentSqrtP,
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0,
uint256 qty1
) internalpurereturns (uint128) {
if (currentSqrtP <= lowerSqrtP) {
return getLiquidityFromQty0(lowerSqrtP, upperSqrtP, qty0);
}
if (currentSqrtP >= upperSqrtP) {
return getLiquidityFromQty1(lowerSqrtP, upperSqrtP, qty1);
}
uint128 liq0 = getLiquidityFromQty0(currentSqrtP, upperSqrtP, qty0);
uint128 liq1 = getLiquidityFromQty1(lowerSqrtP, currentSqrtP, qty1);
return liq0 < liq1 ? liq0 : liq1;
}
}
Contract Source Code
File 34 of 44: Math.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryMath{
/**
* @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 / b + (a % b ==0 ? 0 : 1);
}
}
Contract Source Code
File 35 of 44: MathConstants.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity >=0.8.0;/// @title Contains constants needed for math librarieslibraryMathConstants{
uint256internalconstant TWO_FEE_UNITS =200_000;
uint256internalconstant TWO_POW_96 =2**96;
uint128internalconstant MIN_LIQUIDITY =100000;
uint8internalconstant RES_96 =96;
uint24internalconstant BPS =10000;
uint24internalconstant FEE_UNITS =100000;
// it is strictly less than 5% price movement if jumping MAX_TICK_DISTANCE ticksint24internalconstant MAX_TICK_DISTANCE =480;
// max number of tick travel when inserting if data changesuint256internalconstant MAX_TICK_TRAVEL =10;
}
Contract Source Code
File 36 of 44: Multicall.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;pragmaabicoderv2;import {IMulticall} from'../../interfaces/periphery/IMulticall.sol';
/// @title Multicall/// @notice Enables calling multiple methods in a single call to the contractabstractcontractMulticallisIMulticall{
/// @inheritdoc IMulticallfunctionmulticall(bytes[] calldata data)
externalpayableoverridereturns (bytes[] memory results)
{
results =newbytes[](data.length);
for (uint256 i =0; i < data.length; i++) {
(bool success, bytesmemory result) =address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577if (result.length<68) revert();
assembly {
result :=add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
Contract Source Code
File 37 of 44: PoolAddress.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;/// @title Provides a function for deriving a pool address from the factory, tokens, and swap feelibraryPoolAddress{
/// @notice Deterministically computes the pool address from the given data/// @param factory the factory address/// @param token0 One of the tokens constituting the token pair, regardless of order/// @param token1 The other token constituting the token pair, regardless of order/// @param swapFee Fee to be collected upon every swap in the pool, in fee units/// @param poolInitHash The keccak256 hash of the Pool creation code/// @return pool the pool addressfunctioncomputeAddress(address factory,
address token0,
address token1,
uint24 swapFee,
bytes32 poolInitHash
) internalpurereturns (address pool) {
(token0, token1) = token0 < token1 ? (token0, token1) : (token1, token0);
bytes32 hashed =keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(token0, token1, swapFee)),
poolInitHash
)
);
pool =address(uint160(uint256(hashed)));
}
}
Contract Source Code
File 38 of 44: QtyDeltaMath.sol
// SPDX-License-Identifier: MITpragmasolidity >=0.8.0;import {MathConstantsasC} from'./MathConstants.sol';
import {TickMath} from'./TickMath.sol';
import {FullMath} from'./FullMath.sol';
import {SafeCast} from'./SafeCast.sol';
/// @title Contains helper functions for calculating/// token0 and token1 quantites from differences in prices/// or from burning reinvestment tokenslibraryQtyDeltaMath{
usingSafeCastforuint256;
usingSafeCastforint128;
functioncalcUnlockQtys(uint160 initialSqrtP)
internalpurereturns (uint256 qty0, uint256 qty1)
{
qty0 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, C.TWO_POW_96, initialSqrtP);
qty1 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, initialSqrtP, C.TWO_POW_96);
}
/// @notice Gets the qty0 delta between two prices/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))/// rounds up if adding liquidity, rounds down if removing liquidity/// @param lowerSqrtP The lower sqrt price./// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP/// @param liquidity Liquidity quantity/// @param isAddLiquidity true = add liquidity, false = remove liquidity/// @return token0 qty required for position with liquidity between the 2 sqrt pricesfunctioncalcRequiredQty0(uint160 lowerSqrtP,
uint160 upperSqrtP,
uint128 liquidity,
bool isAddLiquidity
) internalpurereturns (int256) {
uint256 numerator1 =uint256(liquidity) << C.RES_96;
uint256 numerator2;
unchecked {
numerator2 = upperSqrtP - lowerSqrtP;
}
return
isAddLiquidity
? (divCeiling(FullMath.mulDivCeiling(numerator1, numerator2, upperSqrtP), lowerSqrtP))
.toInt256()
: (FullMath.mulDivFloor(numerator1, numerator2, upperSqrtP) / lowerSqrtP).revToInt256();
}
/// @notice Gets the token1 delta quantity between two prices/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))/// rounds up if adding liquidity, rounds down if removing liquidity/// @param lowerSqrtP The lower sqrt price./// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP/// @param liquidity Liquidity quantity/// @param isAddLiquidity true = add liquidity, false = remove liquidity/// @return token1 qty required for position with liquidity between the 2 sqrt pricesfunctioncalcRequiredQty1(uint160 lowerSqrtP,
uint160 upperSqrtP,
uint128 liquidity,
bool isAddLiquidity
) internalpurereturns (int256) {
unchecked {
return
isAddLiquidity
? (FullMath.mulDivCeiling(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).toInt256()
: (FullMath.mulDivFloor(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).revToInt256();
}
}
/// @notice Calculates the token0 quantity proportion to be sent to the user/// for burning reinvestment tokens/// @param sqrtP Current pool sqrt price/// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn/// @return token0 quantity to be sent to the userfunctiongetQty0FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internalpurereturns (uint256)
{
return FullMath.mulDivFloor(liquidity, C.TWO_POW_96, sqrtP);
}
/// @notice Calculates the token1 quantity proportion to be sent to the user/// for burning reinvestment tokens/// @param sqrtP Current pool sqrt price/// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn/// @return token1 quantity to be sent to the userfunctiongetQty1FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internalpurereturns (uint256)
{
return FullMath.mulDivFloor(liquidity, sqrtP, C.TWO_POW_96);
}
/// @notice Returns ceil(x / y)/// @dev division by 0 has unspecified behavior, and must be checked externally/// @param x The dividend/// @param y The divisor/// @return z The quotient, ceil(x / y)functiondivCeiling(uint256 x, uint256 y) internalpurereturns (uint256 z) {
// return x / y + ((x % y == 0) ? 0 : 1);require(y >0);
assembly {
z :=add(div(x, y), gt(mod(x, y), 0))
}
}
}
Contract Source Code
File 39 of 44: RouterTokenHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity 0.8.9;import {IERC20} from'@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {TokenHelper} from'../libraries/TokenHelper.sol';
import {IRouterTokenHelper} from'../../interfaces/periphery/IRouterTokenHelper.sol';
import {IWETH} from'../../interfaces/IWETH.sol';
import {ImmutablePeripheryStorage} from'./ImmutablePeripheryStorage.sol';
abstractcontractRouterTokenHelperisIRouterTokenHelper, ImmutablePeripheryStorage{
constructor(address _factory, address _WETH) ImmutablePeripheryStorage(_factory, _WETH) {}
receive() externalpayable{
require(msg.sender== WETH, 'Not WETH');
}
/// @dev Unwrap all ETH balance and send to the recipientfunctionunwrapWeth(uint256 minAmount, address recipient) externalpayableoverride{
uint256 balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= minAmount, 'Insufficient WETH');
if (balanceWETH >0) {
IWETH(WETH).withdraw(balanceWETH);
TokenHelper.transferEth(recipient, balanceWETH);
}
}
/// @dev Transfer all tokens from the contract to the recipientfunctiontransferAllTokens(address token,
uint256 minAmount,
address recipient
) publicpayablevirtualoverride{
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= minAmount, 'Insufficient token');
if (balanceToken >0) {
TokenHelper.transferToken(IERC20(token), balanceToken, address(this), recipient);
}
}
/// @dev Send all ETH balance of this contract to the senderfunctionrefundEth() externalpayableoverride{
if (address(this).balance>0) TokenHelper.transferEth(msg.sender, address(this).balance);
}
/// @dev Transfer tokenAmount amount of token from the sender to the recipientfunction_transferTokens(address token,
address sender,
address recipient,
uint256 tokenAmount
) internal{
if (token == WETH &&address(this).balance>= tokenAmount) {
IWETH(WETH).deposit{value: tokenAmount}();
IWETH(WETH).transfer(recipient, tokenAmount);
} else {
TokenHelper.transferToken(IERC20(token), tokenAmount, sender, recipient);
}
}
}
Contract Source Code
File 40 of 44: SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;/// @title Safe casting methods/// @notice Contains methods for safely casting between typeslibrarySafeCast{
/// @notice Cast a uint256 to uint32, revert on overflow/// @param y The uint256 to be downcasted/// @return z The downcasted integer, now type uint32functiontoUint32(uint256 y) internalpurereturns (uint32 z) {
require((z =uint32(y)) == y);
}
/// @notice Cast a uint128 to a int128, revert on overflow/// @param y The uint256 to be casted/// @return z The casted integer, now type int256functiontoInt128(uint128 y) internalpurereturns (int128 z) {
require(y <2**127);
z =int128(y);
}
/// @notice Cast a uint256 to a uint128, revert on overflow/// @param y the uint256 to be downcasted/// @return z The downcasted integer, now type uint128functiontoUint128(uint256 y) internalpurereturns (uint128 z) {
require((z =uint128(y)) == y);
}
/// @notice Cast a int128 to a uint128 and reverses the sign./// @param y The int128 to be casted/// @return z = -y, now type uint128functionrevToUint128(int128 y) internalpurereturns (uint128 z) {
unchecked {
returntype(uint128).max-uint128(y) +1;
}
}
/// @notice Cast a uint256 to a uint160, revert on overflow/// @param y The uint256 to be downcasted/// @return z The downcasted integer, now type uint160functiontoUint160(uint256 y) internalpurereturns (uint160 z) {
require((z =uint160(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow/// @param y The uint256 to be casted/// @return z The casted integer, now type int256functiontoInt256(uint256 y) internalpurereturns (int256 z) {
require(y <2**255);
z =int256(y);
}
/// @notice Cast a uint256 to a int256 and reverses the sign, revert on overflow/// @param y The uint256 to be casted/// @return z = -y, now type int256functionrevToInt256(uint256 y) internalpurereturns (int256 z) {
require(y <2**255);
z =-int256(y);
}
/// @notice Cast a int256 to a uint256 and reverses the sign./// @param y The int256 to be casted/// @return z = -y, now type uint256functionrevToUint256(int256 y) internalpurereturns (uint256 z) {
unchecked {
returntype(uint256).max-uint256(y) +1;
}
}
}
Contract Source Code
File 41 of 44: SafeERC20.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;import"../IERC20.sol";
import"../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/librarySafeERC20{
usingAddressforaddress;
functionsafeTransfer(
IERC20 token,
address to,
uint256 value
) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
functionsafeTransferFrom(
IERC20 token,
addressfrom,
address to,
uint256 value
) internal{
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/functionsafeApprove(
IERC20 token,
address spender,
uint256 value
) internal{
// safeApprove should only be called when setting an initial allowance,// or when resetting it to zero. To increase and decrease it, use// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'require(
(value ==0) || (token.allowance(address(this), spender) ==0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
functionsafeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
functionsafeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal{
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/function_callOptionalReturn(IERC20 token, bytesmemory data) private{
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that// the target address contains contract code and also asserts for success in the low-level call.bytesmemory returndata =address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length>0) {
// Return data is optionalrequire(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
Contract Source Code
File 42 of 44: Strings.sol
// SPDX-License-Identifier: MITpragmasolidity ^0.8.0;/**
* @dev String operations.
*/libraryStrings{
bytes16privateconstant _HEX_SYMBOLS ="0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/functiontoString(uint256 value) internalpurereturns (stringmemory) {
// Inspired by OraclizeAPI's implementation - MIT licence// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.solif (value ==0) {
return"0";
}
uint256 temp = value;
uint256 digits;
while (temp !=0) {
digits++;
temp /=10;
}
bytesmemory buffer =newbytes(digits);
while (value !=0) {
digits -=1;
buffer[digits] =bytes1(uint8(48+uint256(value %10)));
value /=10;
}
returnstring(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/functiontoHexString(uint256 value) internalpurereturns (stringmemory) {
if (value ==0) {
return"0x00";
}
uint256 temp = value;
uint256 length =0;
while (temp !=0) {
length++;
temp >>=8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_SYMBOLS[value &0xf];
value >>=4;
}
require(value ==0, "Strings: hex length insufficient");
returnstring(buffer);
}
}
Contract Source Code
File 43 of 44: TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.8.0;/// @title Math library for computing sqrt prices from ticks and vice versa/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports/// prices between 2**-128 and 2**128libraryTickMath{
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128int24internalconstant MIN_TICK =-887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128int24internalconstant MAX_TICK =-MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)uint160internalconstant MIN_SQRT_RATIO =4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)uint160internalconstant MAX_SQRT_RATIO =1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96/// @dev Throws if |tick| > max tick/// @param tick The input tick for the above formula/// @return sqrtP A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)/// at the given tickfunctiongetSqrtRatioAtTick(int24 tick) internalpurereturns (uint160 sqrtP) {
unchecked {
uint256 absTick =uint256(tick <0 ? -int256(tick) : int256(tick));
require(absTick <=uint256(int256(MAX_TICK)), 'T');
// do bitwise comparison, if i-th bit is turned on,// multiply ratio by hardcoded values of sqrt(1.0001^-(2^i)) * 2^128// where 0 <= i <= 19uint256 ratio = (absTick &0x1!=0)
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick &0x2!=0) ratio = (ratio *0xfff97272373d413259a46990580e213a) >>128;
if (absTick &0x4!=0) ratio = (ratio *0xfff2e50f5f656932ef12357cf3c7fdcc) >>128;
if (absTick &0x8!=0) ratio = (ratio *0xffe5caca7e10e4e61c3624eaa0941cd0) >>128;
if (absTick &0x10!=0) ratio = (ratio *0xffcb9843d60f6159c9db58835c926644) >>128;
if (absTick &0x20!=0) ratio = (ratio *0xff973b41fa98c081472e6896dfb254c0) >>128;
if (absTick &0x40!=0) ratio = (ratio *0xff2ea16466c96a3843ec78b326b52861) >>128;
if (absTick &0x80!=0) ratio = (ratio *0xfe5dee046a99a2a811c461f1969c3053) >>128;
if (absTick &0x100!=0) ratio = (ratio *0xfcbe86c7900a88aedcffc83b479aa3a4) >>128;
if (absTick &0x200!=0) ratio = (ratio *0xf987a7253ac413176f2b074cf7815e54) >>128;
if (absTick &0x400!=0) ratio = (ratio *0xf3392b0822b70005940c7a398e4b70f3) >>128;
if (absTick &0x800!=0) ratio = (ratio *0xe7159475a2c29b7443b29c7fa6e889d9) >>128;
if (absTick &0x1000!=0) ratio = (ratio *0xd097f3bdfd2022b8845ad8f792aa5825) >>128;
if (absTick &0x2000!=0) ratio = (ratio *0xa9f746462d870fdf8a65dc1f90e061e5) >>128;
if (absTick &0x4000!=0) ratio = (ratio *0x70d869a156d2a1b890bb3df62baf32f7) >>128;
if (absTick &0x8000!=0) ratio = (ratio *0x31be135f97d08fd981231505542fcfa6) >>128;
if (absTick &0x10000!=0) ratio = (ratio *0x9aa508b5b7a84e1c677de54f3e99bc9) >>128;
if (absTick &0x20000!=0) ratio = (ratio *0x5d6af8dedb81196699c329225ee604) >>128;
if (absTick &0x40000!=0) ratio = (ratio *0x2216e584f5fa1ea926041bedfe98) >>128;
if (absTick &0x80000!=0) ratio = (ratio *0x48a170391f7dc42444e8fa2) >>128;
// take reciprocal for positive tick valuesif (tick >0) ratio =type(uint256).max/ ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.// we then downcast because we know the result always fits within 160 bits due to our tick input constraint// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtP =uint160((ratio >>32) + (ratio % (1<<32) ==0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio/// @dev Throws in case sqrtP < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may/// ever return./// @param sqrtP The sqrt ratio for which to compute the tick as a Q64.96/// @return tick The greatest tick for which the ratio is less than or equal to the input ratiofunctiongetTickAtSqrtRatio(uint160 sqrtP) internalpurereturns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tickrequire(sqrtP >= MIN_SQRT_RATIO && sqrtP < MAX_SQRT_RATIO, 'R');
uint256 ratio =uint256(sqrtP) <<32;
uint256 r = ratio;
uint256 msb =0;
unchecked {
assembly {
let f :=shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(5, gt(r, 0xFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(4, gt(r, 0xFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(3, gt(r, 0xFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(2, gt(r, 0xF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(1, gt(r, 0x3))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=gt(r, 0x1)
msb :=or(msb, f)
}
if (msb >=128) r = ratio >> (msb -127);
else r = ratio << (127- msb);
int256 log_2 = (int256(msb) -128) <<64;
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(63, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(62, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(61, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(60, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(59, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(58, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(57, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(56, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(55, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(54, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(53, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(52, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(51, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 *255738958999603826347141; // 128.128 numberint24 tickLow =int24((log_sqrt10001 -3402992956809132418596140100660247210) >>128);
int24 tickHi =int24((log_sqrt10001 +291339464771989622907027621153398088495) >>128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtP ? tickHi : tickLow;
}
}
functiongetMaxNumberTicks(int24 _tickDistance) internalpurereturns (uint24 numTicks) {
returnuint24(TickMath.MAX_TICK / _tickDistance) *2;
}
}
Contract Source Code
File 44 of 44: TokenHelper.sol
// SPDX-License-Identifier: agpl-3.0pragmasolidity 0.8.9;import'@openzeppelin/contracts/token/ERC20/IERC20.sol';
import'@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
/// @title Helper to transfer token or ETHlibraryTokenHelper{
usingSafeERC20forIERC20;
/// @dev Transfer token from the sender to the receiver/// @notice If the sender is the contract address, should just call transfer token to receiver/// otherwise, tansfer tokens from the sender to the receiverfunctiontransferToken(
IERC20 token,
uint256 amount,
address sender,
address receiver
) internal{
if (sender ==address(this)) {
token.safeTransfer(receiver, amount);
} else {
token.safeTransferFrom(sender, receiver, amount);
}
}
/// @dev Transfer ETh to the receiverfunctiontransferEth(address receiver, uint256 amount) internal{
if (receiver ==address(this)) return;
(bool success, ) =payable(receiver).call{value: amount}('');
require(success, 'transfer eth failed');
}
}