Skip to content

Liquidity Pool Management

The Liquidity Service provides API endpoints for managing liquidity pools, adding and removing liquidity, and executing token swaps. This guide walks you through the common operations with examples.

Overview

Liquidity pools allow users to provide liquidity (deposit pairs of tokens) to enable decentralized trading through automated market makers (AMMs). In return for providing liquidity, users receive LP (Liquidity Provider) tokens representing their share of the pool.

Key Features

  • Create and manage liquidity pools
  • Add and remove liquidity
  • Swap tokens with predictable pricing
  • View user positions and transaction history
  • Administrator controls for fees and rates

Prerequisites

Before using the Liquidity Service:

  1. You need a valid API key with appropriate permissions
  2. Understand the token pairs you want to work with
  3. Have wallets set up with sufficient balances

Creating a Liquidity Pool

To create a new liquidity pool, you need to specify the two tokens that will form the pair, the initial exchange rate, and the fee structure.

const createPool = async () => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
token0ContractDeploymentId: "TOKEN_0_CONTRACT_ID",
token1ContractDeploymentId: "TOKEN_1_CONTRACT_ID",
fee: 300, // 0.3% fee in basis points
rate: "1800.25", // Initial exchange rate
walletId: "YOUR_WALLET_ID",
name: "USDC-ETH Pool",
description: "Liquidity pool for USDC and ETH trading"
})
});
const data = await response.json();
console.log('Pool created with queryId:', data.queryId);
};

Pool Parameters

  • token0ContractDeploymentId/token1ContractDeploymentId: The contract addresses of the tokens in the pair
  • fee: Trading fee in basis points (e.g., 300 = 0.3%)
  • rate: Initial exchange rate (how many units of token1 you get for 1 unit of token0)
  • walletId: Your wallet ID that will be the initial administrator
  • name/description: Human-readable identifiers for the pool

Viewing Liquidity Pools

You can retrieve all available liquidity pools or get details about a specific pool.

List All Pools

const getPools = async () => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pools', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const pools = await response.json();
console.log('Available pools:', pools);
};

Get Pool Details

const getPoolDetails = async (poolId) => {
const response = await fetch(`https://api.fsco.io/v2/liquidity/pools/${poolId}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const pool = await response.json();
console.log('Pool details:', pool);
};

Adding Liquidity

Adding liquidity involves depositing a balanced amount of both tokens in the pool. Before adding liquidity, you can get a quote to see how many LP tokens you’ll receive.

Get Add Liquidity Quote

const getAddLiquidityQuote = async (poolId, token0Amount, token1Amount) => {
const response = await fetch(
`https://api.fsco.io/v2/liquidity/quote/add?poolId=${poolId}&token0Amount=${token0Amount}&token1Amount=${token1Amount}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const quote = await response.json();
console.log('Add liquidity quote:', quote);
return quote;
};

Add Liquidity to Pool

const addLiquidity = async (poolId, walletId, token0Amount, token1Amount) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/add', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
walletId,
token0Amount,
token1Amount
})
});
const result = await response.json();
console.log('Added liquidity:', result);
return result;
};

Removing Liquidity

When removing liquidity, you burn your LP tokens and receive back both tokens in the pair.

Get Remove Liquidity Quote

const getRemoveLiquidityQuote = async (poolId, lpTokenAmount, walletId) => {
const response = await fetch(
`https://api.fsco.io/v2/liquidity/quote/remove?poolId=${poolId}&lpTokenAmount=${lpTokenAmount}&walletId=${walletId}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const quote = await response.json();
console.log('Remove liquidity quote:', quote);
return quote;
};

Remove Liquidity

const removeLiquidity = async (poolId, walletId, lpTokenAmount) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/remove', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
walletId,
lpTokenAmount
})
});
const result = await response.json();
console.log('Removed liquidity:', result);
return result;
};

Swapping Tokens

Swapping allows users to trade one token for another using the liquidity in the pool.

Get Swap Quote

const getSwapQuote = async (poolId, inputTokenAmount, inputTokenIsToken0) => {
const response = await fetch(
`https://api.fsco.io/v2/liquidity/quote/swap?poolId=${poolId}&inputTokenAmount=${inputTokenAmount}&inputTokenIsToken0=${inputTokenIsToken0}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const quote = await response.json();
console.log('Swap quote:', quote);
return quote;
};

Execute Swap

const swap = async (poolId, walletId, amountIn, isToken0ToToken1, slippageBps = 50) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/swap', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
walletId,
amountIn,
isToken0ToToken1,
slippageBps
})
});
const result = await response.json();
console.log('Swap executed:', result);
return result;
};

