Skip to main content

Pair

Class uniquely representing a pool. It should be created using a dedicated constructor.

export class Pair {
public tokenX: PublicKey;
public tokenY: PublicKey;
public feeTier: FeeTier;
public feeTierAddress: PublicKey | null;
public tickSpacing: number;
}

Methods​

Constructor​

constructor(first: PublicKey, second: PublicKey, feeTier: FeeTier)

Params​

NameTypeDescription
firstPublicKeyToken Mint key.
secondPublicKeyToken Mint key.
feeTierFeeTierFee tier struct chosen from the fee tiers existing on pool.

getAddressAndBump​

getAddressAndBump(programId: PublicKey): [PublicKey, number]

Params​

NameTypeDescription
programIdPublicKeyId of the market program.

Return​

TypeDescription
PublicKeyPool address.
numberbump.

getAddress​

getAddress(programId: PublicKey): PublicKey

Params​

NameTypeDescription
programIdPublicKeyId of the market program.

Return​

TypeDescription
PublicKeyPool address.

getFeeTierAddress​

getFeeTierAddress(programId: PublicKey)

Params​

NameTypeDescription
programIdPublicKeyId of the market program.

Return​

TypeDescription
PublicKeyFeeTier address.

Network

Network enum used for initializing the market object.

export enum Network {
LOCAL,
DEV,
TEST,
MAIN,
}

Market

Market class wraps the functionality of the protocol.

Initialization​

Market can be initialized with or without the Provider. Provider can be omitted when using the market for queries only.

public static build(
network: Network,
wallet: IWallet,
connection: Connection,
programId?: PublicKey
)
public static async buildWithoutProvider(
network: Network,
connection: Connection,
programId?: PublicKey
)

Anchor IDL​

If you wish to use raw instructions you can use the provided idl. Idl can be accessed through program property on the Market object.

const market = Market.buildWithoutProvider(...)
market.program;

Entrypoint methods​

Most entrypoints have 3 methods following a pattern of entrypointName, entrypointNameTx, entrypointNameIx. entrypointName methods call and sign the entrypoint with the singer passed in as an argument. entrypointNameTx returns a Tx sometimes with additional instructions that are necessary for performing an action on the protocol. entrypointNameIx returns a single instruction. The exception to this rule is createPool. Some methods have optional parameters which contain information about the current state. When using custom caching for invariants state it's recommended to pass the data when calling these functions. Otherwise the state will be fetched from the RPC.

CreateState​

async createStateIx(admin?: PublicKey)
async createStateTx(admin?: PublicKey)
async createState(admin: PublicKey, signer: Keypair)

Params​

NameTypeDescription
adminPublicKeyAdmin account, defaults to wallet address.
signerKeypairTransaction signer.

Return​

Returns instruction or transaction with create state instruction.

CreateFeeTier​

async createFeeTierIx(createFeeTier: CreateFeeTier)
async createFeeTierTx(createFeeTier: CreateFeeTier)
async createFeeTier(createFeeTier: CreateFeeTier)

Params​

export interface CreateFeeTier {
feeTier: FeeTier;
admin?: PublicKey;
}
NameTypeDescription
feeTierFeeTierFee tier to be created.
adminPublicKeyAdmin account, defaults to wallet address.
signerKeypairTransaction signer.

Return​

Returns instruction or transaction with create fee tier instruction.

CreatePool​

async createPoolTx(createPool: CreatePoolTx, cache: CreatePoolCache = {})
async createPool(createPool: CreatePool, cache: CreatePoolCache = {})

Params​

export interface CreatePool {
pair: Pair;
payer: Keypair;
initTick?: number;
}
export interface CreatePoolTx {
pair: Pair;
payer?: Keypair;
initTick?: number;
}

Params​

NameTypeDescription
pairPairPool identifier for the tick.
payerKeypairSpecifies the signer of the transaction and owner of the pool.
initTicknumberOptional parameter specifying the initial price tick.

Return​

NameTypeDescription
transactionTransactionCreate pool transaction. Containing initReserves and createPool instructions.
signersKeypair[]Array of signers with reserve and tickmap accounts.

CreateTick​

async createTickIx(createTick: CreateTick, cache: CreateTickInstructionCache = {})
async createTickTx(createTick: CreateTick, cache: CreateTickInstructionCache = {})
async createTick(createTick: CreateTick, signer: Keypair, cache: CreateTickInstructionCache = {})

Params​

