> For the complete documentation index, see [llms.txt](https://tapp-exchange.gitbook.io/tapp-exchange/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tapp-exchange.gitbook.io/tapp-exchange/developer-docs/sdk.md).

# SDK Reference

A fully typed, modular **TypeScript SDK** for interacting with the **TAPP Decentralized Exchange** on the **Aptos blockchain**.

This SDK simplifies tasks such as:

* Pool discovery and querying
* Swaps (AMM, CLMM, Stable pools)
* Creating, adding and removing liquidity (AMM, CLMM, Stable pools)
* Collecting fees

## 📚 Table of Contents

* [Installation](#installation)
* [Initialization](#initialization)
* [Pool](#pool)
* [Swap](#swap)
* [Liquidity](#liquidity)
  * [Create Pool and Add Liquidity](#create-pool-and-add-liquidity)
  * [Add Liquidity to existing pools](#add-liquidity-to-existing-pools)
  * [Remove Liquidity](#remove-liquidity)
* [Collect Fee](#collect-fee)
* [Position](#position)

***

## Installation

```bash
npm install @tapp-exchange/sdk
```

## Initialization

The Tapp TypeScript SDK provides a convenient helper function `initTappSDK` to initialize the SDK. ***(Currently only supports MAINNET)***

```ts
import { initTappSDK } from '@tapp-exchange/sdk';
import { Network } from '@aptos-labs/ts-sdk';

const sdk = initTappSDK({
    network: Network.MAINNET, // optional. Default: MAINNET 
    url: 'https://....' // optional. 
});
```

## Pool

### Get Pool List

Fetches a paginated list of available pools, optionally sorted by TVL or other fields.

Use `sdk.Pool.getPools` method.

**Available params**

* `page`: `number` The page number to fetch (defaults to 1).
* `size`: `number` Number of items per page (defaults to 10).
* `sortBy`: `string` Field to sort by (defaults to "tvl").
* `type`: `string` Optional pool type filter. (AMM, CLMM, STABLE)

```ts
const pools = await sdk.Pool.getPools({
  page: 1, 
  size: 10,
  sortBy: 'tvl',
});
```

### Get Specific Pool Info

Retrieves detailed information about a specific pool by its ID.

```ts
const info = await sdk.Pool.getInfo('0xpoolid');
```

## Swap

### Estimate Swap Amount

Estimates the amount received or needed for a swap, depending on input direction.

**Params**

* `amount`: `number` The amount for estimation (used as input or desired output depending on `field`).
* `poolId`: `string` The identifier of the pool.
* `pair`: `[number, number]` A tuple of token indexes to swap, e.g., `[0, 1]` means token at index 0 is being swapped for token at index 1.
* `a2b`: `boolean` Swap direction — `true` for token at `pair[0]` to `pair[1]`, `false` for `pair[1]` to `pair[0]`.
* `field` (optional): `input | output` Indicates if `amount` is an `"input"` or `"output"` amount (defaults to `"input"`).

```ts
const getEstSwap = async () => {
    const result = await sdk.Swap.getEstSwapAmount({
        poolId: "0xpool",
        a2b: true,
        field: 'input', // input or output
        amount: 1000000000,
        pair: [0, 1]
    });
    
    if(result.error instanceof TradeSizeExceedsError) {
        console.error(result.error.message)
        console.error('max allowed amount', result.error.maxAmountIn);
    }

    console.log(result);
};
```

### Get Swap Route

Retrieves the pool route information between two tokens.

Use `sdk.Swap.getRoute` method

**Example**

```ts
async function getRoute() {
    const token0 = '0xtoken1'
    const token1 = '0xtoken2'
    const poolInfo = await sdk.Swap.getRoute(token0, token1);

    console.log(poolInfo)
}
```

### AMM Swap

Creates a swap payload for an AMM pool

Use `sdk.Swap.swapAMMTransactionPayload` method

**Params:**

* `poolId`: `string` The address of the pool in which the swap is performed.
* `a2b`: `boolean` Direction of the swap; `true` for token A to B, `false` for B to A.
* `fixedAmountIn`: `boolean` Whether the input amount is fixed (defaults to `true`).
* `amount0`: `number` Amount of token A.
* `amount1`: `number` Amount of token B.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function swapAMM() {
    const params: SwapAMMParams = {
        poolId: '0xpool',
        a2b: true,
        fixedAmountIn: true,
        amount0: 100000000,
        amount1: 10000000,
    }
    const data = sdk.Swap.swapAMMTransactionPayload(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

### CLMM Swap

Creates a swap payload for a CLMM pool

**Params:**

* `poolId`: `string` The address of the CLMM pool.
* `amountIn`: `number` The input token amount for the swap.
* `minAmountOut`: `number` The minimum acceptable output amount.
* `a2b`: `boolean` Direction of the swap; `true` for token A to B, `false` for B to A.
* `fixedAmountIn`: `boolean` Indicates whether `amountIn` is fixed (`true`).
* `targetSqrtPrice`: `number` The target square root price.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function swapCLMM() {
    const params: SwapCLMMParams = {
        poolId: '0xpool',
        amountIn: 100000000,
        minAmountOut: 521850658,
        a2b: true,
        fixedAmountIn: true,
        targetSqrtPrice: 4295048016
    }
    const data = sdk.Swap.swapCLMMTransactionPayload(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

### Stable Swap

Creates a swap payload for a Stable pool

**Params:**

* `poolId`: `string` The address of the Stable pool.
* `tokenIn`: `number` The Index of the token to swap from.
* `tokenOut`: `number` The Index of the token to swap to.
* `amountIn`: `number` The input token amount for the swap.
* `minAmountOut`: `number` The minimum amount of output tokens.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function swapStable() {
    const params: SwapStableParams = {
        poolId: "0xpool",
        tokenIn: 2,
        tokenOut: 3,
        amountIn: 100000000,
        minAmountOut: 0,
    }
    const data = sdk.Swap.swapStableTransactionPayload(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

## Liquidity

### Create Pool and Add Liquidity

#### AMM

Creates an AMM pool and adds initial liquidity.

**Params**

* `tokenAddress`: `string[]` An array of token addresses.
* `fee`: `number` The fee traders will pay to use your pool's liquidity.
* `amounts`: `number[]` The initial token amounts.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function createAMMPoolAndAddLiquidity() {
    const params: CreateAMMPoolAndAddLiquidityParams = {
        tokenAddress: ['0xtoken1', '0xtoken2'],
        fee: 3000,
        amounts: [20000000000, 30000000000],
    }
    const data = sdk.Position.createAMMPoolAndAddLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

#### CLMM

Creates a CLMM pool and adds initial liquidity.

**Params:**

* `tokenAddress`: `string[]` An array of token addresses.
* `fee`: `number` The fee traders will pay to Use your pool's liquidity.
* `amounts`: `number[]` The initial token amounts.
* `initialPrice`: `number` Starting price for liquidity.
* `minPrice`: `number` The lower bound price of the liquidity range.
* `maxPrice`: `number` The upper bound price of the liquidity range.
* `isMaxAmountB`: `number` Whether the second token amount (`amountB`) is flexible based on slippage.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function createCLMMPoolAndAddLiquidity() {
    const params: CreateCLMMPoolAndAddLiquidityParams = {
        tokenAddress: ['0xtoken1', '0xtoken2'],
        fee: 3000,
        amounts: [10000000000, 10000000000],
        initialPrice: 1,
        minPrice: 0.000001,
        maxPrice: Infinity,
        isMaxAmountB: true,
    }
    const data = sdk.Position.createCLMMPoolAndAddLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

#### Stable

Creates a Stable pool and adds initial liquidity.

**Params:**

* `tokenAddress`: `string[]` An array of token addresses.
* `fee`: `number` The fee traders will pay to Use your pool's liquidity.
* `amounts`: `number[]` The initial token amounts.
* `amplificationFactor`: `number` Amplification factor.
* `offpeg_fee_multiplier`: `number` Optional. Multiplier applied to fee when assets are off-peg. Defaults to `20_000_000_000`.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function createStablePoolAndAddLiquidity() {
    const params: CreateStablePoolAndAddLiquidityParams = {
        tokenAddress: ['0xtoken1', '0xtoken2', '0xtoken3'],
        fee: 500,
        amounts: [20000000000, 10000000000, 2000000000],
        amplificationFactor: 1000,
    }
    const data = sdk.Position.createStablePoolAndAddLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

***

### Remove Liquidity

#### AMM

Removes liquidity from single or multiple AMM positions.

**Single** **Params:**

* `poolId`: `string` The ID of the AMM pool.
* `positionAddr`: `string` The address of the liquidity position.
* `mintedShare`: `number` The amount of share tokens to burn.
* `minAmount0`: `number` Minimum amount of token0.
* `minAmount1`: `number` Minimum amount of token1.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeSingleAMMLiquidity() {
    const params: RemoveSingleAMMLiquidityParams = {
        poolId: '0xpool',
        positionAddr: '0xposition',
        mintedShare: 10000,
        minAmount0: 10000,
        minAmount1: 10000,
    }
    const data = sdk.Position.removeSingleAMMLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

**Multiple** **Params:**

* `poolId`: The ID of the pool.
* `positions`: An array of position objects, each containing:
  * `positionAddr`: The address of the liquidity position.
  * `mintedShare`: The amount of share tokens to burn.
  * `minAmount0`: Minimum amount token0.
  * `minAmount1`: Minimum amount token1.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeMultipleAMMLiquidity() {
    const params: RemoveMultipleAMMLiquidityParams = {
        poolId: '0xpool',
        positions: [
            {
                positionAddr: '0xposition1',
                mintedShare: 10000,
                minAmount0: 10000,
                minAmount1: 10000,
            },
            {
                positionAddr: '0xposition2',
                mintedShare: 20000,
                minAmount0: 20000,
                minAmount1: 20000,
            }
        ]
    }
    const data = sdk.Position.removeMultipleAMMLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

#### CLMM

Removes liquidity from single or multiple CLMM positions.

**Single** Use `sdk.Position.removeSingleCLMMLiquidity` method

**Params:**

* `poolId`: `string` The ID of the CLMM pool.
* `positionAddr`: `string` The address of the liquidity position.
* `mintedShare`: `number` The amount of share tokens to burn.
* `minAmount0`: `number` Minimum amount of token0.
* `minAmount1`: `number` Minimum amount of token1.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeSingleCLMMLiquidity() {
    const params: RemoveSingleCLMMLiquidityParams = {
        poolId: '0xpool',
        positionAddr: '0xposition',
        mintedShare: 10000,
        minAmount0: 10000,
        minAmount1: 10000,
    }
    const data = sdk.Position.removeSingleCLMMLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

**Multiple**

Use `sdk.Position.removeMultipleCLMMLiquidity` method

**Params:**

* `poolId`: `string` The ID of the CLMM pool.
* `positions`: An array of objects, each describing a position with:
  * `positionAddr`: `string` The address of the liquidity position.
  * `mintedShare`: `number` The amount of share tokens to burn.
  * `minAmount0`: `number` Minimum amount of token0.
  * `minAmount1`: `number` Minimum amount of token1.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeMultipleCLMMLiquidity() {
    const params: RemoveMultipleCLMMLiquidityParams = {
        poolId: '0xpool',
        positions: [
            {
                positionAddr: '0xposition1',
                mintedShare: 10000,
                minAmount0: 10000,
                minAmount1: 10000,
            },
            {
                positionAddr: '0xposition2',
                mintedShare: 20000,
                minAmount0: 20000,
                minAmount1: 20000,
            }
        ]
    }
    const data = sdk.Position.removeMultipleCLMMLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

#### Stable

Removes liquidity from single or multiple STABLE positions.

There are 3 types when removing liquidity:

* Remove Liquidity One Coin (type = 0) When you want to remove all liquidity and get 1 coin in return, please use this type. Specify the token index for the token you want to retrieve.
* Remove Liquidity Imbalance (type = 1) When you want to remove liquidity and retrieve a specific amount for each coin index, please use this type. When using this type, you need to pass the maximum liquidity amount that you want to burn.
* Remove Liquidity Ratio (type = 2) Use this type when you want to retrieve amounts based on the current pool liquidity ratio.

**Single**

Use `sdk.Position.removeSingleStableLiquidity` method

**Params:**

* `poolId`: `string` The ID of the stable pool.
* `liquidityType`: `LiquidityType`.
  * `LiquidityType.SingleAsset`: Single asset withdrawal
  * `LiquidityType.Imbalance`: Imbalance withdrawal
  * `LiquidityType.Ratio`: Ratio Withdrawal
* `position`: The position object with (when `liquidityType == LiquidityType.SingleAsset`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `amount`: `number` The minimum token amount to receive
  * `mintedShare`: `number` The amount of share tokens to burn.
  * `tokenOutIndex`: `number` The token index to receive.
* `position`: The position object with (when `liquidityType == LiquidityType.Imbalance`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `maxMintedShare`: `number` The maximum amount of share tokens to burn.
  * `amounts`: `number[]` The minimum token amounts to receive. The number of items in the amounts must be the same as the number of coins in the pool.
* `position`: The position object with (when `liquidityType == LiquidityType.Ratio`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `mintedShare`: `number` The amount of share tokens to burn.
  * `amounts`: `number[]` The minimum token amounts to receive. The number of items in the amounts must be the same as the number of coins in the pool.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeSingleStableLiquidity() {
    // use one of the followings

    // - liquidity type: LiquidityType.SingleAsset
    const params: RemoveSingleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.SingleAsset,
        position: {
           amount: 100,
           mintedShare: 10000,
           positionAddr: '0xposition',
           tokenOutIndex: 0,
        }
    }

    // - or liquidity type: LiquidityType.Imbalance
    const params: RemoveSingleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.Imbalance,
        position: {
            positionAddr: '0xposition',
            amounts: [100, 200, 300],
            maxMintedShare: 10000,
        }
    }

    // - or liquidity type: LiquidityType.Ratio
    const params: RemoveSingleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.Ratio,
        position: {
            positionAddr: '0xposition',
            mintedShare: 10000,
            amounts: [100, 200, 300]
        }
    }
    const data = sdk.Position.removeSingleStableLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

**Multiple**

Use `sdk.Position.removeMultipleStableLiquidity` method

**Params**

* `poolId`: `string` The ID of the stable pool.
* `liquidityType`: `LiquidityType`.
  * `LiquidityType.SingleAsset`: Single asset withdrawal
  * `LiquidityType.Imbalance`: Imbalance withdrawal
  * `LiquidityType.Ratio`: Ratio Withdrawal
* `positions`: An array of position objects, each containing (when `liquidityType == LiquidityType.SingleAsset`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `amount`: `number` The minimum token amount to receive
  * `mintedShare`: `number` The amount of share tokens to burn.
  * `tokenOutIndex`: `number` The token index to receive.
* `positions`: An array of position objects, each containing (when `liquidityType == LiquidityType.Imbalance`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `maxMintedShare`: `number` The maximum amount of share tokens to burn.
  * `amounts`: `number[]` The minimum token amounts to receive.
* `positions`: An array of position objects, each containing (when `liquidityType == LiquidityType.Ratio`):
  * `positionAddr`: `string` The address of the individual liquidity position.
  * `mintedShare`: `number` The amount of share tokens to burn.
  * `amounts`: `number[]` The minimum token amounts to receive.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function removeMultipleStableLiquidity() {
     // use one of the followings

     // - liquidity type: LiquidityType.SingleAsset
    const params: RemoveMultipleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.SingleAsset,
        positions: [
            {
                amount: 100,
                mintedShare: 10000,
                positionAddr: '0xposition1',
                tokenOutIndex: 0,
            },
            {
               amount: 100,
               mintedShare: 10000,
               positionAddr: '0xposition2',
               tokenOutIndex: 1,
            }
        ]
    }

     // - or liquidity type: LiquidityType.Imbalance
    const params: RemoveMultipleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.Imbalance,
        positions: [
            {
                positionAddr: '0xposition1',
                amounts: [100, 200, 300],
                maxMintedShare: 10000,
            },
            {
                positionAddr: '0xposition2',
                amounts: [300, 400, 500],
                maxMintedShare: 10000,
                
            }
        ]
    }

    // - or liquidity type: LiquidityType.Ratio
    const params: RemoveMultipleStableLiquidityParams = {
        poolId: '0xpool',
        liquidityType: LiquidityType.Ratio,
        positions: [
            {
                positionAddr: '0xposition1',
                mintedShare: 10000,
                amounts: [100, 200, 300]
            },
            {
                positionAddr: '0xposition2',
                mintedShare: 10000,
                amounts: [300, 400, 500]
            }
        ]
    }
    const data = sdk.Position.removeMultipleStableLiquidity(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

***

### Add Liquidity to Existing Pools

#### AMM

Adds liquidity to an AMM pool.

**Params**

* `poolId`: `string` The ID of the AMM pool.
* `amountA`: `number` The amount of token A to add as liquidity.
* `amountB`: `number` The amount of token B to add as liquidity.

```ts
const txData = sdk.Position.addAMMLiquidity({
  poolId: '0xpool',
  amountA: 10000000000,
  amountB: 10000000000,
});
```

#### CLMM

Adds liquidity to a CLMM pool.

**Params**

* `poolId`: `string` The unique identifier of the CLMM pool.
* `amountA`: `number` The amount of token A to add.
* `amountB`: `number` The amount of token B to add.
* `fee`: `number` The fee tier of the pool.
* `isMaxAmountB`: `boolean` Whether the second token amount (`amountB`) is flexible based on slippage (e.g. if true, it means amountB can be less than specified due to price movement).
* `minPrice`: `number` The minimum price the liquidity range.
* `maxPrice`: `number` The maximum price the liquidity range.

```ts
const txData = sdk.Position.addCLMMLiquidity({
  poolId: '0xpool',
  amountA: 10000000000,
  amountB: 10000000000,
  fee: 3000,
  isMaxAmountB: true,
  minPrice: 0.00001,
  maxPrice: 100000,
});
```

#### Stable

Adds liquidity to a stable pool.

**Params**

* `poolId`: `string` The ID of the stable pool.
* `amounts`: `number[]` An array of token amounts.

```ts
const txData = sdk.Position.addStableLiquidity({
  poolId: '0xpool',
  amounts: [10000000000, 20000000000],
});
```

***

## Collect Fee

Collects fees from a specific liquidity position in a given pool.

Use `sdk.Position.collectFee` method. **Params**

* `poolId`: `string` The address of the pool from which to collect fees.
* `positionAddr`: `string` The address of the liquidity position.

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function collectFee() {
    const params: CollectFeeParams = {
        poolId: "0xpool",
        positionAddr: "0xposition"
    }
    const data = sdk.Position.collectFee(params);

    await signAndSubmitTransaction({
        sender: account.address,
        data: data
    });
}
```

***

## Position

## Position

Retrieves a paginated list of liquidity positions for a given user address.

Use `sdk.Position.getPositions` method.

Params:

* `userAddr`: `string` The user's wallet address to fetch positions for.
* `page` (optional): `number` The page number for pagination (defaults to 1).
* `size` (optional): `number` The number of results per page (defaults to 10).

```ts
const { signAndSubmitTransaction, account } = useWallet();

async function getPositions() {
    const data = await sdk.Position.getPositions({
        userAddr: "0xuser",
        page: 1,
        size: 10
    });

    console.log(data)
}
```

***
