# IMaverickV2Pool

### Functions <a href="#functions" id="functions"></a>

#### kinds <a href="#kinds" id="kinds"></a>

1-15 number to represent the active kinds. 0b0001 = static; 0b0010 = right; 0b0100 = left; 0b1000 = both; E.g. a pool with all 4 modes will have kinds = b1111 = 15

```solidity
function kinds() external view returns (uint8);
```

#### fee <a href="#fee" id="fee"></a>

Pool swap fee for the given direction (A-in or B-in swap) in 18-decimal format. E.g. 0.01e18 is a 1% swap fee.

```solidity
function fee(bool tokenAIn) external view returns (uint256);
```

#### tickSpacing <a href="#tickspacing" id="tickspacing"></a>

TickSpacing of pool where 1.0001^tickSpacing is the bin width.

```solidity
function tickSpacing() external view returns (uint256);
```

#### lookback <a href="#lookback" id="lookback"></a>

Lookback period of pool in seconds.

```solidity
function lookback() external view returns (uint256);
```

#### accessor <a href="#accessor" id="accessor"></a>

Address of Pool accessor. This is Zero address for permissionless pools.

```solidity
function accessor() external view returns (address);
```

#### tokenA <a href="#tokena" id="tokena"></a>

Pool tokenA. Address of tokenA is such that tokenA < tokenB.

```solidity
function tokenA() external view returns (IERC20);
```

#### tokenB <a href="#tokenb" id="tokenb"></a>

Pool tokenB.

```solidity
function tokenB() external view returns (IERC20);
```

#### factory <a href="#factory" id="factory"></a>

Deploying factory of the pool and also contract that has ability to set and collect protocol fees for the pool.

```solidity
function factory() external view returns (IMaverickV2Factory);
```

#### tokenAScale <a href="#tokenascale" id="tokenascale"></a>

Most significant bit of scale value is a flag to indicate whether tokenA has more or less than 18 decimals. Scale is used in conjuction with Math.toScale/Math.fromScale functions to convert from token amounts to D18 scale internal pool accounting.

```solidity
function tokenAScale() external view returns (uint256);
```

#### tokenBScale <a href="#tokenbscale" id="tokenbscale"></a>

Most significant bit of scale value is a flag to indicate whether tokenA has more or less than 18 decimals. Scale is used in conjuction with Math.toScale/Math.fromScale functions to convert from token amounts to D18 scale internal pool accounting.

```solidity
function tokenBScale() external view returns (uint256);
```

#### binIdByTickKind <a href="#binidbytickkind" id="binidbytickkind"></a>

ID of bin at input tick position and kind.

```solidity
function binIdByTickKind(int32 tick, uint256 kind) external view returns (uint32);
```

#### protocolFeeA <a href="#protocolfeea" id="protocolfeea"></a>

Accumulated tokenA protocol fee.

```solidity
function protocolFeeA() external view returns (uint128);
```

#### protocolFeeB <a href="#protocolfeeb" id="protocolfeeb"></a>

Accumulated tokenB protocol fee.

```solidity
function protocolFeeB() external view returns (uint128);
```

#### lendingFeeRateD18 <a href="#lendingfeerated18" id="lendingfeerated18"></a>

Lending fee rate on flash loans.

```solidity
function lendingFeeRateD18() external view returns (uint256);
```

#### getCurrentTwa <a href="#getcurrenttwa" id="getcurrenttwa"></a>

External function to get the current time-weighted average price.

```solidity
function getCurrentTwa() external view returns (int256);
```

#### getState <a href="#getstate" id="getstate"></a>

External function to get the state of the pool.

```solidity
function getState() external view returns (State memory);
```

#### getBin <a href="#getbin" id="getbin"></a>

Return state of Bin at input binId.

```solidity
function getBin(uint32 binId) external view returns (BinState memory bin);
```

#### getTick <a href="#gettick" id="gettick"></a>

Return state of Tick at input tick position.

```solidity
function getTick(int32 tick) external view returns (TickState memory tickState);
```

#### balanceOf <a href="#balanceof" id="balanceof"></a>