Viewing User Positions

You can check how much liquidity a user has provided to a specific pool.

const getUserPosition = async (poolId, walletId) => {
const response = await fetch(
`https://api.fsco.io/v2/liquidity/pools/${poolId}/position/${walletId}`,
{
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
}
);
const position = await response.json();
console.log('User position:', position);
return position;
};

Transaction History

You can query transaction history for liquidity operations as well as swaps.

Liquidity Transactions

const getLiquidityTransactions = async (walletId = null, poolId = null, page = 1, pageSize = 10) => {
let url = `https://api.fsco.io/v2/liquidity/transactions?page=${page}&pageSize=${pageSize}`;
if (walletId) url += `&walletId=${walletId}`;
if (poolId) url += `&poolId=${poolId}`;
const response = await fetch(url, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const transactions = await response.json();
console.log('Liquidity transactions:', transactions);
return transactions;
};

Swap Transactions

const getSwapTransactions = async (walletId = null, poolId = null, status = null, page = 1, pageSize = 10) => {
let url = `https://api.fsco.io/v2/liquidity/swaps?page=${page}&pageSize=${pageSize}`;
if (walletId) url += `&walletId=${walletId}`;
if (poolId) url += `&poolId=${poolId}`;
if (status) url += `&status=${status}`;
const response = await fetch(url, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const transactions = await response.json();
console.log('Swap transactions:', transactions);
return transactions;
};

Administrator Controls

Pool administrators have additional capabilities to manage the pool.

Update Pool Fees

const updatePoolFees = async (poolId, fee, walletId) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool/fees', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
fee,
walletId
})
});
const result = await response.json();
console.log('Updated pool fees:', result);
return result;
};

Update Pool Rate

const updatePoolRate = async (poolId, rate, walletId) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool/rate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
rate,
walletId
})
});
const result = await response.json();
console.log('Updated pool rate:', result);
return result;
};

Update Pool Status

Administrators can pause or resume trading on a pool.

const updatePoolStatus = async (poolId, status, walletId) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool/status', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
status, // 'active' or 'paused'
walletId
})
});
const result = await response.json();
console.log('Updated pool status:', result);
return result;
};

Admin Fee Management

Administrators can collect fees and adjust fee sharing parameters.

Update Admin Fee Share

const updateAdminFeeShare = async (poolId, adminFeeShare, walletId) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool/admin-fee-share', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
adminFeeShare, // in basis points (e.g., 1000 = 10%)
walletId
})
});
const result = await response.json();
console.log('Updated admin fee share:', result);
return result;
};

Collect Admin Fees

const collectAdminFees = async (poolId, walletId) => {
const response = await fetch('https://api.fsco.io/v2/liquidity/pool/admin-fees/collect', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
poolId,
walletId
})
});
const result = await response.json();
console.log('Collected admin fees:', result);
return result;
};

Best Practices

When working with liquidity pools, consider these best practices:

  1. Get a quote before executing actions - Always get quotes for add liquidity, remove liquidity, and swap operations to estimate the outcome.

  2. Use slippage protection - When swapping tokens, set a reasonable slippage parameter (usually 0.5-1%) to protect against price movements.

  3. Start with small amounts - When first interacting with a pool, start with small amounts to ensure everything works as expected.

  4. Monitor pool status - Check if pools are active before attempting to add liquidity or swap tokens.

  5. Check transaction history - Regularly review your transaction history to confirm all operations completed successfully.

  6. Be aware of fees - Understand the fee structure of each pool before providing liquidity or swapping tokens.

  7. Consider price impact - Large swaps or liquidity provisions can significantly impact price. Check the price impact in quotes.

Troubleshooting

Common Issues

IssuePossible CausesSolutions
Transaction failsInsufficient balance, pool pausedCheck token balances, verify pool status
High slippageLow liquidity, price volatilityReduce trade size, adjust slippage tolerance
Cannot collect feesNot an admin, no fees to collectVerify admin permissions, check fee accumulation
Rate mismatchOutdated rate informationGet a fresh quote before executing actions
API requests failingAuthentication issuesCheck API key permissions and expiration

Error Handling

Always include proper error handling in your code:

try {
// API call here
} catch (error) {
console.error("Error:", error.message);
// Handle specific error types
if (error.response && error.response.status === 400) {
console.error("Bad request:", await error.response.json());
}
}

Next Steps

Now that you understand how to manage liquidity pools, consider exploring: