Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@tucana-network/spot-sdk

Package Overview
Dependencies
Maintainers
4
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tucana-network/spot-sdk

For the latest updates and detailed information on how to interact with the TucanaSpotSDK contract, please refer to the [Tucana Protocol Developer Docs](https://tucana-1.gitbook.io/tucana-product-docs).

latest
npmnpm
Version
0.1.0
Version published
Maintainers
4
Created
Source

TucanaSpotSDK Documentation

For the latest updates and detailed information on how to interact with the TucanaSpotSDK contract, please refer to the Tucana Protocol Developer Docs.

Introduction

The TucanaSpotSDK provides a set of tools for Initia blockchain networks, specifically designed for handling set up a spot DEX based on the CLMM model (concentrated liquidity market maker) on the Initia. This documentation covers the Spot DEX within the TucanaSpotSDK ecosystem.

Getting Started

Installation

Before you can use the TucanaSpotSDK Client, you need to set up your project environment.

npm i @tucana-network/spot-sdk

Instantiate TucanaSpotSDK

  • simulateAddress: should be add an account address with a small amount of assets, it used to do estimated or other query object from chain
import { TucanaSpotSDK, SdkOptions } from '@tucana-network/spot-sdk';

// Configuration for the testnet
export const testnetConfig: SdkOptions = {
  initiaLcdUrl: 'https://lcd.initiation-1.initia.xyz',
  initiaApiUrl: 'https://api.initiation-1.initia.xyz',
  simulateAddress: 'init...',
  clmmPool: {
    package_id: '0x8609f642a8ab1c13d661c14d733cab227bba15635a730af2057051b3f2ada3f6',
    config: {
      poolsHandle: '0xb1e8d74a0f00b44d3e610953f34deb3ce8a48f80bd413379a064e893188a9309'
    }
  }
}

// Configuration for the mainnet
export const mainnetConfig: SdkOptions = {
  initiaLcdUrl: '',
  initiaApiUrl: '',
  simulateAddress: '',
  clmmPool: {
    package_id: '',
    config: {
      poolsHandle: ''
    }
  }
}

// Initialize TucanaSpotSDK with testnetConfig or mainnetConfig
export const sdk = new TucanaSpotSDK(testnetConfig)

Set SDK SenderAddress

After linking the wallet, set the Sender Address to the SDK.

 sdk.senderAddress = key.accAddress // Set sender address to the SDK

Get the list of pools

Function input params

  • options: Query options for pagination and filtering.
const poolList = await sdk.Pool.getPoolList()

Get information about a pool

Function input params

  • poolAddress: The address of the pool
const pool = await sdk.Pool.getPool(poolAddress)

Get the list of ticks for a pool

const pool = await sdk.Pool.getPool(poolAddress)
const res = await sdk.Pool.getPoolTickList(pool.tick_manager.id)

Get the token amounts for a pool

const amounts = await sdk.Pool.getPoolTokenAmounts(poolAddress)

Create pool

Just create one clmmpool, without adding any initial liquidity.

Function input params

  • tick_spacing: tick spacing will affect price precision. Now mainnet exist some different type tick_spacing, they correspond to different fee rates.

    tick spacingfee rate
    20.0001
    100.0005
    600.0025
    2000.01
  • initialize_sqrt_price: for computational convenience, we use fixed-point numbers to represent square root prices. Use the provided by the SDK transformation price to sqrtPrice: TickMath.priceToSqrtPriceX64().

  • uri: the icon of pool, it's allows null.

  • metadata_a: the metadata address about tokenA.

  • metadata_b: the metadata address about tokenB.

 const token0 = currTokenConfig.USDC
 const token1 = currTokenConfig.USDT
 const tick_spacing = 60
 const initialize_sqrt_price = TickMath.tickIndexToSqrtPriceX64(TickMath.priceToTickIndex(d(1.1), token0.decimals, token1.decimals))

// Define pool creation parameters
 const params : CreatePoolParams = {
      tick_spacing,
      uri: '',
      initialize_sqrt_price: initialize_sqrt_price.toString(),
      metadata_a: token1.metadata,
      metadata_b: token0.metadata
    }

 const payload = sdk.Pool.createPoolPaylod(params)
 const respone = await executeTransaction([payload], sdk, key, false)

Create pool and add addliquidity

Create one clmmpool and add some initial liquidity simultaneously. (Recommended)

Function input params

  • tick_lower: Represents the index of the lower tick boundary.
  • tick_upper: Represents the index of the upper tick boundary.
  • amount_a: the amount about Token A, which used to add liquidity.
  • amount_b: the amount about Token B, which used to add liquidity. Notice: amount a and b was calculated by ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(), it will affected by selected tick interval、amount about one fixed Token(TokenA or TokenB)、current sqrt price of pool and allowed price slippage. You can see the usage in the next example.
  • fix_amount_a: true means fixed TokenA amount, false means fixed TokenB amount.
const token0 = currTokenConfig.USDC
const token1 = currTokenConfig.USDT
const tick_spacing = 60
const initialize_price = TickMath.tickIndexToSqrtPriceX64(TickMath.priceToTickIndex(d(1.1), token0.decimals, token1.decimals))

const lowTick = TickPriceData.buildTickPriceData('0.8', tick_spacing, token0, token1)
const highTick = TickPriceData.buildTickPriceData('1.2', tick_spacing, token0, token1)

const fix_amount_a = true
const coin_amount = '1000000'
const slippage = 0.1

const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
    lowTick.tick,
    highTick.tick,
    new BN(coin_amount),
    fix_amount_a,
    true,
    slippage,
    initialize_price
)