export interface CreateTick {
pair: Pair;
index: number;
payer?: PublicKey;
}
NameTypeDescription
pairPairPool identifier for the tick.
indexnumberTick index.
payerPublicKeyOwner of the tick.
signerKeypairTransaction signer.

Return​

Returns instruction or transaction with create tick instruction.

CreatePositionList​

async createPositionListIx(owner: PublicKey, signer?: PublicKey)
async createPositionListTx(owner: PublicKey, signer?: PublicKey)
async createPositionList(owner: PublicKey, signer: Keypair)

Params​

NameTypeDescription
ownerPublicKeyOwner of the position list, defaults to wallet address.
signerPublicKey/KeypairTransaction signer, defaults to owner

Return​

Returns instruction or transaction with create position list instruction.

CreatePosition​

async createPositionIx(createPosition: CreatePosition, cache: CreatePositionTransactionCache = {})
async createPositionTx(createPosition: CreatePosition, cache: CreatePositionTransactionCache = {})
async createPosition(createPosition: CreatePosition, signer: Keypair, cache: CreatePositionTransactionCache = {})

Params​

export interface CreatePosition {
pair: Pair;
owner?: PublicKey;
userTokenX: PublicKey;
userTokenY: PublicKey;
lowerTick: number;
upperTick: number;
liquidityDelta: BN;
knownPrice: BN;
slippage: BN;
}
NameTypeDescription
pairPairUnique pool identifier
ownerPublicKeyAccount that will pay for allocation
signerKeypairAccount that will sign the transaction
lowerTicknumberLower tick index for the position
upperTicknumberUpper tick index for the position
liquidityDeltaBNliquidity of the position
knownPriceBNPrice at which the position should be crated
slippageBNSlippage is based on price impact and calculated by dividing by DENOMINATOR (10^12).
userTokenXPublicKeyUser tokenX account
userTokenYPublicKeyUser tokenY account

Return​

MethodDescription
createPositionIxCreate position instruction
createPositionTxTransaction with create position instruction. If either of the ticks or position list doesn't exist, transaction will contain createTick instructions for the position ticks, and createPositionList instructions.

CreatePoolAndPosition​

This methods combines create pool and create position into one method.

async createPoolAndPositionTx(params: CreatePoolAndPosition, payer?: { publicKey: PublicKey }, cache: CreatePoolAndPositionCache = {})
async createPoolAndPosition(createPool: CreatePoolAndPosition, signer: Keypair, cache: CreatePoolAndPositionCache = {})
export interface CreatePoolAndPosition extends CreatePosition {
initTick?: number;
}

Params​

NameTypeDescription
initTicknumberInitial price tick for the pool.
signer/payerKeypair/{publicKey: PublicKey }Owner of the pool and the position.

Return​

NameTypeDescription
createPoolTxTransactionCreate pool transaction. Containing initReserves and createPool instructions.
createPositionTxTransactionTransaction with create position instruction and createTick instructions. If position list doesn't exist, transaction will contain createPositionList instructions.
createPoolSignersKeypair[]Array of signers with reserve and tickmap accounts.

CreatePoolWithSqrtPriceAndPosition​

async createPoolWithSqrtPriceAndPositionTx(params: CreatePosition, payer?: { publicKey: PublicKey }, cache: CreatePoolAndPositionCache = {})
async createPoolWithSqrtPriceAndPosition(params: CreatePosition, signer: Keypair, cache: CreatePoolAndPositionCache = {})

Params​

Initial price for the pool is taken from the position being created.

NameTypeDescription
signer/payerKeypair/{publicKey: PublicKey }Owner of the pool and the position.

Return​

NameTypeDescription
createPoolTxTransactionCreate pool transaction. Containing initReserves and createPool instructions.
createPositionTxTransactionTransaction with create position instruction and createTick instructions. If position list doesn't exist, transaction will contain createPositionList instructions.
createPoolSignersKeypair[]Array of signers with reserve and tickmap accounts.

Swap​

Performs a swap operation on the protocol. This function allows for passing Tick account addresses explicitly or computes them based on the limit provided in {tickCrosses: LIMIT} struct. In case of swaps where native tokens are used and the transaction is batched with creating, initializing and unwrapping ata account limit is given by TICK_CROSSES_PER_IX_NATIVE_TOKEN and should be passed explicitly. Determine necessary tick addresses based on simulateSwap function to lower the transaction cost.

async swapIx(swap: Swap, cache: SwapCache = {}, ticks: Ticks = { tickCrosses: TICK_CROSSES_PER_IX })
async swapTx(swap: Swap, cache: SwapCache = {}, ticks: Ticks = { tickCrosses: TICK_CROSSES_PER_IX })
async swap(swap: Swap, signer: Keypair, cache: SwapCache = {}, ticks: Ticks = { tickCrosses: TICK_CROSSES_PER_IX })