Retrieves the balance of a user within a bin.

```solidity
function balanceOf(address user, uint256 subaccount, uint32 binId) external view returns (uint128 lpToken);
```

**Parameters**

| Name         | Type      | Description                  |
| ------------ | --------- | ---------------------------- |
| `user`       | `address` | The user's address.          |
| `subaccount` | `uint256` | The subaccount for the user. |
| `binId`      | `uint32`  | The ID of the bin.           |

#### addLiquidity <a href="#addliquidity" id="addliquidity"></a>

Add liquidity to a pool. This function allows users to deposit tokens into a liquidity pool.

This function will call `maverickV2AddLiquidityCallback` on the calling contract to collect the tokenA/tokenB payment.

```solidity
function addLiquidity(address recipient, uint256 subaccount, AddLiquidityParams calldata params, bytes calldata data)
    external
    returns (uint256 tokenAAmount, uint256 tokenBAmount, uint32[] memory binIds);
```

**Parameters**

| Name         | Type                 | Description                                                                              |
| ------------ | -------------------- | ---------------------------------------------------------------------------------------- |
| `recipient`  | `address`            | The account that will receive credit for the added liquidity.                            |
| `subaccount` | `uint256`            | The account that will receive credit for the added liquidity.                            |
| `params`     | `AddLiquidityParams` | Parameters containing the details for adding liquidity, such as token types and amounts. |
| `data`       | `bytes`              | Bytes information that gets passed to the callback.                                      |

**Returns**

| Name           | Type       | Description                                        |
| -------------- | ---------- | -------------------------------------------------- |
| `tokenAAmount` | `uint256`  | The amount of token A added to the pool.           |
| `tokenBAmount` | `uint256`  | The amount of token B added to the pool.           |
| `binIds`       | `uint32[]` | An array of bin IDs where the liquidity is stored. |

#### removeLiquidity <a href="#removeliquidity" id="removeliquidity"></a>

Removes liquidity from the pool.

Liquidity can only be removed from a bin that is either unmerged or has a mergeId of an unmerged bin. If a bin is merged more than one level deep, it must be migrated up the merge stack to the root bin before liquidity removal.

```solidity
function removeLiquidity(address recipient, uint256 subaccount, RemoveLiquidityParams calldata params)
    external
    returns (uint256 tokenAOut, uint256 tokenBOut);
```

**Parameters**

| Name         | Type                    | Description                            |
| ------------ | ----------------------- | -------------------------------------- |
| `recipient`  | `address`               | The address to receive the tokens.     |
| `subaccount` | `uint256`               | The subaccount for the recipient.      |
| `params`     | `RemoveLiquidityParams` | The parameters for removing liquidity. |

**Returns**

| Name        | Type      | Description                     |
| ----------- | --------- | ------------------------------- |
| `tokenAOut` | `uint256` | The amount of token A received. |
| `tokenBOut` | `uint256` | The amount of token B received. |

#### migrateBinUpStack <a href="#migratebinupstack" id="migratebinupstack"></a>

Migrate bins up the linked list of merged bins so that its mergeId is the currrent active bin.

Liquidity can only be removed from a bin that is either unmerged or has a mergeId of an unmerged bin. If a bin is merged more than one level deep, it must be migrated up the merge stack to the root bin before liquidity removal.

```solidity
function migrateBinUpStack(uint32 binId, uint32 maxRecursion) external;
```

**Parameters**

| Name           | Type     | Description                                    |
| -------------- | -------- | ---------------------------------------------- |
| `binId`        | `uint32` | The ID of the bin to migrate.                  |
| `maxRecursion` | `uint32` | The maximum recursion depth for the migration. |

#### swap <a href="#swap" id="swap"></a>

Swap tokenA/tokenB assets in the pool. The swap user has two options for funding their swap.

* The user can push the input token amount to the pool before calling the swap function. In order to avoid having the pool call the callback, the user should pass a zero-length `data` bytes object with the swap call.
* The user can send the input token amount to the pool when the pool calls the `maverickV2SwapCallback` function on the calling contract. That callback has input parameters that specify the token address of the input token, the input and output amounts, and the bytes data sent to the swap function.

