> For the complete documentation index, see [llms.txt](https://docs.mav.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mav.xyz/technical-reference/maverick-v1/v1-contracts/pool.md).

# Pool

### **Table of Contents**

* [**Contract Details**](#contract-details)
* [**Events**](#events)
  * [Swap](#event-swap)
  * [AddLiquidity](#event-addliquidity)
  * [MigrateBinsUpStack](#event-migratebinsupstack)
  * [TransferLiquidity](#event-transferliquidity)
  * [RemoveLiquidity](#event-removeliquidity)
  * [BinMerged](#event-binmerged)
  * [BinMoved](#event-binmoved)
  * [ProtocolFeeCollected](#event-protocolfeecollected)
  * [SetProtocolFeeRatio](#event-setprotocolfeeratio)
* [**Structs**](#structs)
  * [BinDelta](#struct-bindelta)
  * [TwaState](#struct-twastate)
  * [BinState](#struct-binstate)
  * [AddLiquidityParams](#struct-addliquidityparams)
  * [RemoveLiquidityParams](#struct-removeliquidityparams)
  * [State](#struct-state)
* [**Functions**](#functions)
  * [fee()](#fn-fee)
  * [tickSpacing()](#fn-tickspacing)
  * [tokenA()](#fn-tokena)
  * [tokenB()](#fn-tokenb)
  * [factory()](#fn-factory)
  * [binMap()](#fn-binmap)
  * [binPositions()](#fn-binpositions)
  * [binBalanceA()](#fn-binbalancea)
  * [binBalanceB()](#fn-binbalanceb)
  * [getTwa()](#fn-gettwa)
  * [getCurrentTwa()](#fn-getcurrenttwa)
  * [getState()](#fn-getstate)
  * [addLiquidity()](#fn-addliquidity)
  * [transferLiquidity()](#fn-transferliquidity)
  * [removeLiquidity()](#fn-removeliquidity)
  * [migrateBinUpStack()](#fn-migratebinupstack)
  * [swap()](#fn-swap)
  * [getBin()](#fn-getbin)
  * [balanceOf()](#fn-balanceof)
  * [tokenAScale()](#fn-tokenascale)
  * [tokenBScale()](#fn-tokenbscale)

## **Contract Details** <a href="#contract-details" id="contract-details"></a>

* **Name :** *IPool*
* **Solidity Version :** *^0.8.0*
* *SPDX License-Identifier : GPL-2.0-or-later*
* Code: [Github](https://github.com/maverickprotocol/maverick-v1-interfaces/blob/main/contracts/interfaces/IPool.sol)

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

### Swap <a href="#event-swap" id="event-swap"></a>

```solidity
event Swap(address sender, address recipient, bool tokenAIn, bool exactOutput, uint256 amountIn, uint256 amountOut, int32 activeTick);
```

* `sender` : The `address` that executed this swap
* `recipient` : The `address` receiving this swap
* `tokenAIn` : A `boolean` to determine if there is any input for Token A
* `exactOutput` : A `boolean` to determine if there is any exact amount of tokens expected to receive
* `amountIn` : The `uint256` amount of the input token
* `amountOut` : The `uint256` amount of the output token
* `activeTick` : The active tick `int32` value for the pool

### AddLiquidity <a href="#event-addliquidity" id="event-addliquidity"></a>

```solidity
event AddLiquidity(address indexed sender, uint256 indexed tokenId, BinDelta[] binDeltas);
```

* `sender` : The indexed sender `address` that executed `addLiquidity()`
* `tokenId` : The `uint256` indexed ID of the receiving token
* `binDeltas` : An array of `BinDelta` structures

### MigrateBinsUpStack <a href="#event-migratebinsupstack" id="event-migratebinsupstack"></a>

```solidity
event MigrateBinsUpStack(address indexed sender, uint128 binId, uint32 maxRecursion);
```

* `sender` : The indexed sender `address` that executed `MigrateBinsUpStack()`
* `binId` : The `uint128` bin ID that was migrated
* `maxRecursion` : Maximum recursion depth in `uint32`

### TransferLiquidity <a href="#event-transferliquidity" id="event-transferliquidity"></a>

```solidity
event TransferLiquidity(uint256 fromTokenId, uint256 toTokenId, RemoveLiquidityParams[] params);
```

* `fromTokenId` : Transfer liquidity from token ID `uint256`
* `toTokenId` : Transfer liquidity to token ID `uint256`
* `params` : Array of `RemoveLiquidityParams` that specify the bins and amounts

### RemoveLiquidity <a href="#event-removeliquidity" id="event-removeliquidity"></a>

```solidity
event RemoveLiquidity(address indexed sender, address indexed recipient, uint256 indexed tokenId, BinDelta[] binDeltas);
```

* `sender` : Remove liquidity from sender `address`
* `recipient` : Remove liquidity to receiver `address`
* `tokenId` : Current indexed `uint256` tokenId to remove liquidity from
* `binDeltas` : Array of `BinDelta` that specify the bins and amounts

### BinMerged <a href="#event-binmerged" id="event-binmerged"></a>

```solidity
event BinMerged(uint128 indexed binId, uint128 reserveA, uint128 reserveB, uint128 mergeId);
```

* `binId` : The indexed bin ID `uint128` that was merged.
* `reserveA` : amount of A token `uint128` in bin.
* `reserveB` : amount of B token `uint128` in bin.
* `mergeId` : The current active bin `uint128`.

### BinMoved <a href="#event-binmoved" id="event-binmoved"></a>

```solidity
event BinMoved(uint128 indexed binId, int128 previousTick, int128 newTick);
```

* `binId` : The indexed bin ID `uint128` that was moved.
* `previousTick` : Previous tick value in `int128`.
* `newTick` : New tick value in `uint128`.

### ProtocolFeeCollected <a href="#event-protocolfeecollected" id="event-protocolfeecollected"></a>

```solidity
event ProtocolFeeCollected(uint256 protocolFee, bool isTokenA);
```

* `protocolFee` : Amount of Protocol fee collected in `uint256`.
* `isTokenA` : `boolean` check if Token A was used for Protocol fee.

### SetProtocolFeeRatio <a href="#event-setprotocolfeeratio" id="event-setprotocolfeeratio"></a>

```solidity
event SetProtocolFeeRatio(uint256 protocolFee);
```

* `protocolFee` : The new amount of Protocol fee set in `uint256`.

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

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

Return parameters for Add/Remove liquidity.

```solidity
struct BinDelta {
        uint128 deltaA;
        uint128 deltaB;
        uint256 deltaLpBalance;
        uint128 binId;
        uint8 kind;
        int32 lowerTick;
        bool isActive;
    }
```

* `deltaA` : The amount of A token `uint128` that has been added or removed
* `deltaB` : The amount of B token `uint128` that has been added or removed
* `deltaLpBalance` : The amount of LP balance `uint256` that has increase *(add)* or decreased *(remove)*
* `binId` : The bin ID `uint128` of the bin that changed
* `kind` : One of the 4 Kinds *(0=static, 1=right, 2=left, 3=both)* in `uint8`
* `lowerTick` : The lower price tick `int32` of the bin in its current state
* `isActive` : A `boolean` to indicate whether the bin is still active

### TwaState <a href="#struct-twastate" id="struct-twastate"></a>

Time weighted average state.

```solidity
    struct TwaState {
        int96 twa;
        int96 value;
        uint64 lastTimestamp;
    }
```

* `twa` : The twa `int96` at the last update instant
* `value` : The new value `int96` that was passed in at the last update
* `lastTimestamp` : The timestamp `uint64` of the last update in seconds

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

The bin state parameters.

```solidity
    struct BinState {
        uint128 reserveA;
        uint128 reserveB;
        uint128 mergeBinBalance;
        uint128 mergeId;
        uint128 totalSupply;
        uint8 kind;
        int32 lowerTick;
    }
```

* `reserveA` : The amount of A token `uint128` in bin
* `reserveB` : The amount of B token `uint128` in bin
* `mergeBinBalance` : The LP token balance `uint128` that this bin possesses after merge
* `mergeId` : The `binId` that this bin `uint128` has merged in to
* `totalSupply` : The total amount of LP tokens `uint128` in this bin
* `kind` : one of the 4 Kinds *(0=static, 1=right, 2=left, 3=both)* in `uint8`
* `lowerTick` : The lower price tick `int32` of the bin in its current state

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

Parameters for each bin that will get new liquidity.

```solidity
    struct AddLiquidityParams {
        uint8 kind;
        int32 pos;
        bool isDelta;
        uint128 deltaA;
        uint128 deltaB;
    }
```

* `kind` : one of the 4 Kinds *(0=static, 1=right, 2=left, 3=both)* in `uint8`
* `pos` : The bin position in `int32`
* `isDelta` : A `boolean` that indicates whether the bin position is relative to the current bin or an absolute position
* `deltaA` : The amount of A token `uint128` to add
* `deltaB` : The amount of B token `uint128` to add

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

Parameters for each bin that will have liquidity removed.

```solidity
    struct RemoveLiquidityParams {
        uint128 binId;
        uint128 amount;
    }
```

* `binId` : The index of the bin `uint128` losing liquidity
* `amount` : The LP balance amount `uint128` to remove

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

The state of the pool.

```solidity
    struct State {
        int32 activeTick;
        uint8 status;
        uint128 binCounter;
        uint64 protocolFeeRatio;
    }
```

* `activeTick` : The current bin position `int32` that contains the active bins
* `status` : The status values `uint8` defined in `Pool.sol` *e.g. locked or unlocked;*
* `binCounter` : The index `uint128` of the last bin created
* `protocolFeeRatio` : The ratio of the swap fee that is kept for the protocol in `uint64`

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

### fee() <a href="#fn-fee" id="fn-fee"></a>

Retrieves the fee for the pool in 18 decimal format.

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

* Returns :
  * The fee `uint256` for the pool as a uint256 value

### tickSpacing() <a href="#fn-tickspacing" id="fn-tickspacing"></a>

Retrieves the tick spacing of the pool. The tick spacing is used to calculate the bin width.

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

* Returns :
  * The tick spacing as a `uint256` value

### tokenA() <a href="#fn-tokena" id="fn-tokena"></a>

Retrieves the address of token A associated with the pool.

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

* Returns :
  * The `address` of token A as an IERC20 interface

### tokenB() <a href="#fn-tokenb" id="fn-tokenb"></a>

Retrieves the address of token B associated with the pool.

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

* Returns :
  * The `address` of token B as an IERC20 interface

### factory() <a href="#fn-factory" id="fn-factory"></a>

Retrieves the address of the factory contract associated with the pool.

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

* Returns :
  * The `address` of the factory contract as an `IFactory` interface

### binMap() <a href="#fn-binmap" id="fn-binmap"></a>

Retrieves the bitmap of active bins at the given tick.

```solidity
function binMap(int32 tick) external view returns (uint256);
```

* Parameters :
  * tick : The tick `int32` for which to retrieve the active bin map
* Returns :
  * The bitmap of active bins as a `uint256` value

### binPositions() <a href="#fn-binpositions" id="fn-binpositions"></a>

Retrieves the bin ID for the given tick and bin kind

```solidity
function binPositions(int32 tick, uint256 kind) external view returns (uint128);
```

* Parameters:
  * `tick`: The tick `int32` for which to retrieve the bin ID
  * `kind`: The kind `uint256` of the bin *(0=static, 1=right, 2=left, 3=both)*
* Returns:
  * The bin ID as a uint128 value

### binBalanceA() <a href="#fn-binbalancea" id="fn-binbalancea"></a>

Retrieves the internal accounting of the sum of token A balances across bins.

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

* Returns: The sum of token A balances as a `uint128` value

### binBalanceB() <a href="#fn-binbalanceb" id="fn-binbalanceb"></a>

Retrieves the internal accounting of the sum of token B balances across bins.

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

* Returns:
  * The sum of token B balances as a `uint128` value

### getTwa() <a href="#fn-gettwa" id="fn-gettwa"></a>

Retrieves the time-weighted average (TWA) state values.

```solidity
function getTwa() external view returns (TwaState memory);
```

* Returns:
  * A `TwaState` structure containing the TWA, value, last timestamp, and look back

### getCurrentTwa() <a href="#fn-getcurrenttwa" id="fn-getcurrenttwa"></a>

Retrieves the log base binWidth of the time-weighted average price.

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

* Returns:
  * The log base binWidth of the TWA as an `int256` value.

### getState() <a href="#fn-getstate" id="fn-getstate"></a>

Retrieves the state of the pool.

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

* Returns:
  * A `State` structure containing the active tick, status, bin counter, and protocol fee ratio

### addLiquidity() <a href="#fn-addliquidity" id="fn-addliquidity"></a>

Adds liquidity to a pool.

```solidity
function addLiquidity(uint256 tokenId, AddLiquidityParams[] calldata params, bytes calldata data)
    external
    returns (uint256 tokenAAmount, uint256 tokenBAmount, BinDelta[] memory binDeltas);
```

* Parameters:
  * `tokenId`: The NFT token ID `uint256` that will hold the position.
  * `params`: An array of `AddLiquidityParams` structures that specify the mode, position, and liquidity details.
  * `data`: A callback function that `addLiquidity` will call to transfer tokens.
* Returns:
  * `tokenAAmount`: The amount of token A added as a `uint256` value.
  * `tokenBAmount`: The amount of token B added as a `uint256` value.
  * `binDeltas`: An array of `BinDelta` structures representing the changes in bin states.

### transferLiquidity() <a href="#fn-transferliquidity" id="fn-transferliquidity"></a>

Transfers liquidity from one NFT token ID to another using an array of bins.

```solidity
function transferLiquidity(uint256 fromTokenId, uint256 toTokenId, RemoveLiquidityParams[] calldata params) external;
```

* Parameters:
  * `fromTokenId`: The NFT token ID `uint256` that holds the position being transferred.
  * `toTokenId`: The NFT token ID `uint256` that is receiving the liquidity.
  * `params`: An array of `RemoveLiquidityParams` structures specifying the bins and amounts to transfer.

### removeLiquidity() <a href="#fn-removeliquidity" id="fn-removeliquidity"></a>

Removes liquidity from a pool.

```solidity
function removeLiquidity(address recipient, uint256 tokenId, RemoveLiquidityParams[] calldata params)
    external
    returns (uint256 tokenAOut, uint256 tokenBOut, BinDelta[] memory binDeltas);
```

* Parameters:
  * `recipient`: The `address` that will receive the removed tokens.
  * `tokenId`: The NFT token ID `uint256` that holds the position being removed.
  * `params`: An array of `RemoveLiquidityParams` structures specifying the bins and amounts to remove.
* Returns:
  * `tokenAOut`: The amount of token A `uin256` received as a result of removing liquidity.
  * `tokenBOut`: The amount of token B `uin256` received as a result of removing liquidity.
  * `binDeltas`: An array of `BinDelta` structures representing the changes in bin states.

### migrateBinUpStack() <a href="#fn-migratebinupstack" id="fn-migratebinupstack"></a>

Migrates bins up the linked list of merged bins so that its mergeId is the current active bin.

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

* Parameters:
  * `binId`: An array of the bin IDs `uint128` to be migrated.
  * `maxRecursion`: The maximum recursion depth `uint32` of the migration. Set to `zero` to recurse until the active bin is found.

### swap() <a href="#fn-swap" id="fn-swap"></a>

Swaps tokens.

```solidity
function swap(
    address recipient,
    uint256 amount,
    bool tokenAIn,
    bool exactOutput,
    uint256 sqrtPriceLimit,
    bytes calldata data
) external returns (uint256 amountIn, uint256 amountOut);
```

* Parameters:
  * `recipient`: The `address` that will receive the output tokens.
  * `amount`: The amount of tokens `uint256` to swap.
  * `tokenAIn`: A `boolean` indicating whether token A is the input.
  * `exactOutput`: A `boolean` indicating whether the amount specified is the exact output amount *(true)*.
  * `sqrtPriceLimit`: The limiting square root price `uint256` of the swap. A value of `0` indicates no limit. The limit is only engaged for `exactOutput=false`. If the limit is reached, only part of the input amount will be swapped, and the callback will only require that amount of the swap to be paid.
  * `data`: A callback function `bytes` that swap will call to transfer tokens.
* Returns:
  * `amountIn`: The amount of tokens `uint256` swapped as input.
  * `amountOut`: The amount of tokens `uint256` received as output.

### getBin() <a href="#fn-getbin" id="fn-getbin"></a>

Retrieves the bin information for a given bin ID.

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

* Parameters:
  * `binId`: The index of the bin `uint128`.
* Returns:
  * A `BinState` structure containing the details of the bin.

### balanceOf() <a href="#fn-balanceof" id="fn-balanceof"></a>

Retrieves the LP token balance for a given tokenId at a specific binId.

```solidity
function balanceOf(uint256 tokenId, uint128 binId) external view returns (uint256 lpToken);
```

* Parameters:
  * `tokenId`: The NFT token ID `uint256`.
  * `binId`: The index of the bin `uint128`.
* Returns:
  * The LP token balance as a `uint256` value.

### tokenAScale() <a href="#fn-tokenascale" id="fn-tokenascale"></a>

Retrieves the tokenA scale value.

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

> `msb` 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.

* Returns:
  * The tokenA scale value as a `uint256`.

### tokenBScale() <a href="#fn-tokenbscale" id="fn-tokenbscale"></a>

Retrieves the tokenB scale value.

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

> `msb` 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.

* Returns:
  * The tokenB scale value as a `uint256`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.mav.xyz/technical-reference/maverick-v1/v1-contracts/pool.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