Params​

export interface Swap {
pair: Pair;
owner?: PublicKey;
xToY: boolean;
amount: BN;
estimatedPriceAfterSwap: Decimal;
slippage: Decimal;
accountX: PublicKey;
accountY: PublicKey;
byAmountIn: boolean;
referralAccount?: PublicKey;
}
NameTypeDescription
signerPublicKeySigner of the transaction.
ownerPublicKeyOwner of the token accounts.
slippageBNSlippage is based on price impact and calculated by dividing by DENOMINATOR (10^12).
estimatedPriceAfterSwapBNVariable affected by slippage; swap will fail if the final price exceeds the slippage-adjusted target price.
pairPairUnique pool identifier
accountXPublicKeyUser's account for tokenX; must exist before the swap is performed.
accountYPublicKeyUser's account for tokenY; must exist before the swap is performed.
byAmountInbooleanSpecifies whether the amount is used as input (True) or output (False).
xToYbooleanDetermines the direction of the swap, either from tokenX to tokenY or vice versa.
referralAccountPublicKeyOptional parameter that allows the user to specify if the referral fees should be applied
ticksTicksTick limit for the swap or tick addresses

Return​

Swap instruction or transaction with swap instruction.

ClaimFee​

async claimFeeIx(claimFee: ClaimFee, cache: ClaimFeeCache = {})
async claimFeeTx(claimFee: ClaimFee, cache: ClaimFeeCache = {})
async claimFee(claimFee: ClaimFee, signer: Keypair, cache: ClaimFeeCache = {})

Params​

export interface ClaimFee {
pair: Pair;
owner?: PublicKey;
userTokenX: PublicKey;
userTokenY: PublicKey;
index: number;
}
NameTypeDescription
pairPairUnique pool identifier.
signerPublicKeySigner of the transaction.
ownerPublicKeyOwner of the token accounts and the position.
indexnumberIndex of the position to claim fee from.
userTokenXPublicKeyUser's token account for tokenX; must exist before the swap is performed.
userTokenYPublicKeyUser's token account for tokenY; must exist before the swap is performed.

Returns​

Claim fee instruction or transaction with claim fee instruction.

WithdrawProtocolFee​

async withdrawProtocolFeeIx(withdrawProtocolFee: WithdrawProtocolFee, cache: WithdrawProtocolFeeCache = {})
async withdrawProtocolFeeTx(withdrawProtocolFee: WithdrawProtocolFee, cache: WithdrawProtocolFeeCache = {})
async withdrawProtocolFee(withdrawProtocolFee: WithdrawProtocolFee, signer: Keypair, cache: WithdrawProtocolFeeCache = {})

Params​

export interface WithdrawProtocolFee {
pair: Pair;
accountX: PublicKey;
accountY: PublicKey;
admin?: PublicKey;
}
NameTypeDescription
pairPairUnique pool identifier.
signerPublicKeySigner of the transaction.
adminPublicKeyOwner of the token accounts and the fee receiver for the pool.
accountXPublicKeyAdmin's token account for tokenX; must exist before the swap is performed.
accountYPublicKeyAdmin's token account for tokenY; must exist before the swap is performed.

Return​

Returns withdraw protocol fee instruction or transaction with protocol fee instruction.

UpdateSecondsPerLiquidity​

async updateSecondsPerLiquidityIx(updateSecondsPerLiquidity: UpdateSecondsPerLiquidity)
async updateSecondsPerLiquidityTx(updateSecondsPerLiquidity: UpdateSecondsPerLiquidity)
async updateSecondsPerLiquidity(updateSecondsPerLiquidity: UpdateSecondsPerLiquidity, signer: Keypair)

Params​

export interface UpdateSecondsPerLiquidity {
pair: Pair;
owner?: PublicKey;
signer?: PublicKey;
lowerTickIndex: number;
upperTickIndex: number;
index: number;
}
NameTypeDescription
pairPairUnique pool identifier.
signerPublicKeySigner of the transaction.
ownerPublicKeyOwner of the position
lowerTickIndexnumberLower tick index for the position
upperTickIndexnumberUpper tick index for the position

Return​

Return update seconds per liquidity instruction or transaction with the update seconds per liquidity instruction.

ChangeProtocolFee​