If the users elects to do a callback-based swap, the output assets will be sent before the callback is called, allowing the user to execute flash swaps. However, the pool does have reentrancy protection, so a swapper will not be able to interact with the same pool again while they are in the callback function.

```solidity
function swap(address recipient, SwapParams memory params, bytes calldata data)
    external
    returns (uint256 amountIn, uint256 amountOut);
```

**Parameters**

| Name        | Type         | Description                                         |
| ----------- | ------------ | --------------------------------------------------- |
| `recipient` | `address`    | The address to receive the output tokens.           |
| `params`    | `SwapParams` | Parameters containing the details of the swap       |
| `data`      | `bytes`      | Bytes information that gets passed to the callback. |

#### flashLoan <a href="#flashloan" id="flashloan"></a>

Loan tokenA/tokenB assets from the pool to recipient. The fee rate of a loan is determined by `lendingFeeRateD18`, which is set at the protocol level by the factory. This function calls `maverickV2FlashLoanCallback` on the calling contract. At the end of the callback, the caller must pay back the loan with fee (if there is a fee).

```solidity
function flashLoan(address recipient, uint256 amountA, uint256 amountB, bytes calldata data)
    external
    returns (uint128 lendingFeeA, uint128 lendingFeeB);
```

**Parameters**

| Name        | Type      | Description                                         |
| ----------- | --------- | --------------------------------------------------- |
| `recipient` | `address` | The address to receive the loaned tokens.           |
| `amountA`   | `uint256` |                                                     |
| `amountB`   | `uint256` | Loan amount of tokenA sent to recipient.            |
| `data`      | `bytes`   | Bytes information that gets passed to the callback. |

#### setFee <a href="#setfee" id="setfee"></a>

Sets fee for permissioned pools. May only be called by the accessor.

```solidity
function setFee(uint256 newFeeAIn, uint256 newFeeBIn) external;
```

### Events <a href="#events" id="events"></a>

#### PoolSwap <a href="#poolswap" id="poolswap"></a>

```solidity
event PoolSwap(address sender, address recipient, SwapParams params, uint256 amountIn, uint256 amountOut);
```

#### PoolAddLiquidity <a href="#pooladdliquidity" id="pooladdliquidity"></a>

```solidity
event PoolAddLiquidity(
    address sender,
    address recipient,
    uint256 subaccount,
    AddLiquidityParams params,
    uint256 tokenAAmount,
    uint256 tokenBAmount,
    uint32[] binIds
);
```

#### PoolMigrateBinsUpStack <a href="#poolmigratebinsupstack" id="poolmigratebinsupstack"></a>

```solidity
event PoolMigrateBinsUpStack(address sender, uint32 binId, uint32 maxRecursion);
```

#### PoolRemoveLiquidity <a href="#poolremoveliquidity" id="poolremoveliquidity"></a>

```solidity
event PoolRemoveLiquidity(
    address sender,
    address recipient,
    uint256 subaccount,
    RemoveLiquidityParams params,
    uint256 tokenAOut,
    uint256 tokenBOut
);
```

#### PoolSetVariableFee <a href="#poolsetvariablefee" id="poolsetvariablefee"></a>

```solidity
event PoolSetVariableFee(uint256 newFeeAIn, uint256 newFeeBIn);
```

### Errors <a href="#errors" id="errors"></a>

#### PoolZeroLiquidityAdded <a href="#poolzeroliquidityadded" id="poolzeroliquidityadded"></a>

```solidity
error PoolZeroLiquidityAdded();
```

#### PoolMinimumLiquidityNotMet <a href="#poolminimumliquiditynotmet" id="poolminimumliquiditynotmet"></a>

```solidity
error PoolMinimumLiquidityNotMet();
```

#### PoolLocked <a href="#poollocked" id="poollocked"></a>

```solidity
error PoolLocked();
```

#### PoolInvalidInput <a href="#poolinvalidinput" id="poolinvalidinput"></a>

```solidity
error PoolInvalidInput();
```

