TONCO Docs
Документация и Гайды
Документация и Гайды
  • TONCO
    • Что такое TONCO?
    • Концентрированная ликвидность впервые на TON
    • Команда
    • Социальные сети
    • Аудиты
    • Roadmap
  • Что такое концентрированная ликвидность?
    • Глоссарий
    • Fees
    • NFT-токены поставщиков ликвидности
    • Фарминг (Farming)
    • Farming FAQ
  • Ценовые диапазоны
    • Значение ценовых диапазонов
    • Предустановленные диапазоны
    • Продвинутые пресеты диапазонов
    • Движение цены в пределах диапазонов
    • Непостоянные потери (Impermanent Loss)
    • Выбор стратегии
    • Сценарии при управлении ликвидностью
  • Преимущества концентрированной ликвидности
    • Преимущества для поставщиков ликвидности
    • Преимущества для трейдеров
    • Преимущества для проектов
    • Токены ликвидного стейкинга (LST)
  • Стратегии Концентрированной Ликвидности
    • Базовые стратегии
    • Хэджирование с EVAA (lending)
    • Хэджирование с Tradoor (perps)
    • Хэджирование со Storm Trade (perps)
  • Руководство по предоставлению ликвидности
    • Добавление ликвидности
    • Управление позицией
    • Руководство по миграции ликвидности
    • Как рассчитывается APR
    • LPs FAQ
  • TONCO Points Program
    • Introduction
    • How to Earn Points
  • Ambassador Program
    • Introduction
    • Content Creators
    • Community Moderators
    • International Ambassadors
  • Technical Reference
    • 📇Indexer
    • GraphQL Schema
    • Integration FAQ
    • Core Logic
      • 🧺Pool overview
      • Swap calculation
      • 💰Liquidity and positions
      • 📏Ticks
      • 🏦Reserves
    • Contracts
      • 📜Scenarios
      • Pool
      • Router
      • Position NFT
      • Account
Powered by GitBook
On this page
  • Questions
  • Indexer and SDK
  • SDK
  • Examples and references
  • Mainnet
  • Testnet
  • Retrieve pool data
  • Retrieving positions
  • Getting positions by index
  • Getting positions with NFT API's
  • Getting positions from TONCO indexer
  • Forming messages for the swap
  • Swap estimate
  1. Technical Reference

Integration FAQ

PreviousGraphQL SchemaNextCore Logic

Questions

Indexer and SDK

SDK

Github -

Examples and references

Github -

Mainnet

  • Router Contract - EQC_-t0nCnOFMdp7E7qPxAOCbCWGFz-e3pwxb6tTvFmshjt5

Testnet

  • Router Contract - EQDnfag9lHlc0rS6YeI7WwRq-3ltcKSsYxLiXmveB7gNUzNO

Retrieve pool data

The best way to get all the pools and general information about them is to use our indexer.

// Some code
import { ApolloClient, InMemoryCache, gql} from "@apollo/client/core";
import { Command, OptionValues } from "commander";

export const POOLS_QUERY = gql`
query PoolsQuery { 
 pools {   
   name
   address
   jetton0 {
       address
       symbol
       decimals
   }
   jetton1 {
       address
       symbol
       decimals
   }
 }  
}
`;
async function queryPools(options: OptionValues) {


   const appoloClient = new ApolloClient({
       uri: "https://indexer.tonco.io/", 
       credentials: 'same-origin',
       cache: new InMemoryCache(),
   });
   const response = await appoloClient.query({ query: POOLS_QUERY });
   const appoloPoolList =  response.data.pools
   console.log(appoloPoolList);
}

Indexer is critical for our system, and we keep it highly available, however, we encourage caching the pool list.

Retrieving positions

There are several ways to get all positions and positions per person.

Getting positions by index

Getting positions with NFT API's

Getting positions from TONCO indexer

import { ApolloClient, InMemoryCache, gql} from "@apollo/client/core";
import { Address, TonClient4 } from "@ton/ton";
import { getHttpV4Endpoint } from "@orbs-network/ton-access";
import { PoolV3Contract } from "../wrappers/PoolV3Contract";

export const POSITION_QUERY = gql`
query PositionQuery($where: PositionWhere) {
    positions(where: $where) {
      id
      owner
      pool
      nftAddress      
      tickLower
      tickUpper
      liquidity
      feeGrowthInside0LastX128
      feeGrowthInside1LastX128
    }
}
`;