async changeProtocolFeeIx(changeProtocolFee: ChangeProtocolFee)
async changeProtocolFeeTx(changeProtocolFee: ChangeProtocolFee)
async changeProtocolFee(changeProtocolFee: ChangeProtocolFee, signer: Keypair)

Params​

export interface ChangeProtocolFee {
pair: Pair;
admin?: PublicKey;
protocolFee: BN;
}
NameTypeDescription
pairPairUnique pool identifier.
signerPublicKeySigner of the transaction.
adminPublicKeyAdmin of the protocol.
protocolFeeBNNew protocol fee.

Return​

Returns change protocol fee instruction or transaction with protocol fee instruction.

TransferPositionOwnership​

async transferPositionOwnershipIx(transferPositionOwnership: TransferPositionOwnership, cache: TransferPositionCache = {})
async transferPositionOwnershipTx(transferPositionOwnership: TransferPositionOwnership, cache: TransferPositionCache = {})
async transferPositionOwnership(transferPositionOwnership: TransferPositionOwnership, signer: Keypair, cache: TransferPositionCache = {})

Params​

export interface TransferPositionOwnership {
owner?: PublicKey;
recipient?: PublicKey;
index: number;
}
NameTypeDescription
signerKeypairSigner of the transaction.
ownerPublicKeyOwner of the transferred position.
recipientPublicKeyRecipient of the transferred position.
indexnumberIndex of the transferred position.

Simple Queries​

getTickmap​

Returns a tickmap for the given pair.

async getTickmap(pair: Pair, pool?: { tickmap: PublicKey }): Promise<Tickmap>

Params​

NameTypeDescription
pairPairUnique pool identifier.
pool{ tickmap: PublicKey }Struct containing tickmap address to avoid extra fetches.

getFeeTier​

Fetches fee tier account if it exits.

async getFeeTier(feeTier: FeeTier): Promise<FeeTier>

Params​

NameTypeDescription
feeTierFeeTierFeeTier to fetch.

getPoolByAddress​

Fetches a pool based on it's address.

async getPoolByAddress(address: PublicKey): Promise<PoolStructure>

Params​

NameTypeDescription
addressPublicKeyPoolAddress.

getPool​

Fetches a pool based on it's address.

async getPool(pair: Pair): Promise<PoolStructure>

Params​

NameTypeDescription
pairPairUnique pool identifier.

isInitialized​

Checks if a tick is initialized for a given pool.

async isInitialized(pair: Pair, index: number, pool?: { tickmap: PublicKey; tickSpacing: number }, tickmap?: Tickmap): Promise<boolean>

Params​

NameTypeDescription
pairPairUnique pool identifier.
indexnumberIndex of the tick.
pool{ tickmap: PublicKey; tickSpacing: number }Pool data containing tickmap address and tick spacing.
tickmapTickmapTickmap account data for the pool.

getTick​

Fetches a tick account.

async getTick(pair: Pair, index: number): Promise<Tick>

Params​

NameTypeDescription
pairPairUnique pool identifier.
indexnumberIndex of the tick.

getTickByPool​

Fetches a tick account based on pool address.

async getTickByPool(poolAddress: PublicKey, index: number): Promise<Tick>

Params​

NameTypeDescription
poolAddressPublicKeyPool account address.
indexnumberIndex of the tick.

getPositionList​

Fetches the position list.

async getPositionList(owner: PublicKey): Promise<PositionList>

Params​

NameTypeDescription
ownerPublicKeyOwner of the position list.

getPosition​

Returns position account.

async getPosition(owner: PublicKey, index: number): Promise<Position>

Params​

NameTypeDescription
ownerPublicKeyOwner of the position list.
indexnumberIndex of the position in the list.

getState​

Returns the state account.

async getState(): Promise<State>

getOracle​

Fetches oracle account.

async getOracle(pair: Pair, pool?: { oracleAddress: PublicKey }): Promise<Oracle>

Params​

NameTypeDescription
pairPairUnique pool identifier.
pool{oracleAddress:PublicKey}Struct containing oracle address.

Complex Queries​

getAllPosition​

Returns all position for invariant

async getAllPositions(): Promise<Position[]>

getAllPools​

Returns all the pools which exist on invariant.

async getAllPools(): Promise<PoolStructure[]>

getAllIndexedTicks​

Gets all ticks for given pair and creates a Map from number to Tick.

async getAllIndexedTicks(pair: Pair): Promise<Map<number, Tick>>

Params​

NameTypeDescription
pairPairUnique pool identifier.

getAllTicks​

Fetches all ticks for a pool.

async getAllTicks(pair: Pair): Promise<Tick[]>

Params​