#### PoolInsufficientBalance <a href="#poolinsufficientbalance" id="poolinsufficientbalance"></a>

```solidity
error PoolInsufficientBalance(uint256 deltaLpAmount, uint256 accountBalance);
```

#### PoolReservesExceedMaximum <a href="#poolreservesexceedmaximum" id="poolreservesexceedmaximum"></a>

```solidity
error PoolReservesExceedMaximum(uint256 amount);
```

#### PoolValueExceedsBits <a href="#poolvalueexceedsbits" id="poolvalueexceedsbits"></a>

```solidity
error PoolValueExceedsBits(uint256 amount, uint256 bits);
```

#### PoolTickMaxExceeded <a href="#pooltickmaxexceeded" id="pooltickmaxexceeded"></a>

```solidity
error PoolTickMaxExceeded(uint256 tick);
```

#### PoolMigrateBinFirst <a href="#poolmigratebinfirst" id="poolmigratebinfirst"></a>

```solidity
error PoolMigrateBinFirst();
```

#### PoolCurrentTickBeyondSwapLimit <a href="#poolcurrenttickbeyondswaplimit" id="poolcurrenttickbeyondswaplimit"></a>

```solidity
error PoolCurrentTickBeyondSwapLimit(int32 startingTick);
```

#### PoolSenderNotAccessor <a href="#poolsendernotaccessor" id="poolsendernotaccessor"></a>

```solidity
error PoolSenderNotAccessor(address sender_, address accessor);
```

#### PoolSenderNotFactory <a href="#poolsendernotfactory" id="poolsendernotfactory"></a>

```solidity
error PoolSenderNotFactory(address sender_, address accessor);
```

#### PoolFunctionNotImplemented <a href="#poolfunctionnotimplemented" id="poolfunctionnotimplemented"></a>

```solidity
error PoolFunctionNotImplemented();
```

#### PoolTokenNotSolvent <a href="#pooltokennotsolvent" id="pooltokennotsolvent"></a>

```solidity
error PoolTokenNotSolvent(uint256 internalReserve, uint256 tokenBalance, IERC20 token);
```

### Structs <a href="#structs" id="structs"></a>

#### TickState <a href="#tickstate" id="tickstate"></a>

Tick state parameters.

```solidity
struct TickState {
    uint128 reserveA;
    uint128 reserveB;
    uint128 totalSupply;
    uint32[4] binIdsByTick;
}
```

#### TickData <a href="#tickdata" id="tickdata"></a>

Tick data parameters.

```solidity
struct TickData {
    uint256 currentReserveA;
    uint256 currentReserveB;
    uint256 currentLiquidity;
}
```

**Properties**

| Name               | Type      | Description                 |
| ------------------ | --------- | --------------------------- |
| `currentReserveA`  | `uint256` | Current reserve of token A. |
| `currentReserveB`  | `uint256` | Current reserve of token B. |
| `currentLiquidity` | `uint256` | Current liquidity amount.   |

#### BinState <a href="#binstate" id="binstate"></a>

Bin state parameters.

```solidity
struct BinState {
    uint128 mergeBinBalance;
    uint128 tickBalance;
    uint128 totalSupply;
    uint8 kind;
    int32 tick;
    uint32 mergeId;
}
```

**Properties**

| Name              | Type      | Description                                                |
| ----------------- | --------- | ---------------------------------------------------------- |
| `mergeBinBalance` | `uint128` | LP token balance that this bin possesses of the merge bin. |
| `tickBalance`     | `uint128` | Balance of the tick.                                       |
| `totalSupply`     | `uint128` | Total amount of LP tokens in this bin.                     |
| `kind`            | `uint8`   | One of the 4 kinds (0=static, 1=right, 2=left, 3=both).    |
| `tick`            | `int32`   | The lower price tick of the bin in its current state.      |
| `mergeId`         | `uint32`  | Bin ID of the bin that this bin has merged into.           |

#### SwapParams <a href="#swapparams" id="swapparams"></a>

Parameters for swap.