const amount_a = fix_amount_a ? coin_amount : liquidityInput.tokenMaxA.toString()
const amount_b = fix_amount_a ? liquidityInput.tokenMaxB.toString() : coin_amount

// Define parameters for creating a pool with liquidity
const params : CreatePoolWithLiquidityParams= {
    tick_spacing,
    uri: '',
    initialize_price: initialize_price.toString(),
    metadata_a: token1.metadata,
    metadata_b: token0.metadata,
    tick_lower: lowTick.tick,
    tick_upper: highTick.tick,
    amount_a,
    amount_b,
    fix_amount_a
}
const payload = sdk.Pool.createPoolPaylod(params)
const respone = await executeTransaction([payload], sdk, key, false)

Swap

Swaps typically occur in two steps:

  • the first step involves pre-calculating the potential result of the current transaction
  • the second step is to set the slippage based on the pre-calculated results, followed by executing the transaction.

Function input params

  • pool_id: pool object id.
  • a2b: swap direction, true means swap from coinA to coinB, false means swap from coinB to CoinA.
  • by_amount_in: true means fixed the amount of input, false means fixed the amount of output.
  • amount: the amount of input (byAmountIn = true) or output (byAmountIn = false).
  • partner: The partner address. If you do not have a partner, simply leave the partner field unset.
  const pool = await sdk.Pool.getPool(poolAddress)
  const a2b = true
  const by_amount_in = true
  const amount = 1000000
  const slippage = 0.01

  // Estimated amountIn amountOut fee
  const swapResult = await sdk.Pool.calculateSwapAmount({
      pool_id: poolAddress,
      a2b,
      by_amount_in,
      amount,
      partner
    })
   

  const payload = sdk.Pool.createSwapPaylod({
      pool_id: poolAddress,
      a2b,
      by_amount_in,
      amount_in: swapResult.amount_in,
      amount_out: swapResult.amount_out,
      slippage
    })

  const respone = await executeTransaction([payload], sdk, key, false)

Retrieve all positions

  • ownerAddress: The user account address.
  • assignCollections: An array of posotion Collection
const positionList = await sdk.Position.getPositionList(key.accAddress)

Retrieve one position

  • pid: The position ID.
  • calculateFee: Whether to calculate the fee, default is false.
  • calculateReward: Whether to calculate the reward, default is false.
const position = await sdk.Position.getPositionInfo(positionId)

Calculate position fee

Calculate the position fee for a list of position IDs.

  • pids: The list of position IDs.
const posFees = await sdk.Position.calculatePositionFee([positionId])

Calculate position rewards

Calculate the position rewards for a list of position IDs.

  • pids: The list of position IDs.
const posFees = await sdk.Position.calculatePositionRewards([positionId])

Collect position reward

  • pid: position ID.
const posFees = await sdk.Position.collectRewardsPaylod({pid: positionId})

Collect position fee

  • pid: Tposition ID.
const posFees = await sdk.Position.collectFeePaylod({pid: positionId})

Open position and add liquidity

Before you want to deposit liquidity, you need to choose an appropriate price range (corresponding to the tick range) to open a position. In most cases, opening a position and adding liquidity are supposed to be done simultaneously.

  • pool_id: The object id about which pool you want to operation.
  • tick_lower: Represents the index of the lower tick boundary.
  • tick_upper: Represents the index of the upper tick boundary.
  • fix_amount_a: true means fixed coinA amount, false means fixed coinB amount
  • offer_amount_a:If fixed amount A, you must set amountA, amountB will be auto calculated by ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts().
  • offer_amount_b: f fixed amount B, you must set amountB, amountA will be auto calculated by ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts().
const pool = await sdk.Pool.getPool(poolAddress)
const fix_amount_a = true
const coin_amount = '1000000'
//Price slippage point.
const slippage = 0.1
const curSqrtPrice = new BN(pool.current_sqrt_price)
const tick_lower = TickMath.getPrevInitializableTickIndex(pool.current_tick_index, Number(pool.tick_spacing))
const tick_upper = TickMath.getNextInitializableTickIndex(pool.current_tick_index, Number(pool.tick_spacing))