NameTypeDescription
pairPairUnique pool identifier.

getLiquidityOnTicks​

Returns an array of Ticks containing only liquidity values and indexes.

async getLiquidityOnTicks(pair: Pair): Promise<{liquidity:BN, index: number}>

Params​

NameTypeDescription
pairPairUnique pool identifier.

getAllUserLockedPositions​

Fetches all locked user positions.

async getAllUserLockedPositions(owner: PublicKey): Promise<LockedPosition[]>

Params​

NameTypeDescription
ownerPublicKeyOwner of the position.

getAllUserPositions​

Fetches all locked user positions.

async getAllUserPositions(owner: PublicKey): Promise<PositionStructure[]>

Params​

NameTypeDescription
ownerPublicKeyOwner of the position.

getPositionsForPool​

Fetches all position for a given pool.

async getPositionsForPool(pool: PublicKey): Promise<Position[]>

Params​

NameTypeDescription
poolPublicKeyPool address.

getPositionsFromRange​

Fetches user positions for a specified range. Range should start at 0 or higher and end at position list head or lower.

async getPositionsFromRange(owner: PublicKey, lowerIndex: number, upperIndex: number): Promise<Position[]>

Params​

NameTypeDescription
ownerPublicKeyPosition owner public key.
lowerIndexnumberMin index of the range.
upperIndexnumberMax index of the range.

getPositionsFromIndexes​

Fetches an array of users positions.

async getPositionsFromIndexes(owner: PublicKey, indexes: number[]): Promise<Position[]>

Params​

NameTypeDescription
ownerPublicKeyPosition owner public key.
indexesnumber[]Indexes of the owner positions.

getAllPoolLiquidityInTokens​

Returns the total liquidity amount for a pool expressed in tokens.

async getAllPoolLiquidityInTokens(poolAddress: PublicKey): Promise<BN>

Params​

NameTypeDescription
poolAddressPublicKeyPool account address.

getActiveLiquidityInTokens​

Returns the total active liquidity amount for a pool expressed in tokens.

async getActiveLiquidityInTokens(poolAddress: PublicKey, currentTickIndex: number): Promise<BN>

Params​

NameTypeDescription
poolAddressPublicKeyPool account address.
currentTickIndexnumberCurrent price index of the pool.

getReserveBalances​

Returns current balances of the pool.

async getReserveBalances(pair: Pair): Promise<{x: BN, y: BN}>

Params​

NameTypeDescription
pairPairUnique pool identifier.

Return​

NameTypeDescription
xBNBalance of the token X reserve
yBNBalance of the token Y reserve

getGlobalFee​

Returns token fees approximation for a pool.

async getGlobalFee(pair: Pair, pool?: PoolStructure): Promise<{feeX: BN, feeY: BN}>

Params​

NameTypeDescription
pairPairUnique pool identifier.
poolPoolStructurePrefetched pool state.

Return​

NameTypeDescription
feeXBNCollected token X fee.
feeYBNCollected token Y fee.

getVolume​

Returns token volumes for a pool.

async getVolume(pair: Pair, pool?: PoolStructure): Promise<{volumeX: BN, volumeY: BN}>

Params​

NameTypeDescription
pairPairUnique pool identifier.
poolPoolStructurePrefetched pool state.

Return​

NameTypeDescription
volumeXBNToken X volume.
volumeYBNToken Y volume.

getPairLiquidityValues​

Returns token values of liquidity for a pool.

async getPairLiquidityValues(pair: Pair, cachedPool?: PoolStructure): Promise<{liquidityX: BN, liquidityY: BN }>

Params​

NameTypeDescription
pairPairUnique pool identifier.
cachedPoolPoolStructurePrefetched pool state.

Return​

NameTypeDescription
liquidityXBNToken X liquidity.
liquidityYBNToken Y liquidity.

getWholeLiquidity​

Returns total liquidity for a pool.

async getWholeLiquidity(pair: Pair): Promise<BN>

Params​

NameTypeDescription
pairPairUnique pool identifier.

Account addresses​

getTickAddress​

getTickAddress(pair: Pair, index: number): {tickAddress: PublicKey, tickBump: number}

Params​

NameTypeDescription
pairPairPool on which the tick exists.
indexnumberIndex of the tick.

getTickAddressByPool​

getTickAddressByPool(poolAddress: PublicKey, index: number): {tickAddress: PublicKey, tickBump: number}

Params​

NameTypeDescription
poolAddressPublicKeyAddress of the pool on which the tick exists.
indexnumberIndex of the tick.

getPositionListAddress​

