// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
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
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)
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.openzeppelin.com/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:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, 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) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_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;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_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 Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - 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: AGPL-3.0
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint8 internal constant RESOLUTION = 128;
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;
/// @title FixedPoint192
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint192 {
uint8 internal constant RESOLUTION = 192;
uint256 internal constant Q192 =
0x1000000000000000000000000000000000000000000000000;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;
/// @title FixedPoint64
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint64 {
uint8 internal constant RESOLUTION = 64;
uint256 internal constant Q64 = 0x10000000000000000;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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);
/**
* @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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
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: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 adjust callback
/// @notice Callbacks called by Marginal v1 pools when adjusting the margin backing a position
/// @dev Any contract that calls IMarginalV1Pool#adjust must implement this interface
interface IMarginalV1AdjustCallback {
/// @notice Called to `msg.sender` after adjusting the margin backing a position via IMarginalV1Pool#adjust
/// @dev In the implementation you must pay the pool tokens owed to adjust the margin backing a position. The tokens owed
/// is the new position margin, as the original margin is flashed out to `recipient` in the IMarginalV1Pool#adjust call.
/// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
/// @param amount0Owed The amount of token0 that must be payed to pool to successfully adjust the margin backing a position
/// @param amount1Owed The amount of token1 that must be payed to pool to successfully adjust the margin backing a position
/// @param data Any data passed through by the caller via the IMarginalV1Pool#adjust call
function marginalV1AdjustCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 factory
/// @notice The Marginal v1 factory creates pools and enables leverage tiers
interface IMarginalV1Factory {
/// @notice Returns the Marginal v1 pool deployer to use when creating pools
/// @return The address of the Marginal v1 pool deployer
function marginalV1Deployer() external view returns (address);
/// @notice Returns the Uniswap v3 factory to reference for pool oracles
/// @return The address of the Uniswap v3 factory
function uniswapV3Factory() external view returns (address);
/// @notice Returns the minimum observation cardinality the Uniswap v3 oracle must have
/// @dev Used as a check that averaging over `secondsAgo` in the Marginal v1 pool is likely to succeed
/// @return The minimum observation cardinality the Uniswap v3 oracle must have
function observationCardinalityMinimum() external view returns (uint16);
/// @notice Returns the current owner of the Marginal v1 factory contract
/// @dev Changed via permissioned `setOwner` function on the factory
/// @return The address of the current owner of the Marginal v1 factory
function owner() external view returns (address);
/// @notice Returns the pool address for the given unique Marginal v1 pool key
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The address of either token0/token1
/// @param tokenB The address of the other token token1/token0
/// @param maintenance The minimum maintenance requirement for the pool
/// @param oracle The address of the Uniswap v3 oracle used by the pool
/// @return The address of the Marginal v1 pool
function getPool(
address tokenA,
address tokenB,
uint24 maintenance,
address oracle
) external view returns (address);
/// @notice Returns whether given address is a Marginal v1 pool deployed by the factory
/// @return Whether address is a pool
function isPool(address pool) external view returns (bool);
/// @notice Returns the maximum leverage associated with the pool maintenance if pool exists
/// @param maintenance The minimum maintenance margin requirement for the pool
/// @return The maximum leverage for the pool maintenance if pool exists
function getLeverage(uint24 maintenance) external view returns (uint256);
/// @notice Creates a new Marginal v1 pool for the given unique pool key
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The address of either token0/token1
/// @param tokenB The address of the other token token1/token0
/// @param maintenance The minimum maintenance requirement for the pool
/// @param uniswapV3Fee The fee tier of the Uniswap v3 oracle used by the Marginal v1 pool
/// @return pool The address of the created Marginal v1 pool
function createPool(
address tokenA,
address tokenB,
uint24 maintenance,
uint24 uniswapV3Fee
) external returns (address pool);
/// @notice Sets the owner of the Marginal v1 factory contract
/// @dev Can only be called by the current factory owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a new leverage tier for Marginal v1 pool deployments
/// @dev Can only be called by the current factory owner
/// @dev Set leverage tier obeys: l = 1 + 1/M; M = maintenance
/// @param maintenance The minimum maintenance requirement associated with the leverage tier
function enableLeverage(uint24 maintenance) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 mint callback
/// @notice Callbacks called by Marginal v1 pools when adding liquidity
/// @dev Any contract that calls IMarginalV1Pool#mint must implement this interface
interface IMarginalV1MintCallback {
/// @notice Called to `msg.sender` after adding liquidity via IMarginalV1Pool#mint
/// @dev In the implementation you must pay the pool tokens owed to add liquidity to the pool and mint LP tokens.
/// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
/// @param amount0Owed The amount of token0 that must be payed to pool to successfully mint LP tokens
/// @param amount1Owed The amount of token1 that must be payed to pool to successfully mint LP tokens
/// @param data Any data passed through by the caller via the IMarginalV1Pool#mint call
function marginalV1MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 open callback
/// @notice Callbacks called by Marginal v1 pools when opening a position
/// @dev Any contract that calls IMarginalV1Pool#open must implement this interface
interface IMarginalV1OpenCallback {
/// @notice Called to `msg.sender` after opening a position via IMarginalV1Pool#open
/// @dev In the implementation you must pay the pool tokens owed to open a position.
/// The pool tokens owed are the margin and fees required to open the position.
/// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
/// @param amount0Owed The amount of token0 that must be payed to pool to successfully open a position
/// @param amount1Owed The amount of token1 that must be payed to pool to successfully open a position
/// @param data Any data passed through by the caller via the IMarginalV1Pool#open call
function marginalV1OpenCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title The interface for a Marginal v1 pool
/// @notice A Marginal v1 pool facilitates leverage trading, swapping, and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev Inherits from IERC20 as liquidity providers are minted fungible pool tokens
interface IMarginalV1Pool is IERC20 {
/// @notice The Marginal v1 factory that created the pool
/// @return The address of the Marginal v1 factory
function factory() external view returns (address);
/// @notice The Uniswap v3 oracle referenced by the pool for funding and position safety
/// @return The address of the Uniswap v3 oracle referenced by the pool
function oracle() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The address of the token0 contract
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The address of the token1 contract
function token1() external view returns (address);
/// @notice The minimum maintenance requirement for leverage positions on the pool
/// @return The minimum maintenance requirement
function maintenance() external view returns (uint24);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The premium multiplier on liquidation rewards in hundredths of a bip, i.e. 1e-6
/// @dev Liquidation rewards set aside in native (gas) token.
/// Premium acts as an incentive above the expected gas cost to call IMarginalV1Pool#liquidate.
/// @return The premium multiplier
function rewardPremium() external view returns (uint24);
/// @notice The maximum rate of change in tick cumulative between the Marginal v1 pool and the Uniswap v3 oracle
/// @dev Puts a ceiling on funding paid per second
/// @return The maximum tick cumulative rate per second
function tickCumulativeRateMax() external view returns (uint24);
/// @notice The amount of time in seconds to average the Uniswap v3 oracle TWAP over to assess position safety
/// @return The averaging time for the Uniswap v3 oracle TWAP in seconds
function secondsAgo() external view returns (uint32);
/// @notice The period in seconds to benchmark funding payments with respect to
/// @dev Acts as an averaging period on tick cumulative changes between the Marginal v1 pool and the Uniswap v3 oracle
/// @return The funding period in seconds
function fundingPeriod() external view returns (uint32);
/// @notice The pool state represented in (L, sqrt(P)) space
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// totalPositions The total number of leverage positions that have ever been taken out on the pool
/// liquidity The currently available liquidity offered by the pool for swaps and leverage positions
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// blockTimestamp The last `block.timestamp` at which state was synced
/// tickCumulative The tick cumulative running sum of the pool, used in funding calculations
/// feeProtocol The protocol fee for both tokens of the pool
/// initialized Whether the pool has been initialized
function state()
external
view
returns (
uint160 sqrtPriceX96,
uint96 totalPositions,
uint128 liquidity,
int24 tick,
uint32 blockTimestamp,
int56 tickCumulative,
uint8 feeProtocol,
bool initialized
);
/// @notice The liquidity used to capitalize outstanding leverage positions
/// @return The liquidity locked for outstanding leverage positions
function liquidityLocked() external view returns (uint128);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
/// @return protocolFees0 The amount of token0 owed to the protocol
/// @return protocolFees1 The amount of token1 owed to the protocol
function protocolFees()
external
view
returns (uint128 protocolFees0, uint128 protocolFees1);
/// @notice Returns information about a leverage position by the position's key
/// @dev Either debt0 (zeroForOne = true) or debt1 (zeroForOne = false) will be updated each funding sync
/// @param key The position's key is a hash of the packed encoding of the owner and the position ID
/// @return size The position size in the token the owner is long
/// debt0 The position debt in token0 owed to the pool at settlement. If long token1 (zeroForOne = true), this is the debt to be repaid at settlement by owner. Otherwise, simply used for internal accounting
/// debt1 The position debt in token1 owed to the pool at settlement. If long token0 (zeroForOne = false), this is the debt to be repaid at settlement by owner. Otherwise, simply used for internal accounting
/// insurance0 The insurance in token0 set aside to backstop the position in case of late liquidations
/// insurance1 The insurance in token1 set aside to backstop the position in case of late liquidations
/// zeroForOne Whether the position is long token1 and short token0 (true) or long token0 and short token1 (false)
/// liquidated Whether the position has been liquidated
/// tick The pool tick prior to opening the position
/// blockTimestamp The `block.timestamp` at which the position was last synced for funding
/// tickCumulativeDelta The difference in the Uniswap v3 oracle tick cumulative and the Marginal v1 pool tick cumulative at the last funding sync
/// margin The position margin in the token the owner is long
/// liquidityLocked The liquidity locked by the pool to collateralize the position
/// rewards The liquidation rewards in the native (gas) token received by liquidator if position becomes unsafe
function positions(
bytes32 key
)
external
view
returns (
uint128 size,
uint128 debt0,
uint128 debt1,
uint128 insurance0,
uint128 insurance1,
bool zeroForOne,
bool liquidated,
int24 tick,
uint32 blockTimestamp,
int56 tickCumulativeDelta,
uint128 margin,
uint128 liquidityLocked,
uint256 rewards
);
/// @notice Opens a leverage position on the pool
/// @dev The caller of this method receives a callback in the form of IMarginalV1OpenCallback#marginalV1OpenCallback.
/// The caller must forward liquidation rewards in the native (gas) token to be escrowed by the pool contract
/// Rewards determined by current `block.basefee` * estimated gas cost to call IMarginalV1Pool#liquidate * rewardPremium
/// @param recipient The address of the owner of the opened position
/// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
/// @param liquidityDelta The amount of liquidity for the pool to lock to capitalize the position
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after opening the position otherwise the call reverts. If one for zero, the price cannot be greater than this value after opening
/// @param margin The amount of margin used to back the position in the token the position is long
/// @param data Any data to be passed through to the callback
/// @return id The ID of the opened position
/// @return size The size of the opened position in the token the position is long. Excludes margin amount provided by caller
/// @return debt The debt of the opened position in the token the position is short
/// @return amount0 The amount of token0 caller must send to pool to open the position
/// @return amount1 The amount of token1 caller must send to pool to open the position
function open(
address recipient,
bool zeroForOne,
uint128 liquidityDelta,
uint160 sqrtPriceLimitX96,
uint128 margin,
bytes calldata data
)
external
payable
returns (
uint256 id,
uint256 size,
uint256 debt,
uint256 amount0,
uint256 amount1
);
/// @notice Adjusts the margin used to back a position on the pool
/// @dev The caller of this method receives a callback in the form of IMarginalV1AdjustCallback#marginalV1AdjustCallback
/// Old position margin is flashed out to recipient prior to the callback
/// @param recipient The address to receive the old position margin
/// @param id The ID of the position to adjust
/// @param marginDelta The delta of the margin backing the position on the pool. Adding margin to the position when positive, removing margin when negative
/// @param data Any data to be passed through to the callback
/// @return margin0 The amount of token0 to be used as the new margin backing the position
/// @return margin1 The amount of token1 to be used as the new margin backing the position
function adjust(
address recipient,
uint96 id,
int128 marginDelta,
bytes calldata data
) external returns (uint256 margin0, uint256 margin1);
/// @notice Settles a position on the pool
/// @dev The caller of this method receives a callback in the form of IMarginalV1SettleCallback#marginalV1SettleCallback.
/// If a contract, `recipient` must implement a `receive()` function to receive the escrowed liquidation rewards in the native (gas) token from the pool.
/// Position size, margin, and liquidation rewards are flashed out before the callback to allow the caller to swap to repay the debt to the pool
/// @param recipient The address to receive the size, margin, and liquidation rewards of the settled position
/// @param id The ID of the position to settle
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool. Position debt into the pool (> 0) if long token1 (zeroForOne = true), or position size and margin out of the pool (< 0) if long token0 (zeroForOne = false)
/// @return amount1 The delta of the balance of token1 of the pool. Position size and margin out of the pool (< 0) if long token1 (zeroForOne = true), or position debt into the pool (> 0) if long token0 (zeroForOne = false)
/// @return rewards The amount of escrowed native (gas) token sent to `recipient`
function settle(
address recipient,
uint96 id,
bytes calldata data
) external returns (int256 amount0, int256 amount1, uint256 rewards);
/// @notice Liquidates a position on the pool
/// @dev Reverts if position is safe from liquidation. Position is considered safe if
/// (`position.margin` + `position.size`) / oracleTwap >= (1 + `maintenance`) * `position.debt0` when position.zeroForOne = true
/// (`position.margin` + `position.size`) * oracleTwap >= (1 + `maintenance`) * `position.debt1` when position.zeroForOne = false
/// Safety checks are performed after syncing the position debts for funding payments
/// If a contract, `recipient` must implement a `receive()` function to receive the escrowed liquidation rewards in the native (gas) token from the pool.
/// @param recipient The address to receive liquidation rewards escrowed with the position
/// @param owner The address of the owner of the position to liquidate
/// @param id The ID of the position to liquidate
/// @return rewards The amount of escrowed native (gas) token sent to `recipient`
function liquidate(
address recipient,
address owner,
uint96 id
) external returns (uint256 rewards);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IMarginalV1SwapCallback#marginalV1SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap otherwise the call reverts. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Adds liquidity to the pool
/// @dev The caller of this method receives a callback in the form of IMarginalV1MintCallback#marginalV1MintCallback.
/// The pool is initialized through the first call to mint
/// @param recipient The address to mint LP tokens to after adding liquidity to the pool
/// @param liquidityDelta The liquidity added to the pool
/// @param data Any data to be passed through to the callback
/// @return shares The amount of LP token shares minted to recipient
/// @return amount0 The amount of token0 added to the pool reserves
/// @return amount1 The amount of token1 added to the pool reserves
function mint(
address recipient,
uint128 liquidityDelta,
bytes calldata data
) external returns (uint256 shares, uint256 amount0, uint256 amount1);
/// @notice Removes liquidity from the pool
/// @dev Reverts if not enough liquidity available to exit due to outstanding leverage positions
/// @param recipient The address to send token amounts to after removing liquidity from the pool
/// @param shares The amount of LP token shares to burn
/// @return liquidityDelta The liquidity removed from the pool
/// @return amount0 The amount of token0 removed from pool reserves
/// @return amount1 The amount of token1 removed from pool reserves
function burn(
address recipient,
uint256 shares
)
external
returns (uint128 liquidityDelta, uint256 amount0, uint256 amount1);
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol new protocol fee denominator for the pool
function setFeeProtocol(uint8 feeProtocol) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 settle callback
/// @notice Callbacks called by Marginal v1 pools when settling the debt owed by a position to the pool
/// @dev Any contract that calls IMarginalV1Pool#settle must implement this interface
interface IMarginalV1SettleCallback {
/// @notice Called to `msg.sender` after settling a position via IMarginalV1Pool#settle
/// @dev In the implementation you must pay the pool tokens owed to settle the debt owed by a position to the pool.
/// Position size and margin are flashed out to `recipient` in the IMarginalV1Pool#settle call prior to enable debt repayment via swaps.
/// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
/// Amount that must be payed to pool is > 0 as IMarginalV1Pool#open would have reverted otherwise.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of position settlement. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of position settlement. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IMarginalV1Pool#settle call
function marginalV1SettleCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.5.0;
/// @title The interface for the Marginal v1 swap callback
/// @notice Callbacks called by Marginal v1 pools when executing a swap
/// @dev Any contract that calls IMarginalV1Pool#swap must implement this interface
interface IMarginalV1SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IMarginalV1Pool#swap
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a MarginalV1Pool deployed by the canonical MarginalV1Factory.
/// Amount that must be payed to pool is > 0 as IMarginalV1Pool#swap reverts otherwise.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IMarginalV1Pool#swap call
function marginalV1SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IUniswapV3PoolImmutables} from './pool/IUniswapV3PoolImmutables.sol';
import {IUniswapV3PoolState} from './pool/IUniswapV3PoolState.sol';
import {IUniswapV3PoolDerivedState} from './pool/IUniswapV3PoolDerivedState.sol';
import {IUniswapV3PoolActions} from './pool/IUniswapV3PoolActions.sol';
import {IUniswapV3PoolOwnerActions} from './pool/IUniswapV3PoolOwnerActions.sol';
import {IUniswapV3PoolErrors} from './pool/IUniswapV3PoolErrors.sol';
import {IUniswapV3PoolEvents} from './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolErrors,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @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 IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity 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 observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Errors emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolErrors {
error LOK();
error TLU();
error TLM();
error TUM();
error AI();
error M0();
error M1();
error AS();
error IIA();
error L();
error F0();
error F1();
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool 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 observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// 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 maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// @return observationIndex The index of the last oracle observation that was written,
/// @return observationCardinality The current maximum number of observations stored in the pool,
/// @return observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// @return feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
/// @return The liquidity at the current price of the pool
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper
/// @return liquidityNet how much liquidity changes when the pool price crosses the tick,
/// @return feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// @return feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// @return tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// @return secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// @return secondsOutside the seconds spent on the other side of the tick from the current tick,
/// @return initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return liquidity The amount of liquidity in the position,
/// @return feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// @return feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// @return tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// @return tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @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,
/// @return tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// @return secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// @return initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {SqrtPriceMath} from "./SqrtPriceMath.sol";
/// @title Math library for liquidity
/// @notice Facilitates transformations between (L, sqrtP) space and (x, y) token reserves
library LiquidityMath {
using SafeCast for uint256;
/// @notice Transforms (L, sqrtP) values into (x, y) reserve amounts
/// @param liquidity Pool liquidity in (L, sqrtP) space
/// @param sqrtPriceX96 Pool price in (L, sqrtP) space
/// @return amount0 The amount of token0 associated with the given (L, sqrtP) values
/// @return amount1 The amount of token1 associated with the given (L, sqrtP) values
function toAmounts(
uint128 liquidity,
uint160 sqrtPriceX96
) internal pure returns (uint256 amount0, uint256 amount1) {
// x = L / sqrt(P); y = L * sqrt(P)
amount0 =
(uint256(liquidity) << FixedPoint96.RESOLUTION) /
sqrtPriceX96;
amount1 = Math.mulDiv(liquidity, sqrtPriceX96, FixedPoint96.Q96);
}
/// @notice Transforms (x, y) reserve amounts into (L, sqrtP) values
/// @dev Reverts on overflow if reserve0 * reserve1 > type(uint256).max as liquidity must fit into uint128
/// @param reserve0 The amount of token0 in reserves
/// @param reserve1 The amount of token1 in reserves
/// @return liquidity Pool liquidity associated with reserve amounts
/// @return sqrtPriceX96 Pool price associated with reserve amounts
function toLiquiditySqrtPriceX96(
uint256 reserve0,
uint256 reserve1
) internal pure returns (uint128 liquidity, uint160 sqrtPriceX96) {
// L = sqrt(x * y); sqrt(P) = sqrt(y / x)
liquidity = Math.sqrt(reserve0 * reserve1).toUint128();
uint256 _sqrtPriceX96 = (uint256(liquidity) <<
FixedPoint96.RESOLUTION) / reserve0;
if (
!(_sqrtPriceX96 >= SqrtPriceMath.MIN_SQRT_RATIO &&
_sqrtPriceX96 < SqrtPriceMath.MAX_SQRT_RATIO)
) revert SqrtPriceMath.InvalidSqrtPriceX96();
sqrtPriceX96 = uint160(_sqrtPriceX96);
}
/// @notice Calculates (L, sqrtP) after adding/removing amounts to/from pool reserves
/// @param liquidity Pool liquidity before adding/removing reserves
/// @param sqrtPriceX96 Pool price before adding/removing reserves
/// @param amount0 The amount of token0 to add (positive) or remove (negative)
/// @param amount1 The amount of token1 to add (positive) or remove (negative)
/// @return liquidityNext Pool liquidity after adding/removing reserves
/// @return sqrtPriceX96Next Pool price after adding/removing reserves
function liquiditySqrtPriceX96Next(
uint128 liquidity,
uint160 sqrtPriceX96,
int256 amount0,
int256 amount1
) internal pure returns (uint128 liquidityNext, uint160 sqrtPriceX96Next) {
(uint256 reserve0, uint256 reserve1) = toAmounts(
liquidity,
sqrtPriceX96
);
if (amount0 < 0 && uint256(-amount0) >= reserve0)
revert SqrtPriceMath.Amount0ExceedsReserve0();
if (amount1 < 0 && uint256(-amount1) >= reserve1)
revert SqrtPriceMath.Amount1ExceedsReserve1();
uint256 reserve0Next = amount0 >= 0
? reserve0 + uint256(amount0)
: reserve0 - uint256(-amount0);
uint256 reserve1Next = amount1 >= 0
? reserve1 + uint256(amount1)
: reserve1 - uint256(-amount1);
(liquidityNext, sqrtPriceX96Next) = toLiquiditySqrtPriceX96(
reserve0Next,
reserve1Next
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.17;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {LiquidityMath} from "./libraries/LiquidityMath.sol";
import {OracleLibrary} from "./libraries/OracleLibrary.sol";
import {Position} from "./libraries/Position.sol";
import {SqrtPriceMath} from "./libraries/SqrtPriceMath.sol";
import {SwapMath} from "./libraries/SwapMath.sol";
import {TransferHelper} from "./libraries/TransferHelper.sol";
import {IMarginalV1AdjustCallback} from "./interfaces/callback/IMarginalV1AdjustCallback.sol";
import {IMarginalV1MintCallback} from "./interfaces/callback/IMarginalV1MintCallback.sol";
import {IMarginalV1OpenCallback} from "./interfaces/callback/IMarginalV1OpenCallback.sol";
import {IMarginalV1SettleCallback} from "./interfaces/callback/IMarginalV1SettleCallback.sol";
import {IMarginalV1SwapCallback} from "./interfaces/callback/IMarginalV1SwapCallback.sol";
import {IMarginalV1Factory} from "./interfaces/IMarginalV1Factory.sol";
import {IMarginalV1Pool} from "./interfaces/IMarginalV1Pool.sol";
contract MarginalV1Pool is IMarginalV1Pool, ERC20 {
using Position for mapping(bytes32 => Position.Info);
using Position for Position.Info;
using SafeCast for uint256;
/// @inheritdoc IMarginalV1Pool
address public immutable factory;
/// @inheritdoc IMarginalV1Pool
address public immutable oracle;
/// @inheritdoc IMarginalV1Pool
address public immutable token0;
/// @inheritdoc IMarginalV1Pool
address public immutable token1;
/// @inheritdoc IMarginalV1Pool
uint24 public immutable maintenance;
/// @inheritdoc IMarginalV1Pool
uint24 public constant fee = 1000; // 10 bps across all pools
/// @inheritdoc IMarginalV1Pool
uint24 public constant rewardPremium = 2000000; // 2x base fee as liquidation rewards
/// @inheritdoc IMarginalV1Pool
uint24 public constant tickCumulativeRateMax = 920; // bound on funding rate of ~10% per funding period
/// @inheritdoc IMarginalV1Pool
uint32 public constant secondsAgo = 43200; // 12 hr TWAP for oracle price
/// @inheritdoc IMarginalV1Pool
uint32 public constant fundingPeriod = 604800; // 7 day funding period
// @dev varies for different chains
uint256 internal constant blockBaseFeeMin = 40e9; // min base fee for liquidation rewards
uint256 internal constant gasLiquidate = 150000; // gas required to call liquidate
uint128 internal constant MINIMUM_LIQUIDITY = 10000; // liquidity locked on initial mint always available for swaps
uint128 internal constant MINIMUM_SIZE = 10000; // minimum position size, debt, insurance amounts to prevent dust sizes
struct State {
uint160 sqrtPriceX96;
uint96 totalPositions; // > ~ 2e20 years at max per block to fill on mainnet
uint128 liquidity;
int24 tick;
uint32 blockTimestamp;
int56 tickCumulative;
uint8 feeProtocol;
bool initialized;
}
/// @inheritdoc IMarginalV1Pool
State public state;
/// @inheritdoc IMarginalV1Pool
uint128 public liquidityLocked;
struct ProtocolFees {
uint128 token0;
uint128 token1;
}
/// @inheritdoc IMarginalV1Pool
ProtocolFees public protocolFees;
/// @inheritdoc IMarginalV1Pool
mapping(bytes32 => Position.Info) public positions;
uint256 private unlocked = 2; // uses OZ convention of 1 for false and 2 for true
modifier lock() {
if (unlocked == 1) revert Locked();
unlocked = 1;
_;
unlocked = 2;
}
modifier onlyFactoryOwner() {
if (msg.sender != IMarginalV1Factory(factory).owner())
revert Unauthorized();
_;
}
event Initialize(uint160 sqrtPriceX96, int24 tick);
event Open(
address sender,
address indexed owner,
uint256 indexed id,
uint128 liquidityAfter,
uint160 sqrtPriceX96After,
uint128 margin
);
event Adjust(
address indexed owner,
uint256 indexed id,
address recipient,
uint256 marginAfter
);
event Settle(
address indexed owner,
uint256 indexed id,
address recipient,
uint128 liquidityAfter,
uint160 sqrtPriceX96After,
int256 amount0,
int256 amount1,
uint256 rewards
);
event Liquidate(
address indexed owner,
uint256 indexed id,
address recipient,
uint128 liquidityAfter,
uint160 sqrtPriceX96After,
uint256 rewards
);
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
event Mint(
address sender,
address indexed owner,
uint128 liquidityDelta,
uint256 amount0,
uint256 amount1
);
event Burn(
address indexed owner,
address recipient,
uint128 liquidityDelta,
uint256 amount0,
uint256 amount1
);
event SetFeeProtocol(uint8 oldFeeProtocol, uint8 newFeeProtocol);
event CollectProtocol(
address sender,
address indexed recipient,
uint128 amount0,
uint128 amount1
);
error Locked();
error Unauthorized();
error InvalidLiquidityDelta();
error InvalidSqrtPriceLimitX96();
error SqrtPriceX96ExceedsLimit();
error MarginLessThanMin();
error RewardsLessThanMin();
error Amount0LessThanMin();
error Amount1LessThanMin();
error InvalidPosition();
error PositionSafe();
error InvalidAmountSpecified();
error InvalidFeeProtocol();
constructor(
address _factory,
address _token0,
address _token1,
uint24 _maintenance,
address _oracle
) ERC20("Marginal V1 LP Token", "MARGV1-LP") {
factory = _factory;
token0 = _token0;
token1 = _token1;
maintenance = _maintenance;
oracle = _oracle;
}
function initialize() private {
// reverts if not enough historical observations
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
int56[] memory oracleTickCumulativesLast = oracleTickCumulatives(
secondsAgos
);
// use oracle price to initialize
uint160 _sqrtPriceX96 = OracleLibrary.oracleSqrtPriceX96(
OracleLibrary.oracleTickCumulativeDelta(
oracleTickCumulativesLast[0],
oracleTickCumulativesLast[1]
),
secondsAgo
);
int24 tick = TickMath.getTickAtSqrtRatio(_sqrtPriceX96);
state = State({
sqrtPriceX96: _sqrtPriceX96,
totalPositions: 0,
liquidity: 0,
tick: tick,
blockTimestamp: _blockTimestamp(),
tickCumulative: 0,
feeProtocol: 0,
initialized: true
});
emit Initialize(_sqrtPriceX96, tick);
}
function _blockTimestamp() internal view virtual returns (uint32) {
return uint32(block.timestamp);
}
function balance0() private view returns (uint256) {
return IERC20(token0).balanceOf(address(this));
}
function balance1() private view returns (uint256) {
return IERC20(token1).balanceOf(address(this));
}
function oracleTickCumulatives(
uint32[] memory secondsAgos
) private view returns (int56[] memory) {
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(oracle).observe(
secondsAgos
);
return tickCumulatives;
}
function stateSynced() private view returns (State memory) {
State memory _state = state;
// oracle update
unchecked {
uint32 delta = _blockTimestamp() - _state.blockTimestamp;
if (delta == 0) return _state; // early exit if nothing to update
_state.tickCumulative += int56(_state.tick) * int56(uint56(delta)); // overflow desired
_state.blockTimestamp = _blockTimestamp();
}
return _state;
}
/// @inheritdoc IMarginalV1Pool
function open(
address recipient,
bool zeroForOne,
uint128 liquidityDelta,
uint160 sqrtPriceLimitX96,
uint128 margin,
bytes calldata data
)
external
payable
lock
returns (
uint256 id,
uint256 size,
uint256 debt,
uint256 amount0,
uint256 amount1
)
{
State memory _state = stateSynced();
if (
liquidityDelta == 0 ||
liquidityDelta + MINIMUM_LIQUIDITY >= _state.liquidity
) revert InvalidLiquidityDelta();
if (
zeroForOne
? !(sqrtPriceLimitX96 < _state.sqrtPriceX96 &&
sqrtPriceLimitX96 > SqrtPriceMath.MIN_SQRT_RATIO)
: !(sqrtPriceLimitX96 > _state.sqrtPriceX96 &&
sqrtPriceLimitX96 < SqrtPriceMath.MAX_SQRT_RATIO)
) revert InvalidSqrtPriceLimitX96();
uint160 sqrtPriceX96Next = SqrtPriceMath.sqrtPriceX96NextOpen(
_state.liquidity,
_state.sqrtPriceX96,
liquidityDelta,
zeroForOne,
maintenance
);
if (
zeroForOne
? sqrtPriceX96Next < sqrtPriceLimitX96
: sqrtPriceX96Next > sqrtPriceLimitX96
) revert SqrtPriceX96ExceedsLimit();
// zero seconds ago for oracle tickCumulative
int56 oracleTickCumulative = oracleTickCumulatives(new uint32[](1))[0];
Position.Info memory position = Position.assemble(
_state.liquidity,
_state.sqrtPriceX96,
sqrtPriceX96Next,
liquidityDelta,
zeroForOne,
_state.tick,
_state.blockTimestamp,
_state.tickCumulative,
oracleTickCumulative
);
if (
position.size < MINIMUM_SIZE ||
position.debt0 < MINIMUM_SIZE ||
position.debt1 < MINIMUM_SIZE ||
position.insurance0 < MINIMUM_SIZE ||
position.insurance1 < MINIMUM_SIZE
) revert InvalidPosition();
uint128 marginMinimum = position.marginMinimum(maintenance);
if (marginMinimum == 0 || margin < marginMinimum)
revert MarginLessThanMin();
position.margin = margin;
uint256 rewardsMinimum = Position.liquidationRewards(
block.basefee,
blockBaseFeeMin,
gasLiquidate,
rewardPremium
);
if (msg.value < rewardsMinimum) revert RewardsLessThanMin();
position.rewards = msg.value;
_state.liquidity -= liquidityDelta;
_state.sqrtPriceX96 = sqrtPriceX96Next;
liquidityLocked += liquidityDelta;
// callback for margin amount
if (!zeroForOne) {
// long token0 (out) relative to token1 (in); margin in token0
uint256 fees0 = Position.fees(position.size, fee);
amount0 = uint256(margin) + fees0;
uint256 balance0Before = balance0();
IMarginalV1OpenCallback(msg.sender).marginalV1OpenCallback(
amount0,
0,
data
);
if (balance0Before + amount0 > balance0())
revert Amount0LessThanMin();
// account for protocol fees if fee on
if (_state.feeProtocol > 0) {
uint256 delta = fees0 / _state.feeProtocol;
fees0 -= delta;
protocolFees.token0 += uint128(delta);
}
// fees added to available liquidity
(uint128 liquidityAfter, uint160 sqrtPriceX96After) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
int256(fees0),
0
);
_state.liquidity = liquidityAfter;
_state.sqrtPriceX96 = sqrtPriceX96After;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96After);
} else {
// long token1 (out) relative to token0 (in); margin in token1
uint256 fees1 = Position.fees(position.size, fee);
amount1 = uint256(margin) + fees1;
uint256 balance1Before = balance1();
IMarginalV1OpenCallback(msg.sender).marginalV1OpenCallback(
0,
amount1,
data
);
if (balance1Before + amount1 > balance1())
revert Amount1LessThanMin();
// account for protocol fees if fee on
if (_state.feeProtocol > 0) {
uint256 delta = fees1 / _state.feeProtocol;
fees1 -= delta;
protocolFees.token1 += uint128(delta);
}
// fees added to available liquidity
(uint128 liquidityAfter, uint160 sqrtPriceX96After) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
0,
int256(fees1)
);
_state.liquidity = liquidityAfter;
_state.sqrtPriceX96 = sqrtPriceX96After;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96After);
}
id = _state.totalPositions;
size = position.size;
debt = zeroForOne ? position.debt0 : position.debt1;
positions.set(recipient, _state.totalPositions, position);
_state.totalPositions++;
// update pool state to latest
state = _state;
emit Open(
msg.sender,
recipient,
id,
_state.liquidity,
_state.sqrtPriceX96,
margin
);
}
/// @inheritdoc IMarginalV1Pool
function adjust(
address recipient,
uint96 id,
int128 marginDelta,
bytes calldata data
) external lock returns (uint256 margin0, uint256 margin1) {
State memory _state = stateSynced();
Position.Info memory position = positions.get(msg.sender, id);
if (position.size == 0) revert InvalidPosition();
// don't update position stored debts for funding to avoid short circuiting and min margin zero issues
uint128 marginMinimum = position.marginMinimum(maintenance);
if (
int256(uint256(position.margin)) + int256(marginDelta) <
int256(uint256(marginMinimum))
) revert MarginLessThanMin();
// flash margin out then callback for margin in
if (!position.zeroForOne) {
margin0 = uint256(
int256(uint256(position.margin)) + int256(marginDelta)
); // position margin after
TransferHelper.safeTransfer(token0, recipient, position.margin);
uint256 balance0Before = balance0();
IMarginalV1AdjustCallback(msg.sender).marginalV1AdjustCallback(
margin0,
0,
data
);
if (balance0Before + margin0 > balance0())
revert Amount0LessThanMin();
position.margin = margin0.toUint128();
} else {
margin1 = uint256(
int256(uint256(position.margin)) + int256(marginDelta)
); // position margin after
TransferHelper.safeTransfer(token1, recipient, position.margin);
uint256 balance1Before = balance1();
IMarginalV1AdjustCallback(msg.sender).marginalV1AdjustCallback(
0,
margin1,
data
);
if (balance1Before + margin1 > balance1())
revert Amount1LessThanMin();
position.margin = margin1.toUint128();
}
positions.set(msg.sender, id, position);
// update pool state to latest
state = _state;
emit Adjust(msg.sender, uint256(id), recipient, position.margin);
}
/// @inheritdoc IMarginalV1Pool
function settle(
address recipient,
uint96 id,
bytes calldata data
) external lock returns (int256 amount0, int256 amount1, uint256 rewards) {
State memory _state = stateSynced();
Position.Info memory position = positions.get(msg.sender, id);
if (position.size == 0) revert InvalidPosition();
// zero seconds ago for oracle tickCumulative
int56 oracleTickCumulative = oracleTickCumulatives(new uint32[](1))[0];
// update debts for funding
position = position.sync(
_state.blockTimestamp,
_state.tickCumulative,
oracleTickCumulative,
tickCumulativeRateMax,
fundingPeriod
);
liquidityLocked -= position.liquidityLocked;
(uint256 amount0Unlocked, uint256 amount1Unlocked) = position
.amountsLocked();
// flash size + margin + rewards out then callback for debt owed in
rewards = position.rewards;
TransferHelper.safeTransferETH(recipient, rewards); // ok given lock
if (!position.zeroForOne) {
amount0 = -int256(
uint256(position.size) + uint256(position.margin)
); // size + margin out
amount1 = int256(uint256(position.debt1)); // debt in
if (amount0 < 0)
TransferHelper.safeTransfer(
token0,
recipient,
uint256(-amount0)
);
(uint128 liquidityNext, uint160 sqrtPriceX96Next) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
int256(
amount0Unlocked -
uint256(position.size) -
uint256(position.margin)
), // insurance0 + debt0
int256(amount1Unlocked) + amount1 // insurance1 + debt1
);
_state.liquidity = liquidityNext;
_state.sqrtPriceX96 = sqrtPriceX96Next;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96Next);
uint256 balance1Before = balance1();
IMarginalV1SettleCallback(msg.sender).marginalV1SettleCallback(
amount0,
amount1,
data
);
if (balance1Before + uint256(amount1) > balance1())
revert Amount1LessThanMin();
} else {
amount0 = int256(uint256(position.debt0)); // debt in
amount1 = -int256(
uint256(position.size) + uint256(position.margin)
); // size + margin out
if (amount1 < 0)
TransferHelper.safeTransfer(
token1,
recipient,
uint256(-amount1)
);
(uint128 liquidityNext, uint160 sqrtPriceX96Next) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
int256(amount0Unlocked) + amount0, // insurance0 + debt0
int256(
amount1Unlocked -
uint256(position.size) -
uint256(position.margin)
) // insurance1 + debt1
);
_state.liquidity = liquidityNext;
_state.sqrtPriceX96 = sqrtPriceX96Next;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96Next);
uint256 balance0Before = balance0();
IMarginalV1SettleCallback(msg.sender).marginalV1SettleCallback(
amount0,
amount1,
data
);
if (balance0Before + uint256(amount0) > balance0())
revert Amount0LessThanMin();
}
positions.set(msg.sender, id, position.settle());
// update pool state to latest
state = _state;
emit Settle(
msg.sender,
uint256(id),
recipient,
_state.liquidity,
_state.sqrtPriceX96,
amount0,
amount1,
rewards
);
}
/// @inheritdoc IMarginalV1Pool
function liquidate(
address recipient,
address owner,
uint96 id
) external lock returns (uint256 rewards) {
State memory _state = stateSynced();
Position.Info memory position = positions.get(owner, id);
if (position.size == 0) revert InvalidPosition();
// oracle price averaged over seconds ago for liquidation calc
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
int56[] memory oracleTickCumulativesLast = oracleTickCumulatives(
secondsAgos
);
uint160 oracleSqrtPriceX96 = OracleLibrary.oracleSqrtPriceX96(
OracleLibrary.oracleTickCumulativeDelta(
oracleTickCumulativesLast[0],
oracleTickCumulativesLast[1]
),
secondsAgo
);
// update debts for funding
position = position.sync(
_state.blockTimestamp,
_state.tickCumulative,
oracleTickCumulativesLast[1], // zero seconds ago
tickCumulativeRateMax,
fundingPeriod
);
if (position.safe(oracleSqrtPriceX96, maintenance))
revert PositionSafe();
liquidityLocked -= position.liquidityLocked;
(uint256 amount0, uint256 amount1) = position.amountsLocked();
(_state.liquidity, _state.sqrtPriceX96) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
int256(amount0),
int256(amount1)
);
_state.tick = TickMath.getTickAtSqrtRatio(_state.sqrtPriceX96);
rewards = position.rewards;
TransferHelper.safeTransferETH(recipient, rewards); // ok given lock
positions.set(owner, id, position.liquidate());
// update pool state to latest
state = _state;
emit Liquidate(
owner,
uint256(id),
recipient,
_state.liquidity,
_state.sqrtPriceX96,
rewards
);
}
/// @inheritdoc IMarginalV1Pool
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external lock returns (int256 amount0, int256 amount1) {
State memory _state = stateSynced();
if (amountSpecified == 0) revert InvalidAmountSpecified();
if (
zeroForOne
? !(sqrtPriceLimitX96 < _state.sqrtPriceX96 &&
sqrtPriceLimitX96 > SqrtPriceMath.MIN_SQRT_RATIO)
: !(sqrtPriceLimitX96 > _state.sqrtPriceX96 &&
sqrtPriceLimitX96 < SqrtPriceMath.MAX_SQRT_RATIO)
) revert InvalidSqrtPriceLimitX96();
// add fees back in after swap calcs if exact input
bool exactInput = amountSpecified > 0;
int256 amountSpecifiedLessFee = exactInput
? amountSpecified -
int256(SwapMath.swapFees(uint256(amountSpecified), fee, false))
: amountSpecified;
uint160 sqrtPriceX96Next = SqrtPriceMath.sqrtPriceX96NextSwap(
_state.liquidity,
_state.sqrtPriceX96,
zeroForOne,
amountSpecifiedLessFee
);
if (
zeroForOne
? sqrtPriceX96Next < sqrtPriceLimitX96
: sqrtPriceX96Next > sqrtPriceLimitX96
) revert SqrtPriceX96ExceedsLimit();
// amounts without fees
(amount0, amount1) = SwapMath.swapAmounts(
_state.liquidity,
_state.sqrtPriceX96,
sqrtPriceX96Next
);
// optimistic amount out with callback for amount in
if (!zeroForOne) {
amount0 = !exactInput ? amountSpecified : amount0; // in case of rounding issues
if (amount0 < 0)
TransferHelper.safeTransfer(
token0,
recipient,
uint256(-amount0)
);
uint256 fees1 = exactInput
? uint256(amountSpecified) - uint256(amount1)
: SwapMath.swapFees(uint256(amount1), fee, true);
amount1 += int256(fees1);
uint256 balance1Before = balance1();
IMarginalV1SwapCallback(msg.sender).marginalV1SwapCallback(
amount0,
amount1,
data
);
if (amount1 == 0 || balance1Before + uint256(amount1) > balance1())
revert Amount1LessThanMin();
// account for protocol fees if fee on
uint256 delta = _state.feeProtocol > 0
? fees1 / _state.feeProtocol
: 0;
if (delta > 0) protocolFees.token1 += uint128(delta);
// update state liquidity, sqrt price accounting for fee growth
(uint128 liquidityAfter, uint160 sqrtPriceX96After) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
amount0,
amount1 - int256(delta) // exclude protocol fees if any
);
_state.liquidity = liquidityAfter;
_state.sqrtPriceX96 = sqrtPriceX96After;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96After);
} else {
amount1 = !exactInput ? amountSpecified : amount1; // in case of rounding issues
if (amount1 < 0)
TransferHelper.safeTransfer(
token1,
recipient,
uint256(-amount1)
);
uint256 fees0 = exactInput
? uint256(amountSpecified) - uint256(amount0)
: SwapMath.swapFees(uint256(amount0), fee, true);
amount0 += int256(fees0);
uint256 balance0Before = balance0();
IMarginalV1SwapCallback(msg.sender).marginalV1SwapCallback(
amount0,
amount1,
data
);
if (amount0 == 0 || balance0Before + uint256(amount0) > balance0())
revert Amount0LessThanMin();
// account for protocol fees if fee on
uint256 delta = _state.feeProtocol > 0
? fees0 / _state.feeProtocol
: 0;
if (delta > 0) protocolFees.token0 += uint128(delta);
// update state liquidity, sqrt price accounting for fee growth
(uint128 liquidityAfter, uint160 sqrtPriceX96After) = LiquidityMath
.liquiditySqrtPriceX96Next(
_state.liquidity,
_state.sqrtPriceX96,
amount0 - int256(delta), // exclude protocol fees if any
amount1
);
_state.liquidity = liquidityAfter;
_state.sqrtPriceX96 = sqrtPriceX96After;
_state.tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96After);
}
// update pool state to latest
state = _state;
emit Swap(
msg.sender,
recipient,
amount0,
amount1,
_state.sqrtPriceX96,
_state.liquidity,
_state.tick
);
}
/// @inheritdoc IMarginalV1Pool
function mint(
address recipient,
uint128 liquidityDelta,
bytes calldata data
) external lock returns (uint256 shares, uint256 amount0, uint256 amount1) {
uint256 _totalSupply = totalSupply();
bool initializing = (_totalSupply == 0);
if (initializing) initialize();
State memory _state = stateSynced();
uint128 liquidityDeltaMinimum = (initializing ? MINIMUM_LIQUIDITY : 0);
if (liquidityDelta <= liquidityDeltaMinimum)
revert InvalidLiquidityDelta();
(amount0, amount1) = LiquidityMath.toAmounts(
liquidityDelta,
_state.sqrtPriceX96
);
amount0 += 1; // rough round up on amounts in when add liquidity
amount1 += 1;
// total liquidity is available liquidity if all locked liquidity was returned to pool
uint128 totalLiquidityAfter = _state.liquidity +
liquidityLocked +
liquidityDelta;
shares = initializing
? totalLiquidityAfter
: Math.mulDiv(
_totalSupply,
liquidityDelta,
totalLiquidityAfter - liquidityDelta
);
_state.liquidity += liquidityDelta;
// callback for amounts owed
uint256 balance0Before = balance0();
uint256 balance1Before = balance1();
IMarginalV1MintCallback(msg.sender).marginalV1MintCallback(
amount0,
amount1,
data
);
if (balance0Before + amount0 > balance0()) revert Amount0LessThanMin();
if (balance1Before + amount1 > balance1()) revert Amount1LessThanMin();
// update pool state to latest
state = _state;
// lock min liquidity on initial mint to avoid stuck states with price
if (initializing) {
shares -= uint256(MINIMUM_LIQUIDITY);
_mint(address(this), MINIMUM_LIQUIDITY);
}
_mint(recipient, shares);
emit Mint(msg.sender, recipient, liquidityDelta, amount0, amount1);
}
/// @inheritdoc IMarginalV1Pool
function burn(
address recipient,
uint256 shares
)
external
lock
returns (uint128 liquidityDelta, uint256 amount0, uint256 amount1)
{
State memory _state = stateSynced();
uint256 _totalSupply = totalSupply();
// total liquidity is available liquidity if all locked liquidity were returned to pool
uint128 totalLiquidityBefore = _state.liquidity + liquidityLocked;
liquidityDelta = uint128(
Math.mulDiv(totalLiquidityBefore, shares, _totalSupply)
);
if (liquidityDelta > _state.liquidity) revert InvalidLiquidityDelta();
(amount0, amount1) = LiquidityMath.toAmounts(
liquidityDelta,
_state.sqrtPriceX96
);
_state.liquidity -= liquidityDelta;
if (amount0 > 0)
TransferHelper.safeTransfer(token0, recipient, amount0);
if (amount1 > 0)
TransferHelper.safeTransfer(token1, recipient, amount1);
// update pool state to latest
state = _state;
_burn(msg.sender, shares);
emit Burn(msg.sender, recipient, liquidityDelta, amount0, amount1);
}
/// @inheritdoc IMarginalV1Pool
function setFeeProtocol(uint8 feeProtocol) external lock onlyFactoryOwner {
if (!(feeProtocol == 0 || (feeProtocol >= 4 && feeProtocol <= 10)))
revert InvalidFeeProtocol();
emit SetFeeProtocol(state.feeProtocol, feeProtocol);
state.feeProtocol = feeProtocol;
}
/// @inheritdoc IMarginalV1Pool
function collectProtocol(
address recipient
)
external
lock
onlyFactoryOwner
returns (uint128 amount0, uint128 amount1)
{
// no zero check on protocolFees as will revert in amounts calculation
amount0 = protocolFees.token0 - 1; // ensure slot not cleared for gas savings
amount1 = protocolFees.token1 - 1;
protocolFees.token0 = 1;
TransferHelper.safeTransfer(token0, recipient, amount0);
protocolFees.token1 = 1;
TransferHelper.safeTransfer(token1, recipient, amount1);
emit CollectProtocol(msg.sender, recipient, amount0, amount1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10**64) {
value /= 10**64;
result += 64;
}
if (value >= 10**32) {
value /= 10**32;
result += 32;
}
if (value >= 10**16) {
value /= 10**16;
result += 16;
}
if (value >= 10**8) {
value /= 10**8;
result += 8;
}
if (value >= 10**4) {
value /= 10**4;
result += 4;
}
if (value >= 10**2) {
value /= 10**2;
result += 2;
}
if (value >= 10**1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
/// @title Oracle library
/// @notice Enables calculation of the geometric time weighted average price
library OracleLibrary {
/// @notice Returns the geometric time weighted average sqrtP
/// @dev Rounds toward zero for both positive and negative tick delta
/// @param tickCumulativeDelta The delta in tick cumulative over the averaging interval
/// @param timeDelta The time to average over
/// @return The geometric time weighted average price
function oracleSqrtPriceX96(
int56 tickCumulativeDelta,
uint32 timeDelta
) internal pure returns (uint160) {
// @uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol#L35
int24 arithmeticMeanTick = int24(
tickCumulativeDelta / int56(uint56(timeDelta))
);
return TickMath.getSqrtRatioAtTick(arithmeticMeanTick);
}
/// @notice Returns the tick cumulative delta over an interval
/// @dev Allows for tick cumulative overflow
/// @param tickCumulativeStart The tick cumulative value at the start of the interval
/// @param tickCumulativeEnd The tick cumulative value at the end of the interval
/// @return The delta in tick cumulative over the averaging interval
function oracleTickCumulativeDelta(
int56 tickCumulativeStart,
int56 tickCumulativeEnd
) internal pure returns (int56) {
unchecked {
return tickCumulativeEnd - tickCumulativeStart;
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {FixedPoint64} from "./FixedPoint64.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {FixedPoint192} from "./FixedPoint192.sol";
import {OracleLibrary} from "./OracleLibrary.sol";
/// @title Position library
/// @notice Facilitates calculations, updates, and retrieval of leverage position info
/// @dev Positions are represented in (x, y) space
library Position {
using SafeCast for uint256;
// info stored for each trader's leverage position
struct Info {
// size of position in token1 if zeroForOne = true or token0 if zeroForOne = false
uint128 size;
// debt owed by trader at settlement if zeroForOne = true, otherwise used for internal accounting only
uint128 debt0;
// debt owed by trader at settlement if zeroForOne = false, otherwise used for internal accounting only
uint128 debt1;
// insurance balances set aside by LPs to prevent liquidity shortfall in case of late liquidation
uint128 insurance0;
uint128 insurance1;
// whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
bool zeroForOne;
// whether the position has been liquidated
bool liquidated;
// tick before position was opened, used in maintenance margin requirements
int24 tick;
// timestamp when position was last synced for funding payments
uint32 blockTimestamp;
// delta between oracle and pool tick cumulatives at last funding sync (bar{a}_t - a_t)
int56 tickCumulativeDelta;
// margin backing position in token1 if zeroForOne = true or token0 if zeroForOne = false
uint128 margin;
// liquidity locked by LPs to collateralize the position. liability owed to pool
uint128 liquidityLocked;
// liquidation rewards escrowed with position in the native (gas) token to incentivize liquidations
uint256 rewards;
}
/// @notice Gets a position from positions mapping
/// @param positions The pool mapping that stores the leverage positions
/// @param owner The owner of the position
/// @param id The ID of the position
/// @return The position info associated with the (owner, ID) key
function get(
mapping(bytes32 => Info) storage positions,
address owner,
uint96 id
) internal view returns (Info memory) {
return positions[keccak256(abi.encodePacked(owner, id))];
}
/// @notice Stores the given position in positions mapping
/// @dev Used to create a new position or to update existing positions
/// @param positions The pool mapping that stores the leverage positions
/// @param owner The owner of the position
/// @param id The ID of the position
/// @param position The position information to store
function set(
mapping(bytes32 => Info) storage positions,
address owner,
uint96 id,
Info memory position
) internal {
positions[keccak256(abi.encodePacked(owner, id))] = position;
}
/// @notice Realizes funding payments via updates to position debt amounts
/// @param position The position to sync
/// @param blockTimestampLast The latest `block.timestamp` to sync to
/// @param tickCumulativeLast The `tickCumulative` from the pool at `blockTimestampLast`
/// @param oracleTickCumulativeLast The `tickCumulative` from the oracle at `blockTimestampLast`
/// @param tickCumulativeRateMax The maximum rate of change in tick cumulative between the oracle and pool `tickCumulative` values
/// @param fundingPeriod The pool funding period to benchmark funding payments to
/// @return The synced position
function sync(
Info memory position,
uint32 blockTimestampLast,
int56 tickCumulativeLast,
int56 oracleTickCumulativeLast,
uint24 tickCumulativeRateMax,
uint32 fundingPeriod
) internal pure returns (Info memory) {
// early exit if nothing to update
if (blockTimestampLast == position.blockTimestamp) return position;
// oracle tick - marginal tick (bar{a}_t - a_t)
int56 tickCumulativeDeltaLast = OracleLibrary.oracleTickCumulativeDelta(
tickCumulativeLast,
oracleTickCumulativeLast
);
(uint128 debt0, uint128 debt1) = debtsAfterFunding(
position,
blockTimestampLast,
tickCumulativeDeltaLast,
tickCumulativeRateMax,
fundingPeriod
);
position.debt0 = debt0;
position.debt1 = debt1;
position.blockTimestamp = blockTimestampLast;
position.tickCumulativeDelta = tickCumulativeDeltaLast;
return position;
}
/// @notice Liquidates an existing position
/// @param position The position to liquidate
/// @return positionAfter The liquidated position info
function liquidate(
Info memory position
) internal pure returns (Info memory positionAfter) {
positionAfter.zeroForOne = position.zeroForOne;
positionAfter.liquidated = true;
positionAfter.tick = position.tick;
positionAfter.blockTimestamp = position.blockTimestamp;
positionAfter.tickCumulativeDelta = position.tickCumulativeDelta;
}
/// @notice Settles existing position
/// @param position The position to settle
/// @return positionAfter The settled position info
function settle(
Info memory position
) internal pure returns (Info memory positionAfter) {
positionAfter.zeroForOne = position.zeroForOne;
positionAfter.liquidated = position.liquidated;
positionAfter.tick = position.tick;
positionAfter.blockTimestamp = position.blockTimestamp;
positionAfter.tickCumulativeDelta = position.tickCumulativeDelta;
}
/// @notice Assembles a new position from pool state
/// @dev zeroForOne = true means short position (long token1, short token0)
/// @param liquidity The pool liquidity before opening the position
/// @param sqrtPriceX96 The pool sqrt price before opening the position
/// @param sqrtPriceX96Next The pool sqrt price after opening the position
/// @param liquidityDelta The delta in pool liquidity used to collateralize the position
/// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
/// @param tick The pool tick before opening the position
/// @param blockTimestampStart The timestamp at which the pool state was last synced before opening the position
/// @param tickCumulativeStart The tick cumulative value from the pool at `blockTimestampStart`
/// @param oracleTickCumulativeStart The tick cumulative value from the oracle at `blockTimestampStart`
/// @return position The assembled position info
function assemble(
uint128 liquidity,
uint160 sqrtPriceX96,
uint160 sqrtPriceX96Next,
uint128 liquidityDelta,
bool zeroForOne,
int24 tick,
uint32 blockTimestampStart,
int56 tickCumulativeStart,
int56 oracleTickCumulativeStart
) internal pure returns (Info memory position) {
position.zeroForOne = zeroForOne;
position.tick = tick;
position.blockTimestamp = blockTimestampStart;
position.tickCumulativeDelta =
oracleTickCumulativeStart -
tickCumulativeStart;
position.liquidityLocked = liquidityDelta;
position.size = size(
liquidity,
sqrtPriceX96,
sqrtPriceX96Next,
zeroForOne
);
(position.insurance0, position.insurance1) = insurances(
liquidity,
sqrtPriceX96,
sqrtPriceX96Next,
liquidityDelta,
zeroForOne
);
(position.debt0, position.debt1) = debts(
sqrtPriceX96Next,
liquidityDelta,
position.insurance0,
position.insurance1
);
}
/// @notice Size of position in (x, y) amounts
/// @dev Size amount in token1 if zeroForOne = true, or in token0 if zeroForOne = false
/// @param liquidity The pool liquidity before opening the position
/// @param sqrtPriceX96 The pool sqrt price before opening the position
/// @param sqrtPriceX96Next The pool sqrt price after opening the position
/// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
/// @return The position size
function size(
uint128 liquidity,
uint160 sqrtPriceX96,
uint160 sqrtPriceX96Next,
bool zeroForOne
) internal pure returns (uint128) {
if (!zeroForOne) {
// L / sqrt(P) - L / sqrt(P')
return
((uint256(liquidity) << FixedPoint96.RESOLUTION) /
sqrtPriceX96 -
(uint256(liquidity) << FixedPoint96.RESOLUTION) /
sqrtPriceX96Next).toUint128();
} else {
// L * sqrt(P) - L * sqrt(P')
return
(
Math.mulDiv(
liquidity,
sqrtPriceX96 - sqrtPriceX96Next,
FixedPoint96.Q96
)
).toUint128();
}
}
/// @notice Insurance balances to back position in (x, y) amounts
/// @param liquidity The pool liquidity before opening the position
/// @param sqrtPriceX96 The pool sqrt price before opening the position
/// @param sqrtPriceX96Next The pool sqrt price after opening the position
/// @param liquidityDelta The delta in pool liquidity used to collateralize the position
/// @param zeroForOne Whether the position is long token1 and short token0 (true), or long token0 and short token1 (false)
/// @return insurance0 The insurance reserves in token0 needed to prevent liquidity shortfall for late liquidations
/// @return insurance1 The insurance reserves in token1 needed to prevent liquidity shortfall for late liquidations
function insurances(
uint128 liquidity,
uint160 sqrtPriceX96,
uint160 sqrtPriceX96Next,
uint128 liquidityDelta,
bool zeroForOne
) internal pure returns (uint128 insurance0, uint128 insurance1) {
uint256 prod = !zeroForOne
? Math.mulDiv(
liquidity - liquidityDelta,
sqrtPriceX96Next,
sqrtPriceX96
) // iy / y = 1 - sqrt(P'/P) * (1 - del L / L)
: Math.mulDiv(
liquidity - liquidityDelta,
sqrtPriceX96,
sqrtPriceX96Next
); // iy / y = 1 - sqrt(P/P') * (1 - del L / L)
insurance0 = (((uint256(liquidity) - prod) << FixedPoint96.RESOLUTION) /
sqrtPriceX96).toUint128();
insurance1 = (
Math.mulDiv(
uint256(liquidity) - prod,
sqrtPriceX96,
FixedPoint96.Q96
)
).toUint128();
}
/// @notice Debts owed by position in (x, y) amounts
/// @dev Uses invariant (insurance0 + debt0) * (insurance1 + debt1) = liquidityDelta * sqrtPriceNext
/// @param sqrtPriceX96Next The pool sqrt price after opening the position
/// @param liquidityDelta The delta in pool liquidity used to collateralize the position
/// @param insurance0 The position insurance reserves in token0
/// @param insurance1 The position insurance reserves in token1
/// @return debt0 The debt in token0 the position owes to the pool
/// @return debt1 The debt in token1 the position owes to the pool
function debts(
uint160 sqrtPriceX96Next,
uint128 liquidityDelta,
uint128 insurance0,
uint128 insurance1
) internal pure returns (uint128 debt0, uint128 debt1) {
// ix + dx = del L / sqrt(P'); iy + dy = del L * sqrt(P')
debt0 = ((uint256(liquidityDelta) << FixedPoint96.RESOLUTION) /
sqrtPriceX96Next -
uint256(insurance0)).toUint128();
debt1 = (Math.mulDiv(
liquidityDelta,
sqrtPriceX96Next,
FixedPoint96.Q96
) - uint256(insurance1)).toUint128();
}
/// @notice Fees owed when opening the position in (x, y) amounts
/// @dev Fees taken proportional to size
/// @param size The position size
/// @param fee The fee rate charged on position size
/// @return The amount of fees charged to open the position
function fees(uint128 size, uint24 fee) internal pure returns (uint256) {
return (uint256(size) * fee) / 1e6;
}
/// @notice Liquidation rewards required to set aside for liquidator in native (gas) token amount
/// @dev Returned on settle to position owner or used as incentive for liquidator to liquidate position when unsafe
/// @param blockBaseFee Current block base fee
/// @param blockBaseFeeMin Minimum block base fee to use in calculating cost to execute call to liquidate
/// @param gas Estimated gas required to execute call to liquidate
/// @param premium Liquidation premium to incentivize potential liquidators with
/// @return The liquidation rewards to set aside for liquidator if position unsafe
function liquidationRewards(
uint256 blockBaseFee,
uint256 blockBaseFeeMin,
uint256 gas,
uint24 premium
) internal pure returns (uint256) {
uint256 baseFee = (
blockBaseFee > blockBaseFeeMin ? blockBaseFee : blockBaseFeeMin
);
// need base fee of ~4e62 for possible overflow with gas limit of 30e6
return (baseFee * gas * uint256(premium)) / 1e6;
}
/// @notice Absolute minimum margin amount required to be held in position
/// @dev Uses `position.tick` prior to position open (alongside insurance balances) to ensure repayment to pool of at least liquidityDelta liability if ignore funding
/// @param position The position to check minimum margin amounts for
/// @param maintenance The minimum maintenance margin requirement for the pool
/// @return The minimum amount of margin the position must hold
function marginMinimum(
Info memory position,
uint24 maintenance
) internal pure returns (uint128) {
uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(position.tick); // price before open
if (!position.zeroForOne) {
// cx >= (1+M) * dy / P - sx
uint256 debt1Adjusted = (uint256(position.debt1) *
(1e6 + uint256(maintenance))) / 1e6;
uint256 prod = sqrtPriceX96 <= type(uint128).max
? Math.mulDiv(
debt1Adjusted,
FixedPoint192.Q192,
uint256(sqrtPriceX96) * uint256(sqrtPriceX96)
)
: Math.mulDiv(
debt1Adjusted,
FixedPoint128.Q128,
Math.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint64.Q64)
);
return
prod > uint256(position.size)
? (prod - uint256(position.size)).toUint128()
: 0; // check necessary due to funding
} else {
// cy >= (1+M) * dx * P - sy
uint256 debt0Adjusted = (uint256(position.debt0) *
(1e6 + uint256(maintenance))) / 1e6;
uint256 prod = sqrtPriceX96 <= type(uint128).max
? Math.mulDiv(
debt0Adjusted,
uint256(sqrtPriceX96) * uint256(sqrtPriceX96),
FixedPoint192.Q192
)
: Math.mulDiv(
debt0Adjusted,
Math.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint64.Q64),
FixedPoint128.Q128
);
return
prod > uint256(position.size)
? (prod - uint256(position.size)).toUint128()
: 0; // check necessary due to funding
}
}
/// @notice Amounts (x, y) of pool reserves locked in position
/// @dev Includes margin in the event position were to be liquidated
/// @param position The position
/// @return amount0 The amount of token0 set aside for the position
/// @return amount1 The amount of token1 set aside for the position
function amountsLocked(
Info memory position
) internal pure returns (uint256 amount0, uint256 amount1) {
if (!position.zeroForOne) {
amount0 =
uint256(position.size) +
uint256(position.margin) +
uint256(position.debt0) +
uint256(position.insurance0);
amount1 = position.insurance1;
} else {
amount0 = position.insurance0;
amount1 =
uint256(position.size) +
uint256(position.margin) +
uint256(position.debt1) +
uint256(position.insurance1);
}
}
/// @notice Debt adjusted for funding
/// @dev Ref @with-backed/papr/src/UniswapOracleFundingRateController.sol#L156
/// Follows debt0Next = debt0 * (oracleTwap / poolTwap) ** (dt / fundingPeriod) if zeroForOne = true
// or debt1Next = debt1 * (poolTwap / oracleTwap) ** (dt / fundingPeriod) if zeroForOne = false
/// @param position The position to update debts for funding
/// @param blockTimestampLast The block timestamp at the last pool state sync
/// @param tickCumulativeDeltaLast The delta in oracle tick cumulative minus pool tick cumulative values at `blockTimestampLast`
/// @param tickCumulativeRateMax The maximum rate of change in tick cumulative between the oracle and pool `tickCumulative` values
/// @param fundingPeriod The pool funding period to benchmark funding payments to
/// @return debt0 The position debt in token0 after funding
/// @return debt1 The position debt in token1 after funding
function debtsAfterFunding(
Info memory position,
uint32 blockTimestampLast,
int56 tickCumulativeDeltaLast,
uint24 tickCumulativeRateMax,
uint32 fundingPeriod
) internal pure returns (uint128 debt0, uint128 debt1) {
int56 deltaMax;
unchecked {
deltaMax =
int56(uint56(tickCumulativeRateMax)) *
int56(uint56(blockTimestampLast - position.blockTimestamp));
}
if (!position.zeroForOne) {
// debt1Now = debt1Start * (P / bar{P}) ** (now - start) / fundingPeriod
// delta = (a_t - bar{a}_t) - (a_0 - bar{a}_0), clamped by funding rate bounds
int56 delta = OracleLibrary.oracleTickCumulativeDelta(
tickCumulativeDeltaLast,
position.tickCumulativeDelta
);
if (delta > deltaMax) delta = deltaMax;
else if (delta < -deltaMax) delta = -deltaMax;
// @dev ok as position is unsafe well before arithmeticMeanTick reaches min/max tick given fundingPeriod, tickCumulativeRateMax values
uint160 numeratorX96 = OracleLibrary.oracleSqrtPriceX96(
delta,
fundingPeriod / 2 // div by 2 given sqrt price result
);
debt0 = position.debt0;
debt1 = Math
.mulDiv(position.debt1, numeratorX96, FixedPoint96.Q96)
.toUint128();
} else {
// debt0Now = debt0Start * (bar{P} / P) ** (now - start) / fundingPeriod
// delta = (bar{a}_t - a_t) - (bar{a}_0 - a_0), clamped by funding rate bounds
int56 delta = OracleLibrary.oracleTickCumulativeDelta(
position.tickCumulativeDelta,
tickCumulativeDeltaLast
);
if (delta > deltaMax) delta = deltaMax;
else if (delta < -deltaMax) delta = -deltaMax;
// @dev ok as position is unsafe well before arithmeticMeanTick reaches min/max tick given fundingPeriod, tickCumulativeRateMax values
uint160 numeratorX96 = OracleLibrary.oracleSqrtPriceX96(
delta,
fundingPeriod / 2 // div by 2 given sqrt price result
);
debt0 = Math
.mulDiv(position.debt0, numeratorX96, FixedPoint96.Q96)
.toUint128();
debt1 = position.debt1;
}
}
/// @notice Whether the position is safe from liquidation
/// @dev If not safe, position can be liquidated
/// Considered safe if (`position.margin` + `position.size`) / oracleTwap >= (1 + `maintenance`) * `position.debt0` when position.zeroForOne = true
/// or (`position.margin` + `position.size`) * oracleTwap >= (1 + `maintenance`) * `position.debt1` when position.zeroForOne = false
/// @param position The position to check safety of
/// @param sqrtPriceX96 The oracle time weighted average sqrt price
/// @param maintenance The minimum maintenance margin requirement for the pool
/// @return true if safe and false if not safe
function safe(
Info memory position,
uint160 sqrtPriceX96,
uint24 maintenance
) internal pure returns (bool) {
if (!position.zeroForOne) {
uint256 debt1Adjusted = (uint256(position.debt1) *
(1e6 + uint256(maintenance))) / 1e6;
uint256 liquidityCollateral = Math.mulDiv(
uint256(position.margin) + uint256(position.size),
sqrtPriceX96,
FixedPoint96.Q96
);
uint256 liquidityDebt = (debt1Adjusted << FixedPoint96.RESOLUTION) /
sqrtPriceX96;
return liquidityCollateral >= liquidityDebt;
} else {
uint256 debt0Adjusted = (uint256(position.debt0) *
(1e6 + uint256(maintenance))) / 1e6;
uint256 liquidityCollateral = ((uint256(position.margin) +
uint256(position.size)) << FixedPoint96.RESOLUTION) /
sqrtPriceX96;
uint256 liquidityDebt = Math.mulDiv(
debt0Adjusted,
sqrtPriceX96,
FixedPoint96.Q96
);
return liquidityCollateral >= liquidityDebt;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Math library for sqrt price changes
/// @notice Determines sqrt price changes after a opening leverage position and swapping on the pool
library SqrtPriceMath {
/// @dev Adopts Uni V3 tick limits of (-887272, 887272)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO =
1461446703485210103287273052203988822378723970342;
error InvalidSqrtPriceX96();
error Amount0ExceedsReserve0();
error Amount1ExceedsReserve1();
/// @notice Calculates sqrtP after opening a leverage position
/// @dev Choice of insurance function made in this function
/// @param liquidity Pool liquidity before opening the position
/// @param sqrtPriceX96 Pool price before opening the position
/// @param liquidityDelta Liquidity removed from pool to collateralize position
/// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
/// @param maintenance Minimum maintenance margin for the pool
/// @return The price after opening the position
function sqrtPriceX96NextOpen(
uint128 liquidity,
uint160 sqrtPriceX96,
uint128 liquidityDelta,
bool zeroForOne,
uint24 maintenance
) internal pure returns (uint160) {
uint256 prod = uint256(liquidityDelta) *
uint256(liquidity - liquidityDelta);
prod = Math.mulDiv(prod, 1e6, 1e6 + uint256(maintenance));
// root round down ensures no free size but can have nextX96 go opposite of intended direction
// as liquidityDelta -> 0. position.assemble will revert tho if so
uint256 under = uint256(liquidity) ** 2 - 4 * prod;
uint256 root = Math.sqrt(under);
uint256 nextX96 = !zeroForOne
? Math.mulDiv(
sqrtPriceX96,
uint256(liquidity) + root,
2 * uint256(liquidity - liquidityDelta)
)
: Math.mulDiv(
sqrtPriceX96,
2 * uint256(liquidity - liquidityDelta),
uint256(liquidity) + root
);
if (!(nextX96 >= MIN_SQRT_RATIO && nextX96 < MAX_SQRT_RATIO))
revert InvalidSqrtPriceX96();
return uint160(nextX96);
}
/// @notice Calculates sqrtP after swapping tokens
/// @dev Assumes amountSpecified != 0
/// @param liquidity Pool liquidity before swapping
/// @param sqrtPriceX96 Pool price before swapping
/// @param zeroForOne Whether swapping token0 for token1 (true), or token1 for token0 (false)
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @return The price after swapping
function sqrtPriceX96NextSwap(
uint128 liquidity,
uint160 sqrtPriceX96,
bool zeroForOne,
int256 amountSpecified
) internal pure returns (uint160) {
bool exactInput = amountSpecified > 0;
uint256 nextX96;
if (exactInput) {
if (!zeroForOne) {
// 1 is known
// sqrt(P') = sqrt(P) + del y / L
uint256 prod = (
uint256(amountSpecified) <= type(uint160).max
? (uint256(amountSpecified) <<
FixedPoint96.RESOLUTION) / liquidity
: Math.mulDiv(
uint256(amountSpecified),
FixedPoint96.Q96,
liquidity
)
);
nextX96 = uint256(sqrtPriceX96) + prod;
} else {
// 0 is known
// sqrt(P') = sqrt(P) - (del x * sqrt(P)) / (L / sqrt(P) + del x)
uint256 reserve0 = (uint256(liquidity) <<
FixedPoint96.RESOLUTION) / sqrtPriceX96;
uint256 prod = (
uint256(amountSpecified) <= type(uint96).max
? (uint256(amountSpecified) * uint256(sqrtPriceX96)) /
(reserve0 + uint256(amountSpecified))
: Math.mulDiv(
uint256(amountSpecified),
sqrtPriceX96,
reserve0 + uint256(amountSpecified)
)
);
nextX96 = uint256(sqrtPriceX96) - prod;
}
} else {
if (!zeroForOne) {
// 0 is known
// sqrt(P') = sqrt(P) - (del x * sqrt(P)) / (L / sqrt(P) + del x)
uint256 reserve0 = (uint256(liquidity) <<
FixedPoint96.RESOLUTION) / sqrtPriceX96;
if (reserve0 <= uint256(-amountSpecified))
revert Amount0ExceedsReserve0();
uint256 prod = (
uint256(-amountSpecified) <= type(uint96).max
? (uint256(-amountSpecified) * uint256(sqrtPriceX96)) /
(reserve0 - uint256(-amountSpecified))
: Math.mulDiv(
uint256(-amountSpecified),
sqrtPriceX96,
reserve0 - uint256(-amountSpecified)
)
);
nextX96 = uint256(sqrtPriceX96) + prod;
} else {
// 1 is known
// sqrt(P') = sqrt(P) + del y / L
uint256 reserve1 = Math.mulDiv(
liquidity,
sqrtPriceX96,
FixedPoint96.Q96
);
if (reserve1 <= uint256(-amountSpecified))
revert Amount1ExceedsReserve1();
uint256 prod = (
uint256(-amountSpecified) <= type(uint160).max
? (uint256(-amountSpecified) <<
FixedPoint96.RESOLUTION) / liquidity
: Math.mulDiv(
uint256(-amountSpecified),
FixedPoint96.Q96,
liquidity
)
);
nextX96 = uint256(sqrtPriceX96) - prod;
}
}
if (!(nextX96 >= MIN_SQRT_RATIO && nextX96 < MAX_SQRT_RATIO))
revert InvalidSqrtPriceX96();
return uint160(nextX96);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {FixedPoint96} from "./FixedPoint96.sol";
/// @title Math library for swaps
/// @notice Determines amounts involved in swaps
library SwapMath {
/// @notice Computes amounts in and out on swap without fees
/// @dev amount > 0 is amountIn, amount < 0 is amountOut
/// @param liquidity Pool liquidity before the swap
/// @param sqrtPriceX96 Pool price at the start of the swap
/// @param sqrtPriceX96Next Pool price at the end of the swap
/// @return amount0Delta The delta in token0 balance for the pool
/// @return amount1Delta The delta in token1 balance for the pool
function swapAmounts(
uint128 liquidity,
uint160 sqrtPriceX96,
uint160 sqrtPriceX96Next
) internal pure returns (int256 amount0Delta, int256 amount1Delta) {
// del x = L * del (1 / sqrt(P)); del y = L * del sqrt(P)
bool zeroForOne = sqrtPriceX96Next < sqrtPriceX96;
amount0Delta =
int256(
(uint256(liquidity) << FixedPoint96.RESOLUTION) /
sqrtPriceX96Next
) -
int256(
(uint256(liquidity) << FixedPoint96.RESOLUTION) / sqrtPriceX96
);
amount1Delta = zeroForOne
? -int256(
Math.mulDiv(
liquidity,
sqrtPriceX96 - sqrtPriceX96Next,
FixedPoint96.Q96
)
)
: int256(
Math.mulDiv(
liquidity,
sqrtPriceX96Next - sqrtPriceX96,
FixedPoint96.Q96
)
);
}
/// @notice Computes swap fee on amount in
/// @dev Can revert when amount > type(uint232).max, but irrelevant for SwapMath.sol::swapAmounts output and pool fee rate constant
/// @param amount Amount in to calculate swap fees off of
/// @param fee Fee rate applied on amount in to pool
/// @param lessFee Whether `amount` excludes swap fee amount
/// @return Total swap fees taken from amount in to pool
function swapFees(
uint256 amount,
uint24 fee,
bool lessFee
) internal pure returns (uint256) {
return (!lessFee ? (amount * fee) / 1e6 : (amount * fee) / (1e6 - fee));
}
}
// 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 {
error T();
error R();
/// @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 sqrtPriceX96 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 sqrtPriceX96) {
unchecked {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
if (absTick > uint256(int256(MAX_TICK))) revert T();
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;
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
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 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 sqrtPriceX96) internal pure returns (int24 tick) {
unchecked {
// second inequality must be < because the price can never reach the price at the max tick
if (!(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO)) revert R();
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
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) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title Transfer library
/// @notice Facilitates safe transfers of ERC20 tokens and native chain token
library TransferHelper {
using SafeERC20 for IERC20;
/// @notice Transfers an ERC20 token amount from this address
/// @dev If value > balance, transfers balance of this address
/// @param token The address of the ERC20 to transfer
/// @param to The address of the recipient
/// @param value The desired amount of tokens to transfer
function safeTransfer(address token, address to, uint256 value) internal {
// in case of dust errors due to (L, sqrtP) <=> (x, y) transforms
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 amount = value <= balance ? value : balance;
IERC20(token).safeTransfer(to, amount);
}
/// @notice Transfers an amount of native (gas) token from this address
/// @dev Ref @uniswap/v3-periphery/contracts/libraries/TransferHelper.sol#L56
/// @param to The address of the recipient
/// @param value The amount of ETH to transfer
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}("");
require(success, "STE");
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
{
"compilationTarget": {
"MarginalV1Pool.sol": "MarginalV1Pool"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/contracts=.cache/openzeppelin/v4.8.3",
":@uniswap/v3-core/contracts=.cache/uniswap-v3-core/v0.8"
],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"},{"internalType":"uint24","name":"_maintenance","type":"uint24"},{"internalType":"address","name":"_oracle","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"Amount0ExceedsReserve0","type":"error"},{"inputs":[],"name":"Amount0LessThanMin","type":"error"},{"inputs":[],"name":"Amount1ExceedsReserve1","type":"error"},{"inputs":[],"name":"Amount1LessThanMin","type":"error"},{"inputs":[],"name":"InvalidAmountSpecified","type":"error"},{"inputs":[],"name":"InvalidFeeProtocol","type":"error"},{"inputs":[],"name":"InvalidLiquidityDelta","type":"error"},{"inputs":[],"name":"InvalidPosition","type":"error"},{"inputs":[],"name":"InvalidSqrtPriceLimitX96","type":"error"},{"inputs":[],"name":"InvalidSqrtPriceX96","type":"error"},{"inputs":[],"name":"Locked","type":"error"},{"inputs":[],"name":"MarginLessThanMin","type":"error"},{"inputs":[],"name":"PositionSafe","type":"error"},{"inputs":[],"name":"R","type":"error"},{"inputs":[],"name":"RewardsLessThanMin","type":"error"},{"inputs":[],"name":"SqrtPriceX96ExceedsLimit","type":"error"},{"inputs":[],"name":"T","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginAfter","type":"uint256"}],"name":"Adjust","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"liquidityDelta","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"amount0","type":"uint128"},{"indexed":false,"internalType":"uint128","name":"amount1","type":"uint128"}],"name":"CollectProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"}],"name":"Initialize","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"liquidityAfter","type":"uint128"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96After","type":"uint160"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Liquidate","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint128","name":"liquidityDelta","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"liquidityAfter","type":"uint128"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96After","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"margin","type":"uint128"}],"name":"Open","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"oldFeeProtocol","type":"uint8"},{"indexed":false,"internalType":"uint8","name":"newFeeProtocol","type":"uint8"}],"name":"SetFeeProtocol","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint128","name":"liquidityAfter","type":"uint128"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96After","type":"uint160"},{"indexed":false,"internalType":"int256","name":"amount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"amount1","type":"int256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Settle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"int256","name":"amount0","type":"int256"},{"indexed":false,"internalType":"int256","name":"amount1","type":"int256"},{"indexed":false,"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"int24","name":"tick","type":"int24"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint96","name":"id","type":"uint96"},{"internalType":"int128","name":"marginDelta","type":"int128"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"adjust","outputs":[{"internalType":"uint256","name":"margin0","type":"uint256"},{"internalType":"uint256","name":"margin1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"shares","type":"uint256"}],"name":"burn","outputs":[{"internalType":"uint128","name":"liquidityDelta","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"}],"name":"collectProtocol","outputs":[{"internalType":"uint128","name":"amount0","type":"uint128"},{"internalType":"uint128","name":"amount1","type":"uint128"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fee","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"fundingPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint96","name":"id","type":"uint96"}],"name":"liquidate","outputs":[{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"liquidityLocked","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maintenance","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint128","name":"liquidityDelta","type":"uint128"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mint","outputs":[{"internalType":"uint256","name":"shares","type":"uint256"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"uint128","name":"liquidityDelta","type":"uint128"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"open","outputs":[{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"oracle","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"positions","outputs":[{"internalType":"uint128","name":"size","type":"uint128"},{"internalType":"uint128","name":"debt0","type":"uint128"},{"internalType":"uint128","name":"debt1","type":"uint128"},{"internalType":"uint128","name":"insurance0","type":"uint128"},{"internalType":"uint128","name":"insurance1","type":"uint128"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"bool","name":"liquidated","type":"bool"},{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint32","name":"blockTimestamp","type":"uint32"},{"internalType":"int56","name":"tickCumulativeDelta","type":"int56"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"uint128","name":"liquidityLocked","type":"uint128"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolFees","outputs":[{"internalType":"uint128","name":"token0","type":"uint128"},{"internalType":"uint128","name":"token1","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPremium","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"secondsAgo","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint8","name":"feeProtocol","type":"uint8"}],"name":"setFeeProtocol","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint96","name":"id","type":"uint96"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"settle","outputs":[{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"state","outputs":[{"internalType":"uint160","name":"sqrtPriceX96","type":"uint160"},{"internalType":"uint96","name":"totalPositions","type":"uint96"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"int24","name":"tick","type":"int24"},{"internalType":"uint32","name":"blockTimestamp","type":"uint32"},{"internalType":"int56","name":"tickCumulative","type":"int56"},{"internalType":"uint8","name":"feeProtocol","type":"uint8"},{"internalType":"bool","name":"initialized","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"int256","name":"amountSpecified","type":"int256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[{"internalType":"int256","name":"amount0","type":"int256"},{"internalType":"int256","name":"amount1","type":"int256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tickCumulativeRateMax","outputs":[{"internalType":"uint24","name":"","type":"uint24"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]