async function queryPositions(options: OptionValues) {

    const appoloClient = new ApolloClient({
        uri: "https://indexer.tonco.io/", // Replace with your GraphQL endpoint
        credentials: 'same-origin',
        cache: new InMemoryCache(),
    });

    const poolAddress  = Address.parse("EQD25vStEwc-h1QT1qlsYPQwqU5IiOhox5II0C_xsDNpMVo7")
    const ownerAddress = Address.parse("EQC2nUFN69DWcdgiuvSKXI6P3vHF9Gu_zW3OnQf0s5DgYBmJ")
    console.log(poolAddress.toRawString())
    console.log(ownerAddress.toString({bounceable: true}))

    const response = await appoloClient.query({ query: POSITION_QUERY, variables: {
        "where": {
            "pool" : poolAddress.toRawString(),
            "owner": ownerAddress.toString({bounceable: true})
        }
        } });
    const appoloPositionsList =  response.data.positions
    const client =  new TonClient4({ endpoint : await getHttpV4Endpoint() })
    const poolOpened = client.open(new PoolV3Contract(poolAddress))

    for (let [i, positionInfo] of appoloPositionsList.entries()) {
        console.log(`# ${i} :`);
        console.log(positionInfo);
        
        const fees = await poolOpened.getCollectedFees(positionInfo.tickLower, positionInfo.tickUpper, positionInfo.liquidity, positionInfo.feeGrowthInside0LastX128, positionInfo.feeGrowthInside1LastX128)
        console.log(`  Fees Jetton0 : ${fees.amount0}`)
        console.log(`  Fees Jetton1 : ${fees.amount1}`)

        const reserves = await poolOpened.getMintEstimate(positionInfo.tickLower, positionInfo.tickUpper, positionInfo.liquidity)
        console.log(`  Reserves Jetton0 : ${reserves.amount0}`)
        console.log(`  Reserves Jetton1 : ${reserves.amount1}`)

    }
}

Forming messages for the swap

Swap estimate

This question depends on your requirements, limitations, and infrastructure of choice. Here are 5 options

  1. If you have ever implemented integration with other Algebra EVM projects written in your language of choice - then the output simulation can be bit-precise

  2. You can use our Typescript implementation of user-side swap simulation. It includes the script that compares it with a direct contract call. Before actual blockchain execution please check that the estimates you made with TS match the contract call

# Usage example

git clone [email protected]:cryptoalgebra/tonco-demo.git 
cd tonco-demo
cd swap_simulate
npm install 
ts-node scripts/dowloadAndSimulate.ts
  1. You can use our Kotlin implementation of user-side swap simulation.

# Usage example
# Expecting you have JVM and kotlinc 

git clone [email protected]:cryptoalgebra/tonco-demo.git 
cd tonco-demo
cd swap_kotlin
./run.sh

Explorer page:

GraphQL endpoint:

Explorer page:

GraphQL endpoint:

Alternatively, if you don’t want to depend on our infrastructure, you can rescan the blockchain in search of messages sent by the router

If you want to manually scan and enumerate all the positions for a particular pool you can first use the method and get "Number of active NFT positions" from it. Then iterate from 0 as the index of NFT and call

Position NFT is a real NFT so you can use and to get NFT address info and metadata. For position parameters, however, you would need to call the NFT get-method -

Please address the GraphQL schema documents for more details - Getting collected fees - Here is a small snippet that uses our indexer

Sending swap can be done with our SDK -

An example of swap preparation can be found here -

A swap request is created as a payload in the jetton transfer and is sent to the router. The general logic of the input parameters can be derived from the SDK example above and the doc of the pool swap message

The simplest and most precise way is to call the pool contract get method -

Download the pool contract code (code is immutable) and data and run this method in sandbox/blueprint. This would be the simplest and fastest way to make many calls. The general example you can find here -

https://indexer.tonco.io
https://indexer.tonco.io
https://testnet-indexer.tonco.io
https://testnet-indexer.tonco.io
TonConsole Api
TonCenter API
GetPositionInfo()
GraphQL Schema
https://docs.tonco.io/technical-reference/indexer#position-data
https://github.com/cryptoalgebra/tonco-sdk
https://github.com/cryptoalgebra/tonco-sdk/blob/36eb0d7feadfcdcd60583ebe4098eb25fcc02591/src/classes/PoolMessageManager.ts#L649
https://docs.tonco.io/technical-reference/contracts/pool#getswapestimategas
tonco-demo example of shard account
https://github.com/cryptoalgebra/tonco-sdk/
https://github.com/cryptoalgebra/tonco-demo
What is your infrastructure? Do you have SDK?
How do you retrieve all the pools you have?
How do you retrieve all the positions?
How do I perform a swap from my code?
How do I predict the result of the swap?
POOL_INIT
getPoolStateAndConfiguration
get_nft_address_by_index()
POOLV3_SWAP