getPositionListAddress(owner: PublicKey): {positionListAddress: PublicKey, positionListBump: number}

Params​

NameTypeDescription
ownerPublicKeyAddress of the position list owner.

getPositionAddress​

getPositionAddress(owner: PublicKey, index: number): {positionAddress: PublicKey, positionBump: number}

Params​

NameTypeDescription
ownerPublicKeyAddress of the position list owner.
indexnumberIndex of the position on the position list.

getNewPositionAddress​

Returns the address of a new position.

async getNewPositionAddress(owner: PublicKey, positionListHead?: number): {positionAddress: PublicKey, positionBump: number}

Params​

NameTypeDescription
ownerPublicKeyOwner of the position list.
positionListHeadnumberHead of the position in the list; it will be fetched if not passed explicitly.

getStateAddress​

Returns the state address.

getStateAddress(): AddressAndBump

getFeeTierAddress​

Returns the address of the provided fee tier.

getFeeTierAddress(feeTier: FeeTier): AddressAndBump

Params​

NameTypeDescription
feeTierFeeTierFeeTier struct.

getEventOptAccount​

Returns the address of the account used for optimizing event queries, this account will always be present in a transaction if an event may occur.

getEventOptAccount(): AddressAndBump

Utils

MIN_BALANCE_FOR_RENT_EXEMPT​

Utility used when creating pool to avoid fetching data that will most likely remain constant.

export const MIN_BALANCE_FOR_RENT_EXEMPT = {
[Network.LOCAL]: 2039280, // AnchorProvider defaults to solana's minimum amount
[Network.DEV]: 19924,
[Network.TEST]: 19924,
[Network.MAIN]: 19924,
};

FEE_TIERS​

To create or choose a pool you must first choose a fee Tier. FeeTiers are created by the contract administrator, and the current list of them is stored in the sdk under FEE_TIERS. These are possible feeTiers on which the pools may exist. Creating pairs with them and fetching the pools is one of the ways of acquiring existing pools.

export const FEE_TIERS: FeeTier[] = [
{ fee: fromFee(new BN(10)), tickSpacing: 1 },
{ fee: fromFee(new BN(20)), tickSpacing: 5 },
{ fee: fromFee(new BN(50)), tickSpacing: 5 },
{ fee: fromFee(new BN(100)), tickSpacing: 10 },
{ fee: fromFee(new BN(300)), tickSpacing: 30 },
{ fee: fromFee(new BN(1000)), tickSpacing: 100 },
];

Swap simulation​

Swap simulation provides all data necessary to perform a swap.

export interface SimulateSwapInterface {
xToY: boolean
byAmountIn: boolean
swapAmount: BN
priceLimit?: BN
slippage: BN
ticks: Map<number, Tick>
tickmap: Tickmap
pool: PoolData
maxVirtualCrosses: number | undefined
maxCrosses: number | undefined
}

export interface SimulationResult {
status: SimulationStatus
amountPerTick: BN[]
crossedTicks: number[]
accumulatedAmountIn: BN
accumulatedAmountOut: BN
accumulatedFee: BN
minReceived: BN
priceImpact: BN
priceAfterSwap: BN
}

export const simulateSwap = (swapParameters: SimulateSwapInterface): SimulationResult

Input​

NameTypeDescription
maxVirtualCrossesnumberLimit for virtual crosses, should be set to TICK_VIRTUAL_CROSSES_PER_IX
maxCrossesnumberLimit on the number of accounts that can be used for ticks
tickmapTickmapTickmap state
poolPoolPool state
ticksMap<number, Tick>Map from tick index to tick account
priceLimitBNIf omitted, allows the simulation to continue until reaching either the cross limit or the pool's limiting price
slippageBNslippage to be applied on the price limit

Output​

NameTypeDescription
statusSimulationStatusContains an error if there was one
crossedTicksnumber[]Contains the indexes of the ticks that are necessary for the swap to be performed
accumulatedAmountInBNContains the input amount for the swap
accumulatedAmountOutBNExpected output amount
accumulatedFeeBNFee amount that will be paid
minReceivedBNLowest amount of tokens that could be gained from the swap
priceImpactBNImpact on the price after the swap
priceAfterSwapBNEstimated value of the price after the swap is completed

The following is an example of usage.

const poolData = await market.getPool(pair);
const tickmap = await market.getTickmap(pair, pool);
const ticks = await market.getAllIndexedTicks(pair);

