Provide liquidity
Add and remove liquidity
Open a position on a pair, collect what it earns, and take the liquidity back out, in the app or with the SDK.
A position is liquidity on one pair over a range of prices. It trades only in a batch's clearing, at the cleared price. The provider's whole task is four instructions.
| Instruction | Who signs | What it does |
|---|---|---|
add_liquidity | The owner | Moves the range's tokens from the wallet to the two token vaults and opens the position, or adds to it. |
collect_fees | The owner | Pays what the position has earned to the owner. |
remove_liquidity | The owner | Returns the tokens for the liquidity removed, at the pair's price now. |
settle_position | Anyone | Pays what the position has earned to the owner. |
A pair has two tokens. The first is the one listed earlier, and the pair's price is atoms of the second token per atom of the first. Below they are x and y. Ranges and fees explains ticks, and which of the two tokens a range needs.
Add liquidity
Open the pair
On
/pool, the table Pairs lists every pair with its price, liquidity and fee. Press Add liquidity on a row to open/pool/[pair].Set the range
Under Range around the price, choose ±1%, ±5% or ±20%. The page opens on ±5%. Lowest price and Highest price then move one tick spacing with each press of minus or plus. The chosen range draws on the price chart and in Liquidity by price.
Enter the amount
Amount is in the pair's first token. Balance fills in everything the wallet holds of it. You place shows both token amounts the range takes for that amount, and the line under it shows In range or Out of range at the pair's price.
Sign
Press Add liquidity and sign in the wallet. The position appears under Your positions on this pair, and on
/poolunder Your positions.
import { createUna } from '@una/sdk'
// wallet: a Wallet Standard wallet, a keypair, or { address, signTransaction }
const una = createUna({ apiUrl: 'https://api.una.markets', wallet })
const pair = await una.pair('sol-usdc')
// About 5% either side of the pair's price, moved outward onto the tick spacing.
const width = Math.round(Math.log(1.05) / Math.log(1.0001)) // 488 ticks
const tickLower = Math.floor((pair.currentTick - width) / pair.tickSpacing) * pair.tickSpacing
const tickUpper = Math.ceil((pair.currentTick + width) / pair.tickSpacing) * pair.tickSpacing
// Place 1 SOL. The quote returns the USDC that goes with it and the liquidity the two make.
const quote = await una.quoteLiquidity('sol-usdc', { tickLower, tickUpper, amountX: '1000000000' })
// The most the wallet will pay: the quote plus 0.5%, for a price that moves before the transaction lands.
const most = (atoms: string) => ((BigInt(atoms) * 1005n) / 1000n).toString()
const added = await una.addLiquidity('sol-usdc', {
tickLower,
tickUpper,
amountX: most(quote.amountX),
amountY: most(quote.amountY),
liquidityDelta: quote.liquidityDelta,
})
console.log(`position ${added.positionAddress}, transaction ${added.signature}`)una.quoteLiquidity takes amountX or amountY and returns a LiquidityQuote: both amounts, liquidityDelta and inRange. The two amounts are what add_liquidity transfers for that liquidityDelta at the pair's price the API read, computed in the program's integer arithmetic and rounded up as the program rounds. una.addLiquidity builds the transaction, signs it with the wallet, submits it and follows it until it settles. It resolves with positionAddress, signature and the transaction's status.
What add_liquidity takes
add_liquidity
tick_loweri32required- The lower tick of the range.
tick_upperi32required- The upper tick of the range.
liquidity_deltau128required- The liquidity to add. Liquidity is the number that fixes how many atoms of each token the range holds at a price.
max_amount_xu64required- The most atoms of the first token the wallet pays.
max_amount_yu64required- The most atoms of the second token the wallet pays.
The API route takes the same values as tickLower, tickUpper, liquidityDelta, amountX and amountY. The two amounts are the maximums. Without liquidityDelta the API computes the largest liquidity both amounts cover at the pair's price.
The program computes the two token amounts from liquidity_delta and the pair's price and transfers exactly those from the owner's token accounts to the vaults. The maximums only bound them. The app sends the quote's own amounts as the maximums.
A position's address is derived from its owner, the pair's index, tick_lower and tick_upper. One wallet has one position per range on a pair, and add_liquidity on a range it already holds adds to that position after crediting what it has earned so far.
How the amounts are computed
sa = square-root price at tick_lower sb = square-root price at tick_upper s = the pair's square-root price all three Q64.64 L = liquidity_delta x(lo, hi) = L * (hi - lo) * 2^64 / (lo * hi) y(lo, hi) = L * (hi - lo) / 2^64 s <= sa amount_x = x(sa, sb) amount_y = 0 sa < s < sb amount_x = x(s, sb) amount_y = y(sa, s) s >= sb amount_x = 0 amount_y = y(sa, sb)
add_liquidity rounds both amounts up. remove_liquidity uses the same formulas and rounds both down.
For the position followed on What a position earns: liquidity 50,000,000,000 over ticks 45650 to 46450, at a pair price of 100 atoms of y per atom of x, takes 98,020,405 atoms of x and 9,998,286,501 atoms of y.
What the program checks on add
| Error | Raised when |
|---|---|
ZeroLiquidity | liquidity_delta is 0. |
InvalidTickRange | tick_lower is not below tick_upper, a tick is under -443,636 or over 443,636, or a tick is not a multiple of the pair's tick spacing. |
CapacityExceeded | The range needs a tick the pair has not initialized and the pair already has 64 initialized ticks. |
SlippageExceeded | The computed amount of x is over max_amount_x, or the computed amount of y is over max_amount_y. |
MathOverflow | liquidity_delta is over 2^127 - 1, a liquidity total passes its type, or a token amount does not fit in a u64. |
Unauthorized | The position exists and its owner is not the signer. |
The token program refuses the transfer when the wallet holds less than a computed amount. The API answers INVALID_TICK_RANGE before building when a tick is off the spacing.
Read a position
/pool lists the connected wallet's positions under Your positions, and /pool/[pair] lists the ones on that pair. Each row shows the range as two prices, its status, what it holds of each token now, and Fees earned: the amounts credited to the position and not yet paid out.
const { items: positions } = await una.positions({ pair: 'sol-usdc' })
const position = positions.find((p) => p.address === added.positionAddress)!
console.log(`${position.inRange ? 'in range' : 'out of range'}: holds ${position.amountX} + ${position.amountY}, owed ${position.feesOwedX} + ${position.feesOwedY}`)una.positions returns the bound wallet's positions as LiquidityPosition objects. pair narrows it to one pair.
A position is in one of three states.
| State | When | What moves it |
|---|---|---|
| In range | The pair's tick is at or above tick_lower and below tick_upper. The position holds both tokens, trades in each clearing that moves the pair, and earns. | A clearing that moves the pair's tick outside the range. |
| Out of range | The pair's tick is outside the range. The position holds one token and does not trade. | A clearing that moves the pair's tick back inside. |
| Empty | Its liquidity is 0 after everything was removed. The account stays, and anything it earned stays collectable. | add_liquidity on the same range adds to it again. |
Collect fees
collect_fees brings the position's earnings up to the pair's latest clearing and pays all of them, in both tokens, to the owner's associated token accounts. It takes no arguments.
The position's account keeps two amounts owed. add_liquidity on an existing position and remove_liquidity credit earnings to them and leave them there. collect_fees and settle_position credit and pay in one step, so they pay everything earned up to the latest clearing.
feesOwedX and feesOwedY in the API are that same total: the account's two amounts plus what the pair's fee growth has added inside the range since the position's last credit. surplusEarnedX and surplusEarnedY are the second part alone.
On /pool, a position whose Fees earned is above zero shows Collect fees on its row. Press it and sign.
const collected = await una.collectFees(position.address)
console.log(`collected in ${collected.signature}`)| Error | Raised when |
|---|---|
NothingToClaim | The position is owed 0 of both tokens. |
Unauthorized | The signer is not the position's owner, or a receiving account is not the owner's associated token account for that token. |
MathOverflow | The amount owed passes a u64. |
What a position earns shows where the amounts come from.
Remove liquidity
remove_liquidity takes liquidity out of a position and returns its tokens at the pair's price in the same transaction. The position's earnings are credited first and stay on the position for collect_fees.
A clearing writes its batch's number into in_flight_batch on every pair it clears against. While that batch is cleared and neither proven nor slashed, remove_liquidity on the pair is refused with PairInFlight. Once the batch is proven or slashed the removal goes through, and it sets in_flight_batch back to 0. The instruction reads the status from that batch's account, passed as its first remaining account whenever in_flight_batch is not 0. A batch's account is closed only after it is proven, so when the address of that batch holds no account any more, the removal goes through as well. The API adds the address to the transaction it builds.
remove_liquidity
liquidity_deltau128required- The liquidity to remove. The position's whole liquidity empties it.
min_amount_xu64required- The least atoms of the first token to accept. The API sends 0 when
minAmountXis left out. min_amount_yu64required- The least atoms of the second token to accept. The API sends 0 when
minAmountYis left out.
On /pool, press Remove on the position's row and sign. The app removes the position's whole liquidity.
// Half of the position, accepting no less than 99.5% of what it holds for that half now.
const half = BigInt(position.liquidity) / 2n
const least = (atoms: string) => ((BigInt(atoms) * 995n) / 2000n).toString()
const removed = await una.removeLiquidity(position.address, {
liquidityDelta: half.toString(),
minAmountX: least(position.amountX),
minAmountY: least(position.amountY),
})
console.log(`removed in ${removed.signature}`)To remove everything, pass position.liquidity as liquidityDelta.
The amounts come from the formulas above with L = liquidity_delta, rounded down. Which token comes back depends on where the pair's price is: a position that went in with both tokens and is now out of range returns one.
| Error | Raised when |
|---|---|
ZeroLiquidity | liquidity_delta is 0, or it is more than the position's liquidity. |
PairInFlight | The pair's in_flight_batch is not 0 and that batch's account shows a status other than proven, slashed or rolled, or no batch account is passed. |
InvalidBatchAccounts | The first remaining account is not at the address of the pair's in_flight_batch, or the account there is neither a Batch account of the program nor empty. |
SlippageExceeded | The computed amount of x is under min_amount_x, or the computed amount of y is under min_amount_y. |
Unauthorized | The signer is not the position's owner, or a receiving account is not the owner's associated token account for that token. |
MathOverflow | liquidity_delta is over 2^127 - 1, or a total passes its type. |
Settle a position
settle_position does what collect_fees does, for any position, signed by any wallet. It credits the position's earnings up to the pair's latest clearing and pays them to the owner's associated token accounts. The wallet that sends it pays the transaction and receives nothing. It takes no arguments, and it succeeds when nothing is owed.
// Any wallet may send this for any position. What the position is owed goes to its owner.
const settled = await una.settlePosition(position.address)
console.log(`settled in ${settled.signature}`)| Error | Raised when |
|---|---|
Unauthorized | A receiving account is not the owner's associated token account for that token. |
MathOverflow | The amount owed passes a u64. |
When a change takes effect
add_liquidity and remove_liquidity change the pair in the transaction that carries them, whatever the status of the open batch. add_liquidity goes through at any time. remove_liquidity goes through when the last batch that cleared against the pair is proven or slashed, and is refused with PairInFlight between that clearing and its proof.
A solver clears a batch against each pair as it stands when its clearing lands. Liquidity added before that moment trades in that clearing and in every one after it. Liquidity removed before that moment is in none of them.
A solver solves against the pair it read. When a position changes the pair between that read and the clearing, the program refuses the clearing with StateHashMismatch and the solver solves again on the new state, as The clearing conditions describes.
The pair's price, and with it what a position holds, moves when a batch's clearing is posted. What a position earned in a clearing is collectable from that moment.
What it costs
| Cost | Amount | Paid to |
|---|---|---|
| The position's account | Rent for 123 bytes, paid once by the owner when the first add_liquidity on a range creates it | The account |
| Token accounts | Rent for an associated token account of either token the wallet does not have yet. The API adds their creation to each transaction it builds | The accounts |
| Transaction fee | Solana's fee for each transaction | The network |
The program takes no fee on any of the four instructions. When the first token is SOL, the API wraps the SOL the position needs inside the same transaction, and SOL paid back by remove_liquidity or collect_fees arrives as wrapped SOL in the wallet's associated token account.
Events
Each instruction emits one event: LiquidityAdded, LiquidityRemoved, FeesCollected or PositionSettled, each with the position, its owner, the pair's index and the two token amounts that moved. The program reference lists their fields.