```solidity
struct SwapParams {
    uint256 amount;
    bool tokenAIn;
    bool exactOutput;
    int32 tickLimit;
}
```

**Properties**

| Name          | Type      | Description                                                                                                                                                                            |
| ------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `amount`      | `uint256` | Amount of the token that is either the input if exactOutput is false or the output if exactOutput is true.                                                                             |
| `tokenAIn`    | `bool`    | Boolean indicating whether tokenA is the input.                                                                                                                                        |
| `exactOutput` | `bool`    | Boolean indicating whether the amount specified is the exact output amount (true).                                                                                                     |
| `tickLimit`   | `int32`   | The furthest tick a swap will execute in. If no limit is desired, value should be set to type(int32).max for a tokenAIn swap and type(int32).min for a swap where tokenB is the input. |

#### AddLiquidityParams <a href="#addliquidityparams" id="addliquidityparams"></a>

Parameters associated with adding liquidity.

```solidity
struct AddLiquidityParams {
    uint8 kind;
    int32[] ticks;
    uint128[] amounts;
}
```

**Properties**

| Name      | Type        | Description                                             |
| --------- | ----------- | ------------------------------------------------------- |
| `kind`    | `uint8`     | One of the 4 kinds (0=static, 1=right, 2=left, 3=both). |
| `ticks`   | `int32[]`   | Array of ticks to add liquidity to.                     |
| `amounts` | `uint128[]` | Array of bin LP amounts to add.                         |

#### RemoveLiquidityParams <a href="#removeliquidityparams" id="removeliquidityparams"></a>

Parameters for each bin that will have liquidity removed.

```solidity
struct RemoveLiquidityParams {
    uint32[] binIds;
    uint128[] amounts;
}
```

**Properties**

| Name      | Type        | Description                               |
| --------- | ----------- | ----------------------------------------- |
| `binIds`  | `uint32[]`  | Index array of the bins losing liquidity. |
| `amounts` | `uint128[]` | Array of bin LP amounts to remove.        |

#### State <a href="#state" id="state"></a>

State of the pool.

```solidity
struct State {
    uint128 reserveA;
    uint128 reserveB;
    int64 lastTwaD8;
    int64 lastLogPriceD8;
    uint40 lastTimestamp;
    int32 activeTick;
    bool isLocked;
    uint32 binCounter;
    uint8 protocolFeeRatioD3;
}
```

**Properties**

| Name                 | Type      | Description                                                                                                                                                                                                 |
| -------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `reserveA`           | `uint128` | Pool tokenA balanceOf at end of last operation                                                                                                                                                              |
| `reserveB`           | `uint128` | Pool tokenB balanceOf at end of last operation                                                                                                                                                              |
| `lastTwaD8`          | `int64`   | Value of log time weighted average price at last block. Value is 8-decimal scale and is in the fractional tick domain. E.g. a value of 12.3e8 indicates the TWAP was 3/10ths of the way into the 12th tick. |
| `lastLogPriceD8`     | `int64`   | Value of log price at last block. Value is 8-decimal scale and is in the fractional tick domain. E.g. a value of 12.3e8 indicates the price was 3/10ths of the way into the 12th tick.                      |
| `lastTimestamp`      | `uint40`  | Last block.timestamp value in seconds for latest swap transaction.                                                                                                                                          |
| `activeTick`         | `int32`   | Current tick position that contains the active bins.                                                                                                                                                        |
| `isLocked`           | `bool`    | Pool isLocked, E.g., locked or unlocked; isLocked values defined in Pool.sol.                                                                                                                               |
| `binCounter`         | `uint32`  | Index of the last bin created.                                                                                                                                                                              |
| `protocolFeeRatioD3` | `uint8`   | Ratio of the swap fee that is kept for the protocol.                                                                                                                                                        |

#### BinDelta <a href="#bindelta" id="bindelta"></a>

Internal data used for data passing between Pool and Bin code.

```solidity
struct BinDelta {
    uint128 deltaA;
    uint128 deltaB;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.mav.xyz/technical-reference/maverick-v2/v2-contracts/maverick-v2-common-contracts/interfaces/imaverickv2pool.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