const simProps: SimulateSwapInterface = {
xToY: true,
byAmountIn: true,
swapAmount: new BN(1e10),
priceLimit: poolData.sqrtPrice,
slippage: new BN(DENOMINATOR),
ticks,
tickmap,
pool: poolData,
maxCrosses: TICK_CROSSES_PER_IX,
};

const result = simulateSwap(simProps);

if (simulation.status != SimulationStatus.Ok) {
throw new Error(simulation.status);
}

NativeAtaUtils​

These utils can be used for creating native ata instructions. These can be chained with protocol instructions to create an atomic transaction.

export const createNativeAtaInstructions = (
nativeAccount: PublicKey,
owner: PublicKey,
network: Network
): WrappedEthInstructions
export const createNativeAtaWithTransferInstructions = (
nativeAccount: PublicKey,
owner: PublicKey,
network: Network,
nativeAmount: number
): WrappedEthTransferInstructions

Params​

NameTypeDescription
nativeAccountPublicKeyWrapped eth account address.
ownerPublicKeyAccount that will own the new ata account.
networkNetworkUsed to determine rent exemption fee.
nativeAmountnumberAmount of native tokens.

Output​

export interface WrappedEthInstructions {
createIx: TransactionInstruction;
initIx: TransactionInstruction;
unwrapIx: TransactionInstruction;
}
export interface WrappedEthTransferInstructions extends WrappedEthInstructions {
transferIx: TransactionInstruction;
}
NameTypeDescription
createIxTransactionInstructionInstruction used for creating new account.
initIxTransactionInstructionInstruction used for initializing new account.
unwrapIxTransactionInstructionInstruction used for removing ata after completed transaction.
transferIxTransactionInstructionTransfer instruction only needed if you pass tokens to the protocol.

Types

Event types​

These types describe events emitted by invariant contract.

export interface RemovePositionEvent {
owner: PublicKey;
pool: PublicKey;
id: BN;
liquidity: BN;
upperTick: number;
lowerTick: number;
currentTick: number;
upperTickSecondsPerLiquidityOutside: BN;
lowerTickSecondsPerLiquidityOutside: BN;
poolSecondsPerLiquidityGlobal: BN;
currentTimestamp: BN;
}
export interface CreatePositionEvent {
owner: PublicKey;
pool: PublicKey;
id: BN;
liquidity: BN;
upperTick: number;
lowerTick: number;
currentTimestamp: BN;
secondsPerLiquidityInsideInitial: BN;
}

State types​

State types are typescript representation of anchor accounts. Raw Prefix indicates that the wrapper types are still in Decimal form and must be parsed.

export interface Decimal {
v: BN;
}
export interface State {
admin: PublicKey;
nonce: number;
authority: PublicKey;
bump: number;
}
export interface RawFeeTierStructure {
fee: Decimal;
tickSpacing: number;
bump: number;
}
export interface FeeTierStructure {
fee: BN;
tickSpacing: number;
bump: number;
}
export interface RawPoolStructure {
tokenX: PublicKey;
tokenY: PublicKey;
tokenXReserve: PublicKey;
tokenYReserve: PublicKey;
positionIterator: BN;
tickSpacing: number;
fee: Decimal;
protocolFee: Decimal;
liquidity: Decimal;
sqrtPrice: Decimal;
currentTickIndex: number;
tickmap: PublicKey;
feeGrowthGlobalX: Decimal;
feeGrowthGlobalY: Decimal;
feeProtocolTokenX: BN;
feeProtocolTokenY: BN;
secondsPerLiquidityGlobal: Decimal;
startTimestamp: BN;
lastTimestamp: BN;
feeReceiver: PublicKey;
oracleAddress: PublicKey;
oracleInitialized: boolean;
bump: number;
}
export interface PoolStructure {
tokenX: PublicKey;
tokenY: PublicKey;
tokenXReserve: PublicKey;
tokenYReserve: PublicKey;
positionIterator: BN;
tickSpacing: number;
fee: BN;
protocolFee: BN;
liquidity: BN;
sqrtPrice: BN;
currentTickIndex: number;
tickmap: PublicKey;
feeGrowthGlobalX: BN;
feeGrowthGlobalY: BN;
feeProtocolTokenX: BN;
feeProtocolTokenY: BN;
secondsPerLiquidityGlobal: BN;
startTimestamp: BN;
lastTimestamp: BN;
feeReceiver: PublicKey;
oracleAddress: PublicKey;
oracleInitialized: boolean;
bump: number;
}
export interface Tickmap {
bitmap: number[];
}
export interface PositionList {
head: number;
bump: number;
}
export interface RawTick {
pool: PublicKey;
index: number;
sign: boolean;
liquidityChange: Decimal;
liquidityGross: Decimal;
sqrtPrice: Decimal;
feeGrowthOutsideX: Decimal;
feeGrowthOutsideY: Decimal;
secondsPerLiquidityOutside: Decimal;
bump: number;
}
export interface Tick {
pool: PublicKey;
index: number;
sign: boolean;
liquidityChange: BN;
liquidityGross: BN;
sqrtPrice: BN;
feeGrowthOutsideX: BN;
feeGrowthOutsideY: BN;
secondsPerLiquidityOutside: BN;
bump: number;
}
export interface RawPosition {
owner: PublicKey;
pool: PublicKey;
id: BN;
liquidity: Decimal;
lowerTickIndex: number;
upperTickIndex: number;
feeGrowthInsideX: Decimal;
feeGrowthInsideY: Decimal;
secondsPerLiquidityInside: Decimal;
lastSlot: BN;
tokensOwedX: Decimal;
tokensOwedY: Decimal;
bump: number;
}
export interface Position {
owner: PublicKey;
pool: PublicKey;
id: BN;
liquidity: BN;
lowerTickIndex: number;
upperTickIndex: number;
feeGrowthInsideX: BN;
feeGrowthInsideY: BN;
secondsPerLiquidityInside: BN;
lastSlot: BN;
tokensOwedX: BN;
tokensOwedY: BN;
bump: number;
}
export interface PositionStructure {
tokenX: PublicKey;
tokenY: PublicKey;
feeTier: FeeTier;
amountTokenX: BN;
amountTokenY: BN;
lowerPrice: BN;
upperPrice: BN;
unclaimedFeesX: BN;
unclaimedFeesY: BN;
}
export interface FeeTier {
fee: BN;
tickSpacing: number;
}