const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
    tick_lower,
    tick_upper,
    new BN(coin_amount),
    fix_amount_a,
    true,
    slippage,
    curSqrtPrice
)

const amount_a = fix_amount_a ? coin_amount : liquidityInput.tokenMaxA.toString()
const amount_b = fix_amount_a ? liquidityInput.tokenMaxB.toString() : coin_amount

// Define parameters for opening position and adding liquidity
const params: OpenPositionWithLiquidityParams = {
    pool_id: pool.pool_address,
    tick_lower,
    tick_upper,
    fix_amount_a,
    offer_amount_a: amount_a,
    offer_amount_b: amount_b
}

const payload = sdk.Position.addLiquidityPaylod(params)
const respone = await executeTransaction([payload], sdk, key, true)

Add liquidity by fix coin

Once you have set a suitable tick range, you can proceed to add liquidity to this position. The quantity composition of tokens you need to add is affected by the current price of the pool and the tick interval you have chosen.

  • pid: The object id about which pool you want to operation.
  • fix_amount_a: true means fixed coinA amount, false means fixed coinB amount
  • offer_amount_a:If fixed amount A, you must set amountA, amountB will be auto calculated by ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts().
  • offer_amount_b: f fixed amount B, you must set amountB, amountA will be auto calculated by ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts().
const pool = await sdk.Pool.getPool(poolAddress)
const position = await sdk.Position.getPositionInfo(positionId)

const fix_amount_a = true
const coin_amount = '1000000'
const slippage = 0.1
const curSqrtPrice = new BN(pool.current_sqrt_price)
const tick_lower = position.tick_lower_index
const tick_upper = position.tick_upper_index

const liquidityInput = ClmmPoolUtil.estLiquidityAndcoinAmountFromOneAmounts(
    tick_lower,
    tick_upper,
    new BN(coin_amount),
    fix_amount_a,
    true,
    slippage,
    curSqrtPrice
)

const amount_a = fix_amount_a ? coin_amount : liquidityInput.tokenMaxA.toString()
const amount_b = fix_amount_a ? liquidityInput.tokenMaxB.toString() : coin_amount

// Define parameters for adding liquidity by fixing coin
const params: AddLiquidityFixCoinParams = {
    pid: positionId,
    fix_amount_a,
    offer_amount_a: amount_a,
    offer_amount_b: amount_b
}

const payload = sdk.Position.addLiquidityPaylod(params)
const respone = await executeTransaction([payload], sdk, key, false)

Remove liquidity

When you want to adjust the liquidity of your position or withdraw liquidity from the position, you can use the following method. When you withdraw liquidity, you also have the option to collect fees or rewards at the same time. Please refer to the parameter description below for more details.

  • pid: The object id about position.
  • delta_liquidity: The quantity of liquidity.
  • min_amount_a: The minimum amount of coin A that a user can acquire.
  • min_amount_b: The minimum amount of coin B that a user can acquire.
const pool = await sdk.Pool.getPool(poolAddress)
const position = await sdk.Position.getPositionInfo(positionId)

const slippage = 0.01
const curSqrtPrice = new BN(pool.current_sqrt_price)
const tick_lower = position.tick_lower_index
const tick_upper = position.tick_upper_index
const lowerSqrtPrice = TickMath.tickIndexToSqrtPriceX64(tick_lower)
const upperSqrtPrice = TickMath.tickIndexToSqrtPriceX64(tick_upper)
const liquidity =  '1000000'

const coinAmounts = ClmmPoolUtil.getCoinAmountFromLiquidity(new BN(liquidity), curSqrtPrice, lowerSqrtPrice, upperSqrtPrice, true)
const min_amount_a = d(coinAmounts.coinA.toString()).mul(1 - slippage).toFixed(0)
const min_amount_b = d(coinAmounts.coinB.toString()).mul(1 - slippage).toFixed(0)

// Define parameters for removing liquidity
const params: RemoveLiquidityParams = {
    pid: position.id,
    min_amount_a,
    min_amount_b,
    delta_liquidity: liquidity
}

const payload = sdk.Position.removeLiquidityPaylod(params)
const respone = await executeTransaction([payload], sdk, key, false)

Price to TickIndex

when you want to open position, you dont know how to set your tick_lower and tick_upper.

// decimalsA and decimalsB means the decimal of coinA and coinB
const tick_lower = TickMath.priceToTickIndex(price, decimalsA, decimalsB)

Calculate price from sqrt price

const pool = await sdk.Pool.getPool(poolAddress)
const price = TickMath.sqrtPriceX64ToPrice(new BN(pool.current_sqrt_price))

FAQs

Package last updated on 03 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts