// 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: GPL-2.0-or-later
pragma solidity =0.8.15;
/// @title Function for getting block timestamp
/// @dev Base contract that is overridden for tests
abstract contract BlockTimestamp {
/// @dev Method that exists purely to be overridden for tests
/// @return The current block timestamp
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {PoolAddress} from "./PoolAddress.sol";
/// @notice Provides validation for callbacks from Marginal V1 Pools
/// @dev Fork of Uniswap V3 periphery CallbackValidation.sol
library CallbackValidation {
error PoolNotSender();
error OracleNotSender();
/// @notice Returns the address of a valid Marginal V1 Pool
/// @param factory The contract address of the Marginal V1 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param maintenance The maintenance requirements of the pool
/// @param oracle The contract address of the oracle referenced by the pool
/// @return pool The V1 pool contract address
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 maintenance,
address oracle
) internal view returns (IMarginalV1Pool pool) {
return
verifyCallback(
factory,
PoolAddress.getPoolKey(tokenA, tokenB, maintenance, oracle)
);
}
/// @notice Returns the address of a valid Marginal V1 Pool
/// @param factory The contract address of the Marginal V1 factory
/// @param poolKey The identifying key of the V1 pool
/// @return pool The V1 pool contract address
function verifyCallback(
address factory,
PoolAddress.PoolKey memory poolKey
) internal view returns (IMarginalV1Pool pool) {
pool = IMarginalV1Pool(PoolAddress.getAddress(factory, poolKey));
if (msg.sender != address(pool)) revert PoolNotSender();
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Marginal V1 factory
/// @param poolKey The identifying key of the V1 pool
/// @return uniswapV3Pool The Uniswap V3 pool oracle address associated with the V1 pool
function verifyUniswapV3Callback(
address factory,
PoolAddress.PoolKey memory poolKey
) internal view returns (IUniswapV3Pool uniswapV3Pool) {
PoolAddress.getAddress(factory, poolKey); // checks marginal pool active
uniswapV3Pool = IUniswapV3Pool(poolKey.oracle);
if (msg.sender != poolKey.oracle) revert OracleNotSender();
}
}
// 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 v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: address zero is not a valid owner");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _ownerOf(tokenId);
require(owner != address(0), "ERC721: invalid token ID");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
_requireMinted(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not token owner or approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
_requireMinted(tokenId);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
_safeTransfer(from, to, tokenId, data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _ownerOf(tokenId) != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId, 1);
// Check that tokenId was not minted by `_beforeTokenTransfer` hook
require(!_exists(tokenId), "ERC721: token already minted");
unchecked {
// Will not overflow unless all 2**256 token ids are minted to the same owner.
// Given that tokens are minted one by one, it is impossible in practice that
// this ever happens. Might change if we allow batch minting.
// The ERC fails to describe this case.
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId, 1);
// Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
owner = ERC721.ownerOf(tokenId);
// Clear approvals
delete _tokenApprovals[tokenId];
unchecked {
// Cannot overflow, as that would require more tokens to be burned/transferred
// out than the owner initially received through minting and transferring in.
_balances[owner] -= 1;
}
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId, 1);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Check that tokenId was not transferred by `_beforeTokenTransfer` hook
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId];
unchecked {
// `_balances[from]` cannot overflow for the same reason as described in `_burn`:
// `from`'s balance is the number of token held, which is at least one before the current
// transfer.
// `_balances[to]` could overflow in the conditions described in `_mint`. That would require
// all 2**256 token ids to be minted, which in practice is impossible.
_balances[from] -= 1;
_balances[to] += 1;
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` has not been minted yet.
*/
function _requireMinted(uint256 tokenId) internal view virtual {
require(_exists(tokenId), "ERC721: invalid token ID");
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
* - When `from` is zero, the tokens will be minted for `to`.
* - When `to` is zero, ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
* used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
* - When `from` is zero, the tokens were minted for `to`.
* - When `to` is zero, ``from``'s tokens were burned.
* - `from` and `to` are never both zero.
* - `batchSize` is non-zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
* being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
* that `ownerOf(tokenId)` is `a`.
*/
// solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal {
_balances[account] += amount;
}
}
// 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 v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// 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 (last updated v4.8.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// 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 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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {IPeripheryImmutableState} from "./IPeripheryImmutableState.sol";
import {IPeripheryPayments} from "./IPeripheryPayments.sol";
/// @title The interface of the non-fungible token for Marginal v1 leverage positions
/// @notice Wraps Marginal v1 leverage positions in a non-fungible token to allow for transfers
interface INonfungiblePositionManager is IERC721Metadata {
/// @notice Returns details of an existing position
/// @param tokenId The NFT token id associated with the position
/// @dev Do *NOT* use in callback. Vulnerable to re-entrancy view issues.
/// @return pool The pool address position taken out on
/// @return positionId The position ID stored in the pool for the associated position
/// @return zeroForOne Whether position settlement requires debt in of token0 for size + margin out of token1
/// @return size The position size on the pool in the margin token
/// @return debt The position debt owed to the pool in the non-margin token
/// @return margin The margin backing the position on the pool
/// @return safeMarginMinimum The minimum margin requirements necessary to keep position open on pool while also being safe from liquidation
/// @return liquidated Whether the position has been liquidated
/// @return safe Whether the position can be liquidated
/// @return rewards The reward available to liquidators when position not safe
function positions(
uint256 tokenId
)
external
view
returns (
address pool,
uint96 positionId,
bool zeroForOne,
uint128 size,
uint128 debt,
uint128 margin,
uint128 safeMarginMinimum,
bool liquidated,
bool safe,
uint256 rewards
);
struct MintParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
bool zeroForOne;
uint128 sizeDesired;
uint128 sizeMinimum;
uint128 debtMaximum;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
uint128 margin;
address recipient;
uint256 deadline;
}
/// @notice Mints a new position, opening on pool
/// @dev If a contract, `msg.sender` must implement a `receive()` function to receive any refunded excess liquidation rewards in the native (gas) token from the manager.
/// @param params The parameters necessary for the position mint, encoded as `MintParams` in calldata
/// @return tokenId The NFT token id associated with the minted position
/// @return size The position size on the pool in the margin token
/// @return debt The position debt owed to the pool in the non-margin token
/// @return margin The amount of margin token in used to open the position
/// @return fees The amount of fees in margin token paid to open the position
/// @return rewards The amount of liquidation rewards in native (gas) token escrowed in opened position
function mint(
MintParams calldata params
)
external
payable
returns (
uint256 tokenId,
uint256 size,
uint256 debt,
uint256 margin,
uint256 fees,
uint256 rewards
);
struct LockParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
uint256 tokenId;
uint128 marginIn;
uint256 deadline;
}
/// @dev Adds margin to an existing position
/// @param params The parameters necessary for adding margin to the position, encoded as `LockParams` in calldata
/// @return margin The margin backing the position after calling lock
function lock(
LockParams calldata params
) external payable returns (uint256 margin);
struct FreeParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
uint256 tokenId;
uint128 marginOut;
address recipient;
uint256 deadline;
}
/// @notice Removes margin from an existing position
/// @param params The parameters necessary for removing margin from the position, encoded as `FreeParams` in calldata
/// @return margin The margin backing the position after calling free
function free(FreeParams calldata params) external returns (uint256 margin);
struct BurnParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
uint256 tokenId;
address recipient;
uint256 deadline;
}
/// @notice Burns an existing position, settling on pool via external payer
/// @dev If a contract, `msg.sender` must implement a `receive()` function to receive any refunded excess debt payment in the native (gas) token from the manager.
/// @param params The parameters necessary for settling the position, encoded as `BurnParams` in calldata
/// @return amountIn The amount of debt token in used to settle position
/// @return amountOut The amount of margin token received after settling position
/// @return rewards The amount of escrowed liquidation rewards in native (gas) token released by pool after settling position
function burn(
BurnParams calldata params
)
external
payable
returns (uint256 amountIn, uint256 amountOut, uint256 rewards);
struct IgniteParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
uint256 tokenId;
uint256 amountOutMinimum;
address recipient;
uint256 deadline;
}
/// @notice Burns an existing position, settling on pool via swap through spot
/// @dev If a contract, `recipient` must implement a `receive()` function to receive any excess liquidation rewards unused by the spot swap in the native (gas) token from the manager.
/// @param params The parameters necessary for settling the position, encoded as `IgniteParams` in calldata
/// @return amountOut The amount of margin token received after settling position
/// @return rewards The amount of escrowed liquidation rewards in native (gas) token released by pool after settling position
function ignite(
IgniteParams calldata params
) external returns (uint256 amountOut, uint256 rewards);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {INonfungiblePositionManager} from "./INonfungiblePositionManager.sol";
/// @title Non-fungible token descriptor for Marginal v1 leverage positions
/// @notice Describes position NFT tokens via URI
interface INonfungibleTokenPositionDescriptor {
/// @notice Produces the URI describing a particular token ID for a position manager
/// @dev Note this URI may be a data: URI with the JSON contents directly inlined
/// @param positionManager The position manager for which to describe the token
/// @param tokenId The ID of the token for which to produce a description, which may not be valid
/// @return The URI of the ERC721-compliant metadata
function tokenURI(
INonfungiblePositionManager positionManager,
uint256 tokenId
) external view returns (string memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Marginal V1 factory
function factory() external view returns (address);
/// @return Returns the address of the Uniswap V3 factory
function uniswapV3Factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Transfers the full amount of ETH held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the ETH from users
/// @param amountMinimum The minimum amount of ETH required for a transfer
/// @param recipient The destination address of the ETH
function sweepETH(
uint256 amountMinimum,
address recipient
) external payable;
}
// 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#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 UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @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 IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// 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: 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: GPL-2.0-or-later
pragma solidity =0.8.15;
pragma abicoder v2;
import '../interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {IERC721Metadata} from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {Multicall} from "@uniswap/v3-periphery/contracts/base/Multicall.sol";
import {PeripheryValidation} from "@uniswap/v3-periphery/contracts/base/PeripheryValidation.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {PeripheryImmutableState} from "./base/PeripheryImmutableState.sol";
import {PositionManagement} from "./base/PositionManagement.sol";
import {PositionState} from "./base/PositionState.sol";
import {PoolAddress} from "./libraries/PoolAddress.sol";
import {PositionAmounts} from "./libraries/PositionAmounts.sol";
import {INonfungibleTokenPositionDescriptor} from "./interfaces/INonfungibleTokenPositionDescriptor.sol";
import {INonfungiblePositionManager} from "./interfaces/INonfungiblePositionManager.sol";
/// @title Non-fungible token for Marginal v1 leverage positions
/// @notice Wraps Marginal v1 leverage positions in the ERC721 non-fungible token interface
contract NonfungiblePositionManager is
INonfungiblePositionManager,
Multicall,
ERC721,
PeripheryImmutableState,
PositionManagement,
PositionState,
PeripheryValidation
{
struct Position {
address pool;
uint96 id;
}
mapping(uint256 => Position) private _positions;
uint256 private _nextId = 1;
address private immutable _tokenDescriptor;
modifier onlyApprovedOrOwner(uint256 tokenId) {
if (!_isApprovedOrOwner(msg.sender, tokenId)) revert Unauthorized();
_;
}
event Mint(
uint256 indexed tokenId,
address sender,
address indexed recipient,
uint256 positionId,
uint256 size,
uint256 debt,
uint256 margin,
uint256 fees,
uint256 rewards
);
event Lock(
uint256 indexed tokenId,
address indexed sender,
uint256 marginAfter
);
event Free(
uint256 indexed tokenId,
address indexed sender,
address recipient,
uint256 marginAfter
);
event Burn(
uint256 indexed tokenId,
address indexed sender,
address recipient,
uint256 amountIn,
uint256 amountOut,
uint256 rewards
);
event Ignite(
uint256 indexed tokenId,
address indexed sender,
address recipient,
uint256 amountOut,
uint256 rewards
);
error Unauthorized();
error InvalidPoolKey();
constructor(
address _factory,
address _WETH9,
address _tokenDescriptor_
)
ERC721("Marginal V1 Position Token", "MARGV1-POS")
PeripheryImmutableState(_factory, _WETH9)
{
_tokenDescriptor = _tokenDescriptor_;
}
/// @notice Returns the Uniform Resource Identifier (URI) for `tokenId` token
/// @param tokenId The NFT token id associated with the position
/// @return The URI for the position with given NFT token id
function tokenURI(
uint256 tokenId
) public view override(ERC721, IERC721Metadata) returns (string memory) {
require(_exists(tokenId));
return
INonfungibleTokenPositionDescriptor(_tokenDescriptor).tokenURI(
this,
tokenId
);
}
/// @inheritdoc INonfungiblePositionManager
function positions(
uint256 tokenId
)
external
view
returns (
address pool,
uint96 positionId,
bool zeroForOne,
uint128 size,
uint128 debt,
uint128 margin,
uint128 safeMarginMinimum,
bool liquidated,
bool safe,
uint256 rewards
)
{
Position memory position = _positions[tokenId];
pool = position.pool;
positionId = position.id;
(
zeroForOne,
size,
debt,
margin,
safeMarginMinimum,
liquidated,
safe,
rewards
) = getPositionSynced(pool, address(this), positionId);
}
/// @inheritdoc INonfungiblePositionManager
function mint(
MintParams calldata params
)
external
payable
checkDeadline(params.deadline)
returns (
uint256 tokenId,
uint256 size,
uint256 debt,
uint256 margin,
uint256 fees,
uint256 rewards
)
{
IMarginalV1Pool pool = getPool(
PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
})
);
(uint160 sqrtPriceX96, , uint128 liquidity, , , , , ) = pool.state();
uint128 liquidityDelta = PositionAmounts.getLiquidityForSize(
liquidity,
sqrtPriceX96,
params.maintenance,
params.zeroForOne,
params.sizeDesired
);
uint256 positionId;
(positionId, size, debt, margin, fees, rewards) = open(
OpenParams({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle,
recipient: address(this),
zeroForOne: params.zeroForOne,
liquidityDelta: liquidityDelta,
sqrtPriceLimitX96: params.sqrtPriceLimitX96 == 0
? (
params.zeroForOne
? TickMath.MIN_SQRT_RATIO + 1
: TickMath.MAX_SQRT_RATIO - 1
)
: params.sqrtPriceLimitX96,
margin: params.margin,
sizeMinimum: params.sizeMinimum,
debtMaximum: params.debtMaximum == 0
? type(uint128).max
: params.debtMaximum,
amountInMaximum: params.amountInMaximum == 0
? type(uint256).max
: params.amountInMaximum
})
);
// @dev ok to call before set position since _safeMint not used so no callback
_mint(params.recipient, (tokenId = _nextId++));
_positions[tokenId] = Position({
pool: address(pool),
id: uint96(positionId)
});
// refund any excess ETH from escrowed rewards to sender at end of function to avoid re-entrancy with fallback
refundETH();
emit Mint(
tokenId,
msg.sender,
params.recipient,
positionId,
size,
debt,
margin,
fees,
rewards
);
}
/// @inheritdoc INonfungiblePositionManager
function lock(
LockParams calldata params
)
external
payable
onlyApprovedOrOwner(params.tokenId)
checkDeadline(params.deadline)
returns (uint256 margin)
{
Position memory position = _positions[params.tokenId];
if (
address(
getPool(
PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
})
)
) != position.pool
) revert InvalidPoolKey();
(uint256 margin0, uint256 margin1) = adjust(
AdjustParams({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle,
recipient: msg.sender, // rebates to sender if dust leftover
id: position.id,
marginDelta: int128(params.marginIn)
})
);
margin = margin0 > 0 ? margin0 : margin1;
emit Lock(params.tokenId, msg.sender, margin);
}
/// @inheritdoc INonfungiblePositionManager
function free(
FreeParams calldata params
)
external
onlyApprovedOrOwner(params.tokenId)
checkDeadline(params.deadline)
returns (uint256 margin)
{
Position memory position = _positions[params.tokenId];
if (
address(
getPool(
PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
})
)
) != position.pool
) revert InvalidPoolKey();
(uint256 margin0, uint256 margin1) = adjust(
AdjustParams({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle,
recipient: params.recipient,
id: position.id,
marginDelta: -int128(params.marginOut)
})
);
margin = margin0 > 0 ? margin0 : margin1;
emit Free(params.tokenId, msg.sender, params.recipient, margin);
}
/// @inheritdoc INonfungiblePositionManager
function burn(
BurnParams calldata params
)
external
payable
onlyApprovedOrOwner(params.tokenId)
checkDeadline(params.deadline)
returns (uint256 amountIn, uint256 amountOut, uint256 rewards)
{
Position memory position = _positions[params.tokenId];
if (
address(
getPool(
PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
})
)
) != position.pool
) revert InvalidPoolKey();
// @dev delete the position and burn token before settling on pool to avoid re-entrancy view issues
delete _positions[params.tokenId];
_burn(params.tokenId);
(int256 amount0, int256 amount1, uint256 rewards) = settle(
SettleParams({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle,
recipient: params.recipient,
id: position.id
})
);
amountIn = amount0 > 0
? uint256(amount0)
: (amount1 > 0 ? uint256(amount1) : 0);
amountOut = amount0 < 0
? uint256(-amount0)
: (amount1 < 0 ? uint256(-amount1) : 0);
emit Burn(
params.tokenId,
msg.sender,
params.recipient,
amountIn,
amountOut,
rewards
);
}
/// @inheritdoc INonfungiblePositionManager
function ignite(
IgniteParams calldata params
)
external
onlyApprovedOrOwner(params.tokenId)
checkDeadline(params.deadline)
returns (uint256 amountOut, uint256 rewards)
{
Position memory position = _positions[params.tokenId];
if (
address(
getPool(
PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
})
)
) != position.pool
) revert InvalidPoolKey();
// @dev delete the position and burn token before settling on pool to avoid re-entrancy view issues
delete _positions[params.tokenId];
_burn(params.tokenId);
(amountOut, rewards) = flash(
FlashParams({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle,
recipient: params.recipient,
id: position.id,
amountOutMinimum: params.amountOutMinimum
})
);
emit Ignite(
params.tokenId,
msg.sender,
params.recipient,
amountOut,
rewards
);
}
}
// 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: GPL-2.0-or-later
pragma solidity =0.8.15;
import {IMarginalV1Factory} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Factory.sol";
import "../interfaces/IPeripheryImmutableState.sol";
/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract PeripheryImmutableState is IPeripheryImmutableState {
address public immutable factory;
address public immutable uniswapV3Factory;
address public immutable WETH9;
constructor(address _factory, address _WETH9) {
factory = _factory;
uniswapV3Factory = IMarginalV1Factory(_factory).uniswapV3Factory();
WETH9 = _WETH9;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IWETH9} from "@uniswap/v3-periphery/contracts/interfaces/external/IWETH9.sol";
import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import {PoolAddress} from "../libraries/PoolAddress.sol";
import {IPeripheryPayments} from "../interfaces/IPeripheryPayments.sol";
import {PeripheryImmutableState} from "./PeripheryImmutableState.sol";
abstract contract PeripheryPayments is
IPeripheryPayments,
PeripheryImmutableState
{
receive() external payable {
// WETH9 if unwrap, pool when receiving escrowed liquidation rewards
require(
msg.sender == WETH9 || PoolAddress.isPool(factory, msg.sender),
"Not WETH9 or pool"
);
}
/// @inheritdoc IPeripheryPayments
function unwrapWETH9(
uint256 amountMinimum,
address recipient
) public payable override {
uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, "Insufficient WETH9");
if (balanceWETH9 > 0) {
IWETH9(WETH9).withdraw(balanceWETH9);
TransferHelper.safeTransferETH(recipient, balanceWETH9);
}
}
/// @inheritdoc IPeripheryPayments
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) public payable override {
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, "Insufficient token");
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
/// @inheritdoc IPeripheryPayments
function refundETH() public payable override {
if (address(this).balance > 0)
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
/// @inheritdoc IPeripheryPayments
function sweepETH(uint256 amountMinimum, address recipient) public payable {
uint256 balanceETH = address(this).balance;
require(balanceETH >= amountMinimum, "Insufficient ETH");
if (balanceETH > 0)
TransferHelper.safeTransferETH(recipient, balanceETH);
}
/// @notice Wraps balance of native (gas) token in contract to WETH9
function wrapETH() internal {
if (address(this).balance > 0)
IWETH9(WETH9).deposit{value: address(this).balance}();
}
/// @notice Pay ERC20 token to recipient
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH9 && address(this).balance >= value) {
// pay with WETH9
IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
IWETH9(WETH9).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
/// @notice Balance of ERC20 token held by this contract
/// @param token The token to check
/// @return value The balance amount
function balance(address token) internal view returns (uint256 value) {
return IERC20(token).balanceOf(address(this));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.8.15;
import './BlockTimestamp.sol';
abstract contract PeripheryValidation is BlockTimestamp {
modifier checkDeadline(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Transaction too old');
_;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IMarginalV1Factory} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Factory.sol";
/// @dev Fork of Uniswap V3 periphery PoolAddress.sol
library PoolAddress {
error PoolInactive();
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 maintenance;
address oracle;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param maintenance The maintenance level of the pool
/// @param oracle The contract address of the oracle referenced by the pool
/// @return PoolKey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 maintenance,
address oracle
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return
PoolKey({
token0: tokenA,
token1: tokenB,
maintenance: maintenance,
oracle: oracle
});
}
/// @notice Gets the pool address from factory given pool key
/// @dev Reverts if pool not created yet
/// @param factory The factory contract address
/// @param key The pool key
/// @return pool The contract address of the pool
function getAddress(
address factory,
PoolKey memory key
) internal view returns (address pool) {
pool = IMarginalV1Factory(factory).getPool(
key.token0,
key.token1,
key.maintenance,
key.oracle
);
if (pool == address(0)) revert PoolInactive();
}
/// @notice Checks factory for whether `pool` is a valid pool
/// @param factory The factory contract address
/// @param pool The contract address to check whether is a pool
function isPool(
address factory,
address pool
) internal view returns (bool) {
return IMarginalV1Factory(factory).isPool(pool);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.4.0;
/// @title PoolConstants
/// @notice A library for pool internal constants relevant for periphery contracts
library PoolConstants {
uint24 internal constant fee = 1000; // 10 bps across all pools
uint24 internal constant rewardPremium = 2000000; // 2x base fee as liquidation rewards
uint24 internal constant tickCumulativeRateMax = 920; // bound on funding rate of ~10% per funding period
uint32 internal constant secondsAgo = 43200; // 12 hr TWAP for oracle price
uint32 internal 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
}
// 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: AGPL-3.0
pragma solidity ^0.8.0;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {LiquidityMath} from "@marginal/v1-core/contracts/libraries/LiquidityMath.sol";
/// @title Position amounts library
/// @notice Calculates liquidity from desired size amounts
library PositionAmounts {
using SafeCast for uint256;
error SizeGreaterThanReserve(uint256 reserve);
/// @notice Gets the pool liquidity to be utilized for a given position size
/// @param liquidity The available liquidity of the pool
/// @param sqrtPriceX96 The sqrt price of the pool
/// @param maintenance The minimum maintenance requirement of the pool
/// @param zeroForOne Whether long token1 and short token0 (true), or long token0 and short token1 (false)
/// @param size The desired size of the position in token1 if zeroForOne = true, or token0 if zeroForOne = false
/// @return liquidityDelta The pool liquidity to be utilized
function getLiquidityForSize(
uint128 liquidity,
uint160 sqrtPriceX96,
uint24 maintenance,
bool zeroForOne,
uint128 size
) internal pure returns (uint128 liquidityDelta) {
// del L / L = (sx / x) / (1 - (1 - sx / x) ** 2 / (1 + M))
(uint256 reserve0, uint256 reserve1) = LiquidityMath.toAmounts(
liquidity,
sqrtPriceX96
);
uint256 reserve = !zeroForOne ? reserve0 : reserve1;
if (size >= reserve) revert SizeGreaterThanReserve(reserve);
uint256 prod = (reserve - uint256(size)) ** 2 / reserve;
uint256 denom = reserve - (prod * 1e6) / (1e6 + maintenance);
liquidityDelta = ((uint256(liquidity) * uint256(size)) / denom)
.toUint128();
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;
import {TickMath} from "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import {IUniswapV3SwapCallback} from "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import {IMarginalV1AdjustCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1AdjustCallback.sol";
import {IMarginalV1OpenCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1OpenCallback.sol";
import {IMarginalV1SettleCallback} from "@marginal/v1-core/contracts/interfaces/callback/IMarginalV1SettleCallback.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {Position as PositionLibrary} from "@marginal/v1-core/contracts/libraries/Position.sol";
import {PeripheryImmutableState} from "./PeripheryImmutableState.sol";
import {PeripheryPayments} from "./PeripheryPayments.sol";
import {CallbackValidation} from "../libraries/CallbackValidation.sol";
import {PoolAddress} from "../libraries/PoolAddress.sol";
import {PoolConstants} from "../libraries/PoolConstants.sol";
abstract contract PositionManagement is
IMarginalV1AdjustCallback,
IMarginalV1OpenCallback,
IMarginalV1SettleCallback,
IUniswapV3SwapCallback,
PeripheryImmutableState,
PeripheryPayments
{
struct PositionCallbackData {
PoolAddress.PoolKey poolKey;
address payer;
}
error SizeLessThanMin(uint256 size);
error DebtGreaterThanMax(uint256 debt);
error AmountInGreaterThanMax(uint256 amountIn);
error AmountOutLessThanMin(uint256 amountOut);
error RewardsLessThanMin(uint256 rewardsMinimum);
/// @dev Returns the pool for the given token pair and maintenance. The pool contract may or may not exist.
function getPool(
PoolAddress.PoolKey memory poolKey
) internal view returns (IMarginalV1Pool) {
return IMarginalV1Pool(PoolAddress.getAddress(factory, poolKey));
}
struct OpenParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
address recipient;
bool zeroForOne;
uint128 liquidityDelta;
uint160 sqrtPriceLimitX96;
uint128 margin;
uint128 sizeMinimum;
uint128 debtMaximum;
uint256 amountInMaximum;
}
/// @notice Opens a new position on pool
/// @param params The parameters necessary to open the position on the pool
/// @return id The position ID stored in the pool
/// @return size The position size on the pool in the margin token
/// @return debt The position debt owed to the pool in the non-margin token
/// @return margin The margin backing the position opened on the pool
/// @return fees The fees paid in margin token to open the position on the pool
/// @return rewards The rewards escrowed in opened position available to liquidators when position not safe
function open(
OpenParams memory params
)
internal
virtual
returns (
uint256 id,
uint256 size,
uint256 debt,
uint256 margin,
uint256 fees,
uint256 rewards
)
{
PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
});
IMarginalV1Pool pool = getPool(poolKey);
rewards = PositionLibrary.liquidationRewards(
block.basefee,
PoolConstants.blockBaseFeeMin,
PoolConstants.gasLiquidate,
PoolConstants.rewardPremium
); // deposited for liquidation reward escrow
// @dev use address(this).balance and not msg.value to avoid issues with multicall
if (address(this).balance < rewards) revert RewardsLessThanMin(rewards); // only send the min required
uint256 amount0;
uint256 amount1;
(id, size, debt, amount0, amount1) = pool.open{value: rewards}(
params.recipient,
params.zeroForOne,
params.liquidityDelta,
params.sqrtPriceLimitX96,
params.margin,
abi.encode(
PositionCallbackData({poolKey: poolKey, payer: msg.sender})
)
);
if (size < uint256(params.sizeMinimum)) revert SizeLessThanMin(size);
if (debt > uint256(params.debtMaximum)) revert DebtGreaterThanMax(debt);
uint256 amountIn = (!params.zeroForOne) ? amount0 : amount1; // in margin token
if (amountIn > params.amountInMaximum)
revert AmountInGreaterThanMax(amountIn);
margin = params.margin;
fees = amountIn - margin;
}
/// @inheritdoc IMarginalV1OpenCallback
function marginalV1OpenCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external virtual {
PositionCallbackData memory decoded = abi.decode(
data,
(PositionCallbackData)
);
CallbackValidation.verifyCallback(factory, decoded.poolKey);
if (amount0Owed > 0)
pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
if (amount1Owed > 0)
pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
}
struct AdjustParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
address recipient;
uint96 id;
int128 marginDelta;
}
/// @notice Adjusts margin backing position on pool
/// @param params The parameters necessary to adjust the position on the pool
/// @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(
AdjustParams memory params
) internal virtual returns (uint256 margin0, uint256 margin1) {
PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
});
IMarginalV1Pool pool = getPool(poolKey);
// manager receives flashed out margin and must handle delta in callback
(margin0, margin1) = pool.adjust(
address(this),
params.id,
params.marginDelta,
abi.encode(
PositionCallbackData({poolKey: poolKey, payer: msg.sender})
)
);
// sweep any freed margin remaining in contract
address tokenOut = margin0 > 0 ? params.token0 : params.token1;
uint256 amountOut = balance(tokenOut);
if (amountOut > 0)
pay(tokenOut, address(this), params.recipient, amountOut);
}
/// @inheritdoc IMarginalV1AdjustCallback
function marginalV1AdjustCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external virtual {
PositionCallbackData memory decoded = abi.decode(
data,
(PositionCallbackData)
);
CallbackValidation.verifyCallback(factory, decoded.poolKey);
if (amount0Owed > 0) {
uint256 balance0 = balance(decoded.poolKey.token0);
if (amount0Owed > balance0)
pay(
decoded.poolKey.token0,
decoded.payer,
address(this),
amount0Owed - balance0
);
pay(decoded.poolKey.token0, address(this), msg.sender, amount0Owed);
}
if (amount1Owed > 0) {
uint256 balance1 = balance(decoded.poolKey.token1);
if (amount1Owed > balance1)
pay(
decoded.poolKey.token1,
decoded.payer,
address(this),
amount1Owed - balance1
);
pay(decoded.poolKey.token1, address(this), msg.sender, amount1Owed);
}
}
struct SettleParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
address recipient;
uint96 id;
}
/// @notice Settles a position on pool via external payer of debt
/// @dev Beware of re-entrancy issues given implicit ETH transfer at end of function
/// @param params The parameters necessary to settle the position on the pool
/// @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 `params.recipient`
function settle(
SettleParams memory params
)
internal
virtual
returns (int256 amount0, int256 amount1, uint256 rewards)
{
PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
});
IMarginalV1Pool pool = getPool(poolKey);
(amount0, amount1, rewards) = pool.settle(
params.recipient,
params.id,
abi.encode(
PositionCallbackData({poolKey: poolKey, payer: msg.sender})
)
);
// any remaining ETH in the contract from payable return to sender
refundETH();
}
struct FlashParams {
address token0;
address token1;
uint24 maintenance;
address oracle;
address recipient;
uint96 id;
uint256 amountOutMinimum;
}
/// @notice Settles a position by repaying debt with portion of size swapped through spot
/// @dev Beware of re-entrancy issues given implicit ETH transfer at end of function
/// @param params The parameters necessary to flash settle the position on the pool
/// @return amountOut The amount of margin token received from pool less debts repaid via swapping on spot
/// @return rewards The amount of escrowed native (gas) token released by pool after flash settling the position
function flash(
FlashParams memory params
) internal virtual returns (uint256 amountOut, uint256 rewards) {
PoolAddress.PoolKey memory poolKey = PoolAddress.PoolKey({
token0: params.token0,
token1: params.token1,
maintenance: params.maintenance,
oracle: params.oracle
});
IMarginalV1Pool pool = getPool(poolKey);
address payer = address(this);
int256 amount0;
int256 amount1;
(amount0, amount1, rewards) = pool.settle(
payer,
params.id,
abi.encode(PositionCallbackData({poolKey: poolKey, payer: payer}))
);
address tokenOut = amount0 < 0 ? params.token0 : params.token1;
amountOut = balance(tokenOut);
if (amountOut < params.amountOutMinimum)
revert AmountOutLessThanMin(amountOut);
if (amountOut > 0) pay(tokenOut, payer, params.recipient, amountOut);
// any remaining WETH in contract from liquidation rewards return as ETH
unwrapWETH9(0, params.recipient);
}
/// @inheritdoc IMarginalV1SettleCallback
function marginalV1SettleCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external virtual {
if (amount0Delta <= 0 && amount1Delta <= 0) revert SizeLessThanMin(0); // can't settle position with zero size; Q: ok? necessary?
PositionCallbackData memory decoded = abi.decode(
data,
(PositionCallbackData)
);
CallbackValidation.verifyCallback(factory, decoded.poolKey);
if (decoded.payer == address(this)) {
// wrap ETH balance from liquidation rewards returned for possible use in settlement
wrapETH();
// swap portion of flashed size through spot to repay debt
bool zeroForOne = amount1Delta > 0; // owe 1 to marginal if true
IUniswapV3Pool(decoded.poolKey.oracle).swap(
msg.sender,
zeroForOne,
(zeroForOne ? -amount1Delta : -amount0Delta),
(
zeroForOne
? TickMath.MIN_SQRT_RATIO + 1
: TickMath.MAX_SQRT_RATIO - 1
),
abi.encode(decoded.poolKey)
);
} else {
// simply pay debt from external payer
if (amount0Delta > 0)
pay(
decoded.poolKey.token0,
decoded.payer,
msg.sender,
uint256(amount0Delta)
);
if (amount1Delta > 0)
pay(
decoded.poolKey.token1,
decoded.payer,
msg.sender,
uint256(amount1Delta)
);
}
}
/// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external virtual {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
PoolAddress.PoolKey memory poolKey = abi.decode(
data,
(PoolAddress.PoolKey)
);
CallbackValidation.verifyUniswapV3Callback(factory, poolKey);
if (amount0Delta > 0)
pay(
poolKey.token0,
address(this),
msg.sender,
uint256(amount0Delta)
);
if (amount1Delta > 0)
pay(
poolKey.token1,
address(this),
msg.sender,
uint256(amount1Delta)
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity =0.8.15;
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {Position as PositionLibrary} from "@marginal/v1-core/contracts/libraries/Position.sol";
import {OracleLibrary} from "@marginal/v1-core/contracts/libraries/OracleLibrary.sol";
import {IMarginalV1Pool} from "@marginal/v1-core/contracts/interfaces/IMarginalV1Pool.sol";
import {PoolConstants} from "../libraries/PoolConstants.sol";
abstract contract PositionState {
using PositionLibrary for PositionLibrary.Info;
/// @notice Gets pool state synced for pool oracle updates
/// @param pool The pool to get state of
function getStateSynced(
address pool
)
internal
view
returns (
uint160 sqrtPriceX96,
uint96 totalPositions,
uint128 liquidity,
int24 tick,
uint32 blockTimestamp,
int56 tickCumulative,
uint8 feeProtocol,
bool initialized
)
{
(
sqrtPriceX96,
totalPositions,
liquidity,
tick,
blockTimestamp,
tickCumulative,
feeProtocol,
initialized
) = IMarginalV1Pool(pool).state();
// oracle update
unchecked {
tickCumulative +=
int56(tick) *
int56(uint56(uint32(block.timestamp) - blockTimestamp)); // overflow desired
blockTimestamp = uint32(block.timestamp);
}
}
/// @notice Gets external oracle tick cumulative values for time deltas: [secondsAgo, 0]
/// @param pool The pool to get external oracle state for
function getOracleSynced(
address pool
) internal view returns (int56[] memory oracleTickCumulatives) {
address oracle = IMarginalV1Pool(pool).oracle();
// zero seconds ago for oracle tickCumulative
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = PoolConstants.secondsAgo;
(oracleTickCumulatives, ) = IUniswapV3Pool(oracle).observe(secondsAgos);
}
/// @notice Gets pool position synced for funding updates
/// @param pool The pool the position is on
/// @param recipient The recipient of the position at open
/// @param id The position id
function getPositionSynced(
address pool,
address recipient,
uint96 id
)
internal
view
returns (
bool zeroForOne,
uint128 size,
uint128 debt,
uint128 margin,
uint128 safeMarginMinimum,
bool liquidated,
bool safe,
uint256 rewards
)
{
PositionLibrary.Info memory info;
{
bytes32 key = keccak256(abi.encodePacked(recipient, id));
uint128 _debt0;
uint128 _debt1;
int24 _tick;
uint32 _blockTimestamp;
int56 _tickCumulativeDelta;
(
size,
_debt0,
_debt1,
,
,
zeroForOne,
liquidated,
_tick,
_blockTimestamp,
_tickCumulativeDelta,
margin,
,
rewards
) = IMarginalV1Pool(pool).positions(key);
info = PositionLibrary.Info({
size: size,
debt0: _debt0,
debt1: _debt1,
insurance0: 0, // @dev irrelevant for sync
insurance1: 0,
zeroForOne: zeroForOne,
liquidated: liquidated,
tick: _tick,
blockTimestamp: _blockTimestamp,
tickCumulativeDelta: _tickCumulativeDelta,
margin: margin,
liquidityLocked: 0, // @dev irrelevant for sync
rewards: rewards
});
}
uint24 maintenance = IMarginalV1Pool(pool).maintenance();
uint128 marginMinimum = info.marginMinimum(maintenance);
// sync if not settled or liquidated
if (info.size > 0) {
int56 oracleTickCumulativeDelta;
{
(
,
,
,
,
uint32 blockTimestampLast,
int56 tickCumulativeLast,
,
) = getStateSynced(pool);
int56[] memory oracleTickCumulativesLast = getOracleSynced(
pool
);
oracleTickCumulativeDelta = OracleLibrary
.oracleTickCumulativeDelta(
oracleTickCumulativesLast[0],
oracleTickCumulativesLast[1]
);
info.sync(
blockTimestampLast,
tickCumulativeLast,
oracleTickCumulativesLast[1], // zero seconds ago
PoolConstants.tickCumulativeRateMax,
PoolConstants.fundingPeriod
);
}
safe = info.safe(
OracleLibrary.oracleSqrtPriceX96(
oracleTickCumulativeDelta,
PoolConstants.secondsAgo
),
maintenance
);
safeMarginMinimum = _safeMarginMinimum(
info,
marginMinimum,
maintenance,
oracleTickCumulativeDelta
);
}
debt = zeroForOne ? info.debt0 : info.debt1;
}
/// @notice Calculates the minimum margin requirement for the position to remain safe from liquidation
/// @dev c_y (safe) >= (1+M) * d_x * max(P, TWAP) - s_y when zeroForOne = true when no funding
/// or c_x (safe) >= (1+M) * d_y / min(P, TWAP) - s_x when zeroForOne = false when no funding
/// @param info The synced position info
/// @param marginMinimum The margin minimum when ignoring funding and liquidation
/// @param maintenance The minimum maintenance margin requirement
/// @param oracleTickCumulativeDelta The difference in oracle tick cumulatives averaged over to assess position safety with
function _safeMarginMinimum(
PositionLibrary.Info memory info,
uint128 marginMinimum,
uint24 maintenance,
int56 oracleTickCumulativeDelta
) internal pure returns (uint128 safeMarginMinimum) {
int24 positionTick = info.tick;
int24 oracleTick = int24(
oracleTickCumulativeDelta / int56(uint56(PoolConstants.secondsAgo))
);
// change to using oracle tick for safe margin minimum calculation with liquidation and funding
info.tick = oracleTick;
safeMarginMinimum = info.marginMinimum(maintenance);
if (marginMinimum > safeMarginMinimum)
safeMarginMinimum = marginMinimum;
info.tick = positionTick; // in case reuse info, return to actual position tick
}
}
// 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: 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: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
}
// 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: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
{
"compilationTarget": {
"NonfungiblePositionManager.sol": "NonfungiblePositionManager"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@marginal/v1-core/contracts=.cache/marginal-v1-core/v1.0.1",
":@openzeppelin/contracts=.cache/openzeppelin/v4.8.3",
":@uniswap/v3-core/contracts=.cache/uniswap-v3-core/v0.8",
":@uniswap/v3-periphery/contracts=.cache/uniswap-v3-periphery/v0.8"
],
"viaIR": true
}
[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH9","type":"address"},{"internalType":"address","name":"_tokenDescriptor_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"}],"name":"AmountInGreaterThanMax","type":"error"},{"inputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"}],"name":"AmountOutLessThanMin","type":"error"},{"inputs":[{"internalType":"uint256","name":"debt","type":"uint256"}],"name":"DebtGreaterThanMax","type":"error"},{"inputs":[],"name":"InvalidPoolKey","type":"error"},{"inputs":[],"name":"OracleNotSender","type":"error"},{"inputs":[],"name":"PoolInactive","type":"error"},{"inputs":[],"name":"PoolNotSender","type":"error"},{"inputs":[{"internalType":"uint256","name":"rewardsMinimum","type":"uint256"}],"name":"RewardsLessThanMin","type":"error"},{"inputs":[{"internalType":"uint256","name":"reserve","type":"uint256"}],"name":"SizeGreaterThanReserve","type":"error"},{"inputs":[{"internalType":"uint256","name":"size","type":"uint256"}],"name":"SizeLessThanMin","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":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountIn","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginAfter","type":"uint256"}],"name":"Free","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountOut","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Ignite","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"marginAfter","type":"uint256"}],"name":"Lock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"positionId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"size","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fees","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"rewards","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"WETH9","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.BurnParams","name":"params","type":"tuple"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"marginOut","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.FreeParams","name":"params","type":"tuple"}],"name":"free","outputs":[{"internalType":"uint256","name":"margin","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amountOutMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.IgniteParams","name":"params","type":"tuple"}],"name":"ignite","outputs":[{"internalType":"uint256","name":"amountOut","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"marginIn","type":"uint128"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.LockParams","name":"params","type":"tuple"}],"name":"lock","outputs":[{"internalType":"uint256","name":"margin","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1AdjustCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Owed","type":"uint256"},{"internalType":"uint256","name":"amount1Owed","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1OpenCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"marginalV1SettleCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"maintenance","type":"uint24"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"uint128","name":"sizeDesired","type":"uint128"},{"internalType":"uint128","name":"sizeMinimum","type":"uint128"},{"internalType":"uint128","name":"debtMaximum","type":"uint128"},{"internalType":"uint256","name":"amountInMaximum","type":"uint256"},{"internalType":"uint160","name":"sqrtPriceLimitX96","type":"uint160"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct INonfungiblePositionManager.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"size","type":"uint256"},{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"margin","type":"uint256"},{"internalType":"uint256","name":"fees","type":"uint256"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"positions","outputs":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"uint96","name":"positionId","type":"uint96"},{"internalType":"bool","name":"zeroForOne","type":"bool"},{"internalType":"uint128","name":"size","type":"uint128"},{"internalType":"uint128","name":"debt","type":"uint128"},{"internalType":"uint128","name":"margin","type":"uint128"},{"internalType":"uint128","name":"safeMarginMinimum","type":"uint128"},{"internalType":"bool","name":"liquidated","type":"bool"},{"internalType":"bool","name":"safe","type":"bool"},{"internalType":"uint256","name":"rewards","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refundETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepETH","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uniswapV3Factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"int256","name":"amount0Delta","type":"int256"},{"internalType":"int256","name":"amount1Delta","type":"int256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"uniswapV3SwapCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amountMinimum","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWETH9","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]