Cache Types​

Cache types are a combination of queryable state information that must be passed if you wish to avoid querying additional data and maximize the speed. pool, positionList, tickmap, position fields correspond to real state that can be fetched. In case of positionList you must additionally specify if the list is initialized (i.e. the account exists already). TickmapWithReserves type serves as a thinner interface on pool state.

tokenXProgram/tokenXProgramAddress and tokenYProgram/tokenYProgramAddress are used to store the associated token program address (SPL or Token 2022). lowerTickExists and upperTickExists indicate the state of the ticks for the position you wish to create. minRentExemption contains the minimum amount of tokens that are needed for an account to be exempt from rent.

export interface PositionListCache {
initialized: boolean;
head: number;
}
export interface TickmapWithReserves {
tokenXReserve: PublicKey;
tokenYReserve: PublicKey;
tickmap: PublicKey;
}
export interface CreatePositionInstructionCache {
pool?: TickmapWithReserves;
positionList?: PositionListCache;
tokenXProgramAddress?: PublicKey;
tokenYProgramAddress?: PublicKey;
}
export interface CreatePositionTransactionCache
extends CreatePositionInstructionCache {
lowerTickExists?: boolean;
upperTickExists?: boolean;
}
export interface CreateTickInstructionCache {
pool?: { tickmap: PublicKey };
tokenXProgramAddress?: PublicKey;
tokenYProgramAddress?: PublicKey;
}
export interface CreatePoolCache {
minRentExemption?: number;
tokenXProgramAddress?: PublicKey;
tokenYProgramAddress?: PublicKey;
}
export interface CreatePoolAndPositionCache extends CreatePoolCache {
positionList?: PositionListCache;
}
export interface SwapCache {
tickmap?: Tickmap;
pool?: PoolStructure;
tokenXProgram?: PublicKey;
tokenYProgram?: PublicKey;
}
export interface ClaimFeeCache {
position?: Position;
pool?: PoolStructure;
tokenXProgram?: PublicKey;
tokenYProgram?: PublicKey;
}
export interface WithdrawProtocolFeeCache {
pool?: PoolStructure;
tokenXProgram?: PublicKey;
tokenYProgram?: PublicKey;
}
export interface RemovePositionCache {
pool?: PoolStructure;
position?: Position;
positionList?: PositionList;
tokenXProgram?: PublicKey;
tokenYProgram?: PublicKey;
}
export interface TransferPositionCache {
ownerPositionList?: PositionList;
recipientPositionList?: PositionList;
}

Other​

type TickAddresses = {
tickAddresses: PublicKey[];
tickCrosses?: never;
};
type TickCrosses = {
tickCrosses: number;
tickAddresses?: never;
};
type Ticks = NonNullable<TickAddresses | TickCrosses>;