repo_id
stringclasses
279 values
file_path
stringlengths
43
179
content
stringlengths
1
4.18M
__index_level_0__
int64
0
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/close-bundled-position-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to close a bundled position in a Whirlpool. * * @category Instruction Types * @param bundledPosition - PublicKey for the bundled position. * @param positionBundle - PublicKey for the position bundle. * @param positionBundleTokenAccount - The associated token address for the position bundle token in the owners wallet. * @param positionBundleAuthority - authority that owns the token corresponding to this desired bundled position. * @param bundleIndex - The bundle index that holds the bundled position. * @param receiver - PublicKey for the wallet that will receive the rented lamports. */ export type CloseBundledPositionParams = { bundledPosition: PublicKey; positionBundle: PublicKey; positionBundleTokenAccount: PublicKey; positionBundleAuthority: PublicKey; bundleIndex: number; receiver: PublicKey; }; /** * Close a bundled position in a Whirlpool. * * #### Special Errors * `InvalidBundleIndex` - If the provided bundle index is out of bounds. * `ClosePositionNotEmpty` - The provided position account is not empty. * * @category Instructions * @param program - program object containing services required to generate the instruction * @param params - CloseBundledPositionParams object * @returns - Instruction to perform the action. */ export function closeBundledPositionIx( program: Program<Whirlpool>, params: CloseBundledPositionParams, ): Instruction { const { bundledPosition, positionBundle, positionBundleTokenAccount, positionBundleAuthority, bundleIndex, receiver, } = params; const ix = program.instruction.closeBundledPosition(bundleIndex, { accounts: { bundledPosition, positionBundle, positionBundleTokenAccount, positionBundleAuthority, receiver, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/delete-position-bundle-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to delete a PositionBundle account. * * @category Instruction Types * @param owner - PublicKey for the wallet that owns the position bundle token. * @param positionBundle - PublicKey for the position bundle. * @param positionBundleMint - PublicKey for the mint for the position bundle token. * @param positionBundleTokenAccount - The associated token address for the position bundle token in the owners wallet. * @param receiver - PublicKey for the wallet that will receive the rented lamports. */ export type DeletePositionBundleParams = { owner: PublicKey; positionBundle: PublicKey; positionBundleMint: PublicKey; positionBundleTokenAccount: PublicKey; receiver: PublicKey; }; /** * Deletes a PositionBundle account. * * #### Special Errors * `PositionBundleNotDeletable` - The provided position bundle has open positions. * * @category Instructions * @param program - program object containing services required to generate the instruction * @param params - DeletePositionBundleParams object * @returns - Instruction to perform the action. */ export function deletePositionBundleIx( program: Program<Whirlpool>, params: DeletePositionBundleParams, ): Instruction { const { owner, positionBundle, positionBundleMint, positionBundleTokenAccount, receiver, } = params; const ix = program.instruction.deletePositionBundle({ accounts: { positionBundle: positionBundle, positionBundleMint: positionBundleMint, positionBundleTokenAccount, positionBundleOwner: owner, receiver, tokenProgram: TOKEN_PROGRAM_ID, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-fee-rate-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to set fee rate for a Whirlpool. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space. * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates. * @param feeRate - The new fee rate for this fee-tier. Stored as a hundredths of a basis point. */ export type SetFeeRateParams = { whirlpool: PublicKey; whirlpoolsConfig: PublicKey; feeAuthority: PublicKey; feeRate: number; }; /** * Sets the fee rate for a Whirlpool. * Only the current fee authority has permission to invoke this instruction. * * #### Special Errors * - `FeeRateMaxExceeded` - If the provided fee_rate exceeds MAX_FEE_RATE. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetFeeRateParams object * @returns - Instruction to perform the action. */ export function setFeeRateIx( program: Program<Whirlpool>, params: SetFeeRateParams, ): Instruction { const { whirlpoolsConfig, whirlpool, feeAuthority, feeRate } = params; const ix = program.instruction.setFeeRate(feeRate, { accounts: { whirlpoolsConfig, whirlpool, feeAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-tick-array-ix.ts
import * as anchor from "@coral-xyz/anchor"; import type { Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to initialize a TickArray account. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the initialized tick-array will host ticks for. * @param tickArrayPda - PDA for the tick array account that will be initialized * @param startTick - The starting tick index for this tick-array. Has to be a multiple of TickArray size & the tick spacing of this pool. * @param funder - The account that would fund the creation of this account */ export type InitTickArrayParams = { whirlpool: PublicKey; tickArrayPda: PDA; startTick: number; funder: PublicKey; }; /** * Initializes a TickArray account. * * #### Special Errors * `InvalidStartTick` - if the provided start tick is out of bounds or is not a multiple of TICK_ARRAY_SIZE * tick spacing. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitTickArrayParams object * @returns - Instruction to perform the action. */ export function initTickArrayIx( program: Program<Whirlpool>, params: InitTickArrayParams, ): Instruction { const { whirlpool, funder, tickArrayPda } = params; const ix = program.instruction.initializeTickArray(params.startTick, { accounts: { whirlpool, funder, tickArray: tickArrayPda.publicKey, systemProgram: anchor.web3.SystemProgram.programId, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-default-fee-rate-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import { PDAUtil } from "../utils/public"; /** * Parameters to set the default fee rate for a FeeTier. * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this fee-tier is initialized in * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates. * @param tickSpacing - The tick spacing of the fee-tier that we would like to update. * @param defaultFeeRate - The new default fee rate for this fee-tier. Stored as a hundredths of a basis point. */ export type SetDefaultFeeRateParams = { whirlpoolsConfig: PublicKey; feeAuthority: PublicKey; tickSpacing: number; defaultFeeRate: number; }; /** * Updates a fee tier account with a new default fee rate. The new rate will not retroactively update * initialized pools. * * #### Special Errors * - `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetDefaultFeeRateParams object * @returns - Instruction to perform the action. */ export function setDefaultFeeRateIx( program: Program<Whirlpool>, params: SetDefaultFeeRateParams, ): Instruction { const { whirlpoolsConfig, feeAuthority, tickSpacing, defaultFeeRate } = params; const feeTierPda = PDAUtil.getFeeTier( program.programId, whirlpoolsConfig, tickSpacing, ); const ix = program.instruction.setDefaultFeeRate(defaultFeeRate, { accounts: { whirlpoolsConfig, feeTier: feeTierPda.publicKey, feeAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-reward-ix.ts
import * as anchor from "@coral-xyz/anchor"; import type { Program } from "@coral-xyz/anchor"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { Keypair, PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to initialize a rewards for a Whirlpool * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool config space that the fee-tier will be initialized for. * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS). * @param rewardMint - PublicKey for the reward mint that we'd use for the reward index. * @param rewardVaultKeypair - Keypair of the vault for this reward index. * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool * @param funder - The account that would fund the creation of this account */ export type InitializeRewardParams = { whirlpool: PublicKey; rewardIndex: number; rewardMint: PublicKey; rewardVaultKeypair: Keypair; rewardAuthority: PublicKey; funder: PublicKey; }; /** * Initialize reward for a Whirlpool. A pool can only support up to a set number of rewards. * The initial emissionsPerSecond is set to 0. * * #### Special Errors * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool, * or exceeds NUM_REWARDS, or all reward slots for this pool has been initialized. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitializeRewardParams object * @returns - Instruction to perform the action. */ export function initializeRewardIx( program: Program<Whirlpool>, params: InitializeRewardParams, ): Instruction { const { rewardAuthority, funder, whirlpool, rewardMint, rewardVaultKeypair, rewardIndex, } = params; const ix = program.instruction.initializeReward(rewardIndex, { accounts: { rewardAuthority, funder, whirlpool, rewardMint, rewardVault: rewardVaultKeypair.publicKey, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [rewardVaultKeypair], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-config-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Keypair, PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to initialize a WhirlpoolsConfig account. * * @category Instruction Types * @param whirlpoolsConfigKeypair - Generated keypair for the WhirlpoolsConfig. * @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees. * @param collect_protocol_fees_authority - Authority authorized to collect protocol fees. * @param rewardEmissionsSuperAuthority - Authority authorized to set reward authorities in pools. * @param defaultProtocolFeeRate - The default protocol fee rate. Stored as a basis point of the total fees collected by feeRate. * @param funder - The account that would fund the creation of this account */ export type InitConfigParams = { whirlpoolsConfigKeypair: Keypair; feeAuthority: PublicKey; collectProtocolFeesAuthority: PublicKey; rewardEmissionsSuperAuthority: PublicKey; defaultProtocolFeeRate: number; funder: PublicKey; }; /** * Initializes a WhirlpoolsConfig account that hosts info & authorities * required to govern a set of Whirlpools. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitConfigParams object * @returns - Instruction to perform the action. */ export function initializeConfigIx( program: Program<Whirlpool>, params: InitConfigParams, ): Instruction { const { feeAuthority, collectProtocolFeesAuthority, rewardEmissionsSuperAuthority, defaultProtocolFeeRate, funder, } = params; const ix = program.instruction.initializeConfig( feeAuthority, collectProtocolFeesAuthority, rewardEmissionsSuperAuthority, defaultProtocolFeeRate, { accounts: { config: params.whirlpoolsConfigKeypair.publicKey, funder, systemProgram: SystemProgram.programId, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [params.whirlpoolsConfigKeypair], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/close-position-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to close a position in a Whirlpool. * * @category Instruction Types * @param receiver - PublicKey for the wallet that will receive the rented lamports. * @param position - PublicKey for the position. * @param positionMint - PublicKey for the mint token for the Position token. * @param positionTokenAccount - The associated token address for the position token in the owners wallet. * @param positionAuthority - Authority that owns the position token. */ export type ClosePositionParams = { receiver: PublicKey; position: PublicKey; positionMint: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; }; /** * Close a position in a Whirlpool. Burns the position token in the owner's wallet. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - ClosePositionParams object * @returns - Instruction to perform the action. */ export function closePositionIx( program: Program<Whirlpool>, params: ClosePositionParams, ): Instruction { const { positionAuthority, receiver: receiver, position: position, positionMint: positionMint, positionTokenAccount, } = params; const ix = program.instruction.closePosition({ accounts: { positionAuthority, receiver, position, positionMint, positionTokenAccount, tokenProgram: TOKEN_PROGRAM_ID, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-reward-emissions-super-authority-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to set rewards emissions for a reward in a Whirlpool * * @category Instruction Types * @param whirlpoolsConfig - PublicKey for the WhirlpoolsConfig that we want to update. * @param rewardEmissionsSuperAuthority - Current reward emission super authority in this WhirlpoolsConfig * @param newRewardEmissionsSuperAuthority - New reward emission super authority for this WhirlpoolsConfig */ export type SetRewardEmissionsSuperAuthorityParams = { whirlpoolsConfig: PublicKey; rewardEmissionsSuperAuthority: PublicKey; newRewardEmissionsSuperAuthority: PublicKey; }; /** * Set the whirlpool reward super authority for a WhirlpoolsConfig * Only the current reward super authority has permission to invoke this instruction. * This instruction will not change the authority on any `WhirlpoolRewardInfo` whirlpool rewards. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetRewardEmissionsSuperAuthorityParams object * @returns - Instruction to perform the action. */ export function setRewardEmissionsSuperAuthorityIx( program: Program<Whirlpool>, params: SetRewardEmissionsSuperAuthorityParams, ): Instruction { const { whirlpoolsConfig, rewardEmissionsSuperAuthority, newRewardEmissionsSuperAuthority, } = params; const ix = program.instruction.setRewardEmissionsSuperAuthority({ accounts: { whirlpoolsConfig, rewardEmissionsSuperAuthority: rewardEmissionsSuperAuthority, newRewardEmissionsSuperAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/collect-protocol-fees-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to collect protocol fees for a Whirlpool * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet * @param tokenOwnerAccountB - PublicKey for the associated token account for tokenA in the collection wallet * @param collectProtocolFeesAuthority - assigned authority in the WhirlpoolsConfig that can collect protocol fees */ export type CollectProtocolFeesParams = { whirlpoolsConfig: PublicKey; whirlpool: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; collectProtocolFeesAuthority: PublicKey; }; /** * Collect protocol fees accrued in this Whirlpool. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - CollectProtocolFeesParams object * @returns - Instruction to perform the action. */ export function collectProtocolFeesIx( program: Program<Whirlpool>, params: CollectProtocolFeesParams, ): Instruction { const { whirlpoolsConfig, whirlpool, collectProtocolFeesAuthority, tokenVaultA, tokenVaultB, tokenOwnerAccountA: tokenDestinationA, tokenOwnerAccountB: tokenDestinationB, } = params; const ix = program.instruction.collectProtocolFees({ accounts: { whirlpoolsConfig, whirlpool, collectProtocolFeesAuthority, tokenVaultA, tokenVaultB, tokenDestinationA, tokenDestinationB, tokenProgram: TOKEN_PROGRAM_ID, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-fee-authority-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to set the fee authority in a WhirlpoolsConfig * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param feeAuthority - The current feeAuthority in the WhirlpoolsConfig * @param newFeeAuthority - The new feeAuthority in the WhirlpoolsConfig */ export type SetFeeAuthorityParams = { whirlpoolsConfig: PublicKey; feeAuthority: PublicKey; newFeeAuthority: PublicKey; }; /** * Sets the fee authority for a WhirlpoolsConfig. * The fee authority can set the fee & protocol fee rate for individual pools or set the default fee rate for newly minted pools. * Only the current fee authority has permission to invoke this instruction. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetFeeAuthorityParams object * @returns - Instruction to perform the action. */ export function setFeeAuthorityIx( program: Program<Whirlpool>, params: SetFeeAuthorityParams, ): Instruction { const { whirlpoolsConfig, feeAuthority, newFeeAuthority } = params; const ix = program.instruction.setFeeAuthority({ accounts: { whirlpoolsConfig, feeAuthority, newFeeAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-default-protocol-fee-rate-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to set the default fee rate for a FeeTier. * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates. * @param defaultProtocolFeeRate - The new default protocol fee rate for this config. Stored as a basis point of the total fees collected by feeRate. */ export type SetDefaultProtocolFeeRateParams = { whirlpoolsConfig: PublicKey; feeAuthority: PublicKey; defaultProtocolFeeRate: number; }; /** * Updates a WhirlpoolsConfig with a new default protocol fee rate. The new rate will not retroactively update * initialized pools. * * #### Special Errors * - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetDefaultFeeRateParams object * @returns - Instruction to perform the action. */ export function setDefaultProtocolFeeRateIx( program: Program<Whirlpool>, params: SetDefaultProtocolFeeRateParams, ): Instruction { const { whirlpoolsConfig, feeAuthority, defaultProtocolFeeRate } = params; const ix = program.instruction.setDefaultProtocolFeeRate( defaultProtocolFeeRate, { accounts: { whirlpoolsConfig, feeAuthority, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/open-position-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { METADATA_PROGRAM_ADDRESS, WHIRLPOOL_NFT_UPDATE_AUTH } from ".."; import type { Whirlpool } from "../artifacts/whirlpool"; import type { OpenPositionBumpsData, OpenPositionWithMetadataBumpsData, } from "../types/public/anchor-types"; import { openPositionAccounts } from "../utils/instructions-util"; /** * Parameters to open a position in a Whirlpool. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param ownerKey - PublicKey for the wallet that will host the minted position token. * @param positionPda - PDA for the derived position address. * @param positionMintAddress - PublicKey for the mint token for the Position token. * @param positionTokenAccount - The associated token address for the position token in the owners wallet. * @param tickLowerIndex - The tick specifying the lower end of the position range. * @param tickUpperIndex - The tick specifying the upper end of the position range. * @param funder - The account that would fund the creation of this account */ export type OpenPositionParams = { whirlpool: PublicKey; owner: PublicKey; positionPda: PDA; positionMintAddress: PublicKey; positionTokenAccount: PublicKey; tickLowerIndex: number; tickUpperIndex: number; funder: PublicKey; }; /** * Open a position in a Whirlpool. A unique token will be minted to represent the position in the users wallet. * The position will start off with 0 liquidity. * * #### Special Errors * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - OpenPositionParams object * @returns - Instruction to perform the action. */ export function openPositionIx( program: Program<Whirlpool>, params: OpenPositionParams, ): Instruction { const { positionPda, tickLowerIndex, tickUpperIndex } = params; const bumps: OpenPositionBumpsData = { positionBump: positionPda.bump, }; const ix = program.instruction.openPosition( bumps, tickLowerIndex, tickUpperIndex, { accounts: openPositionAccounts(params), }, ); // TODO: Require Keypair and auto sign this ix return { instructions: [ix], cleanupInstructions: [], signers: [], }; } /** * Open a position in a Whirlpool. A unique token will be minted to represent the position * in the users wallet. Additional Metaplex metadata is appended to identify the token. * The position will start off with 0 liquidity. * * #### Special Errors * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - OpenPositionParams object and a derived PDA that hosts the position's metadata. * @returns - Instruction to perform the action. */ export function openPositionWithMetadataIx( program: Program<Whirlpool>, params: OpenPositionParams & { metadataPda: PDA }, ): Instruction { const { positionPda, metadataPda, tickLowerIndex, tickUpperIndex } = params; const bumps: OpenPositionWithMetadataBumpsData = { positionBump: positionPda.bump, metadataBump: metadataPda.bump, }; const ix = program.instruction.openPositionWithMetadata( bumps, tickLowerIndex, tickUpperIndex, { accounts: { ...openPositionAccounts(params), positionMetadataAccount: metadataPda.publicKey, metadataProgram: METADATA_PROGRAM_ADDRESS, metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH, }, }, ); // TODO: Require Keypair and auto sign this ix return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-fee-tier-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to initialize a FeeTier account. * * @category Instruction Types * @param whirlpoolsConfig - PublicKey for the whirlpool config space that the fee-tier will be initialized for. * @param feeTierPda - PDA for the fee-tier account that will be initialized * @param tickSpacing - The tick spacing this fee tier recommends its default fee rate for. * @param defaultFeeRate - The default fee rate for this fee-tier. Stored as a hundredths of a basis point. * @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees. * @param funder - The account that would fund the creation of this account */ export type InitFeeTierParams = { whirlpoolsConfig: PublicKey; feeTierPda: PDA; tickSpacing: number; defaultFeeRate: number; feeAuthority: PublicKey; funder: PublicKey; }; /** * Initializes a fee tier account usable by Whirlpools in this WhirlpoolsConfig space. * * Special Errors * `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitFeeTierParams object * @returns - Instruction to perform the action. */ export function initializeFeeTierIx( program: Program<Whirlpool>, params: InitFeeTierParams, ): Instruction { const { feeTierPda, whirlpoolsConfig, tickSpacing, feeAuthority, defaultFeeRate, funder, } = params; const ix = program.instruction.initializeFeeTier( tickSpacing, defaultFeeRate, { accounts: { config: whirlpoolsConfig, feeTier: feeTierPda.publicKey, feeAuthority, funder, systemProgram: SystemProgram.programId, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/index.ts
export * from "./close-bundled-position-ix"; export * from "./close-position-ix"; export * from "./close-position-with-token-extensions-ix"; export * from "./collect-fees-ix"; export * from "./collect-protocol-fees-ix"; export * from "./collect-reward-ix"; export * from "./composites"; export * from "./decrease-liquidity-ix"; export * from "./delete-position-bundle-ix"; export * from "./increase-liquidity-ix"; export * from "./initialize-config-ix"; export * from "./initialize-fee-tier-ix"; export * from "./initialize-pool-ix"; export * from "./initialize-position-bundle-ix"; export * from "./initialize-reward-ix"; export * from "./initialize-tick-array-ix"; export * from "./open-bundled-position-ix"; export * from "./open-position-ix"; export * from "./open-position-with-token-extensions-ix"; export * from "./set-collect-protocol-fees-authority-ix"; export * from "./set-default-fee-rate-ix"; export * from "./set-default-protocol-fee-rate-ix"; export * from "./set-fee-authority-ix"; export * from "./set-fee-rate-ix"; export * from "./set-protocol-fee-rate-ix"; export * from "./set-reward-authority-by-super-authority-ix"; export * from "./set-reward-authority-ix"; export * from "./set-reward-emissions-ix"; export * from "./set-reward-emissions-super-authority-ix"; export * from "./swap-ix"; export * from "./two-hop-swap-ix"; export * from "./update-fees-and-rewards-ix"; export * from "./v2";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/collect-fees-ix.ts
import type { Program } from "@coral-xyz/anchor"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to collect fees from a position. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from. * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param positionAuthority - authority that owns the token corresponding to this desired position. */ export type CollectFeesParams = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; positionAuthority: PublicKey; }; /** * Collect fees accrued for this position. * Call updateFeesAndRewards before this to update the position to the newest accrued values. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - CollectFeesParams object * @returns - Instruction to perform the action. */ export function collectFeesIx( program: Program<Whirlpool>, params: CollectFeesParams, ): Instruction { const { whirlpool, positionAuthority, position, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, } = params; const ix = program.instruction.collectFees({ accounts: { whirlpool, positionAuthority, position, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenProgram: TOKEN_PROGRAM_ID, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/open-position-with-token-extensions-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { WHIRLPOOL_NFT_UPDATE_AUTH } from ".."; import type { Whirlpool } from "../artifacts/whirlpool"; import { openPositionWithTokenExtensionsAccounts } from "../utils/instructions-util"; /** * Parameters to open a position (based on Token-2022) in a Whirlpool. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param ownerKey - PublicKey for the wallet that will host the minted position token. * @param positionPda - PDA for the derived position address. * @param positionMint - PublicKey for the mint token for the Position token. * @param positionTokenAccount - The associated token address for the position token in the owners wallet. * @param funder - The account that would fund the creation of this account * @param tickLowerIndex - The tick specifying the lower end of the position range. * @param tickUpperIndex - The tick specifying the upper end of the position range. * @param withTokenMetadataExtension - If true, the position token will have a TokenMetadata extension. */ export type OpenPositionWithTokenExtensionsParams = { whirlpool: PublicKey; owner: PublicKey; positionPda: PDA; positionMint: PublicKey; positionTokenAccount: PublicKey; funder: PublicKey; tickLowerIndex: number; tickUpperIndex: number; withTokenMetadataExtension: boolean; }; /** * Open a position in a Whirlpool. A unique token will be minted to represent the position * in the users wallet. Additional TokenMetadata extension is initialized to identify the token if requested. * Mint and Token account are based on Token-2022. * The position will start off with 0 liquidity. * * #### Special Errors * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - OpenPositionWithTokenExtensionsParams object and a derived PDA that hosts the position's metadata. * @returns - Instruction to perform the action. */ export function openPositionWithTokenExtensionsIx( program: Program<Whirlpool>, params: OpenPositionWithTokenExtensionsParams, ): Instruction { const { tickLowerIndex, tickUpperIndex, withTokenMetadataExtension } = params; const ix = program.instruction.openPositionWithTokenExtensions( tickLowerIndex, tickUpperIndex, withTokenMetadataExtension, { accounts: { ...openPositionWithTokenExtensionsAccounts(params), metadataUpdateAuth: WHIRLPOOL_NFT_UPDATE_AUTH, }, }, ); // TODO: Require Keypair and auto sign this ix return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/initialize-pool-ix.ts
import type { BN, Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { Keypair, PublicKey } from "@solana/web3.js"; import { SystemProgram, SYSVAR_RENT_PUBKEY } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { WhirlpoolBumpsData } from "../types/public/anchor-types"; /** * Parameters to initialize a Whirlpool account. * * @category Instruction Types * @param initSqrtPrice - The desired initial sqrt-price for this pool * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param whirlpoolPda - PDA for the whirlpool account that would be initialized * @param tokenMintA - Mint public key for token A * @param tokenMintB - Mint public key for token B * @param tokenVaultAKeypair - Keypair of the token A vault for this pool * @param tokenVaultBKeypair - Keypair of the token B vault for this pool * @param feeTierKey - PublicKey of the fee-tier account that this pool would use for the fee-rate * @param tickSpacing - The desired tick spacing for this pool. * @param funder - The account that would fund the creation of this account */ export type InitPoolParams = { initSqrtPrice: BN; whirlpoolsConfig: PublicKey; whirlpoolPda: PDA; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenVaultAKeypair: Keypair; tokenVaultBKeypair: Keypair; feeTierKey: PublicKey; tickSpacing: number; funder: PublicKey; }; /** * Initializes a tick_array account to represent a tick-range in a Whirlpool. * * Special Errors * `InvalidTokenMintOrder` - The order of mints have to be ordered by * `SqrtPriceOutOfBounds` - provided initial_sqrt_price is not between 2^-64 to 2^64 * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitPoolParams object * @returns - Instruction to perform the action. */ export function initializePoolIx( program: Program<Whirlpool>, params: InitPoolParams, ): Instruction { const { initSqrtPrice, tokenMintA, tokenMintB, whirlpoolsConfig, whirlpoolPda, feeTierKey, tokenVaultAKeypair, tokenVaultBKeypair, tickSpacing, funder, } = params; const whirlpoolBumps: WhirlpoolBumpsData = { whirlpoolBump: whirlpoolPda.bump, }; const ix = program.instruction.initializePool( whirlpoolBumps, tickSpacing, initSqrtPrice, { accounts: { whirlpoolsConfig, tokenMintA, tokenMintB, funder, whirlpool: whirlpoolPda.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, feeTier: feeTierKey, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, rent: SYSVAR_RENT_PUBKEY, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [tokenVaultAKeypair, tokenVaultBKeypair], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/set-reward-emissions-ix.ts
import type { BN, Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to set rewards emissions for a reward in a Whirlpool * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool which the reward resides in. * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS). * @param rewardVaultKey - PublicKey of the vault for this reward index. * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool * @param emissionsPerSecondX64 - The new emissions per second to set for this reward. */ export type SetRewardEmissionsParams = { whirlpool: PublicKey; rewardIndex: number; rewardVaultKey: PublicKey; rewardAuthority: PublicKey; emissionsPerSecondX64: BN; }; /** * Set the reward emissions for a reward in a Whirlpool. * * #### Special Errors * - `RewardVaultAmountInsufficient` - The amount of rewards in the reward vault cannot emit more than a day of desired emissions. * - `InvalidTimestamp` - Provided timestamp is not in order with the previous timestamp. * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool, * or exceeds NUM_REWARDS. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetRewardEmissionsParams object * @returns - Instruction to perform the action. */ export function setRewardEmissionsIx( program: Program<Whirlpool>, params: SetRewardEmissionsParams, ): Instruction { const { rewardAuthority, whirlpool, rewardIndex, rewardVaultKey: rewardVault, emissionsPerSecondX64, } = params; const ix = program.instruction.setRewardEmissions( rewardIndex, emissionsPerSecondX64, { accounts: { rewardAuthority, whirlpool, rewardVault, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/increase-liquidity-ix.ts
import type { Program } from "@coral-xyz/anchor"; import { TOKEN_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type BN from "bn.js"; import type { Whirlpool } from "../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to increase liquidity for a position. * * @category Instruction Types * @param liquidityAmount - The total amount of Liquidity the user is willing to deposit. * @param tokenMaxA - The maximum amount of token A to add to the position. * @param tokenMaxB - The maximum amount of token B to add to the position. * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from. * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index. * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index. * @param positionAuthority - authority that owns the token corresponding to this desired position. */ export type IncreaseLiquidityParams = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tickArrayLower: PublicKey; tickArrayUpper: PublicKey; positionAuthority: PublicKey; } & IncreaseLiquidityInput; /** * Input parameters to deposit liquidity into a position. * * This type is usually generated by a quote class to estimate the amount of tokens required to * deposit a certain amount of liquidity into a position. * * @category Instruction Types * @param tokenMaxA - the maximum amount of tokenA allowed to withdraw from the source wallet. * @param tokenMaxB - the maximum amount of tokenB allowed to withdraw from the source wallet. * @param liquidityAmount - the desired amount of liquidity to deposit into the position/ */ export type IncreaseLiquidityInput = { tokenMaxA: BN; tokenMaxB: BN; liquidityAmount: BN; }; /** * Add liquidity to a position in the Whirlpool. * * #### Special Errors * `LiquidityZero` - Provided liquidity amount is zero. * `LiquidityTooHigh` - Provided liquidity exceeds u128::max. * `TokenMaxExceeded` - The required token to perform this operation exceeds the user defined amount. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - IncreaseLiquidityParams object * @returns - Instruction to perform the action. */ export function increaseLiquidityIx( program: Program<Whirlpool>, params: IncreaseLiquidityParams, ): Instruction { const { liquidityAmount, tokenMaxA, tokenMaxB, whirlpool, positionAuthority, position, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tickArrayLower, tickArrayUpper, } = params; const ix = program.instruction.increaseLiquidity( liquidityAmount, tokenMaxA, tokenMaxB, { accounts: { whirlpool, tokenProgram: TOKEN_PROGRAM_ID, positionAuthority, position, positionTokenAccount, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tickArrayLower, tickArrayUpper, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/close-position-with-token-extensions-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import { TOKEN_2022_PROGRAM_ID } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../artifacts/whirlpool"; /** * Parameters to close a position (based on Token-2022) in a Whirlpool. * * @category Instruction Types * @param receiver - PublicKey for the wallet that will receive the rented lamports. * @param position - PublicKey for the position. * @param positionMint - PublicKey for the mint token for the Position token. * @param positionTokenAccount - The associated token address for the position token in the owners wallet. * @param positionAuthority - Authority that owns the position token. */ export type ClosePositionWithTokenExtensionsParams = { receiver: PublicKey; position: PublicKey; positionMint: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; }; /** * Close a position in a Whirlpool. Burns the position token in the owner's wallet. * Mint and TokenAccount are based on Token-2022. And Mint accout will be also closed. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - ClosePositionWithTokenExtensionsParams object * @returns - Instruction to perform the action. */ export function closePositionWithTokenExtensionsIx( program: Program<Whirlpool>, params: ClosePositionWithTokenExtensionsParams, ): Instruction { const ix = program.instruction.closePositionWithTokenExtensions({ accounts: { ...params, token2022Program: TOKEN_2022_PROGRAM_ID, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/swap-with-route.ts
import type { Percentage, ResolvedTokenAddressInstruction, } from "@orca-so/common-sdk"; import { AddressUtil, EMPTY_INSTRUCTION, TokenUtil, TransactionBuilder, ZERO, } from "@orca-so/common-sdk"; import type { Account } from "@solana/spl-token"; import { NATIVE_MINT, TOKEN_PROGRAM_ID, createAssociatedTokenAccountInstruction, createCloseAccountInstruction, getAssociatedTokenAddressSync, } from "@solana/spl-token"; import type { TransactionInstruction } from "@solana/web3.js"; import { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; import type { AtaAccountInfo, SubTradeRoute, TradeRoute, WhirlpoolContext, } from "../.."; import { PDAUtil, SwapUtils, twoHopSwapQuoteFromSwapQuotes } from "../.."; import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher"; import { PREFER_CACHE } from "../../network/public/fetcher"; import { adjustForSlippage } from "../../utils/position-util"; import { contextOptionsToBuilderOptions } from "../../utils/txn-utils"; import { swapIx } from "../swap-ix"; import { twoHopSwapIx } from "../two-hop-swap-ix"; export type SwapFromRouteParams = { route: TradeRoute; slippage: Percentage; wallet: PublicKey; resolvedAtaAccounts: AtaAccountInfo[] | null; }; export async function getSwapFromRoute( ctx: WhirlpoolContext, params: SwapFromRouteParams, opts: WhirlpoolAccountFetchOptions = PREFER_CACHE, txBuilder: TransactionBuilder = new TransactionBuilder( ctx.connection, ctx.wallet, contextOptionsToBuilderOptions(ctx.opts), ), ) { const { route, wallet, resolvedAtaAccounts, slippage } = params; const requiredAtas = new Set<string>(); const requiredIntermediateAtas = new Set<string>(); const requiredTickArrays = []; let hasNativeMint = false; let nativeMintAmount = new BN(0); function addOrNative(mint: string, amount: BN) { if (mint === NATIVE_MINT.toBase58()) { hasNativeMint = true; nativeMintAmount = nativeMintAmount.add(amount); } else { requiredAtas.add(mint); } } for (let i = 0; i < route.subRoutes.length; i++) { const routeFragment = route.subRoutes[i]; const slippageAdjustedRoute = adjustQuoteForSlippage( routeFragment, slippage, ); if (slippageAdjustedRoute.hopQuotes.length == 1) { const { quote, mintA, mintB } = slippageAdjustedRoute.hopQuotes[0]; requiredTickArrays.push( ...[quote.tickArray0, quote.tickArray1, quote.tickArray2], ); const inputAmount = quote.amountSpecifiedIsInput ? quote.amount : quote.otherAmountThreshold; addOrNative(mintA.toString(), quote.aToB ? inputAmount : ZERO); addOrNative(mintB.toString(), !quote.aToB ? inputAmount : ZERO); } else if (slippageAdjustedRoute.hopQuotes.length == 2) { const { quote: quoteOne, mintA: mintOneA, mintB: mintOneB, } = slippageAdjustedRoute.hopQuotes[0]; const { quote: quoteTwo, mintA: mintTwoA, mintB: mintTwoB, } = slippageAdjustedRoute.hopQuotes[1]; const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quoteOne, quoteTwo); requiredTickArrays.push( ...[ twoHopQuote.tickArrayOne0, twoHopQuote.tickArrayOne1, twoHopQuote.tickArrayOne2, twoHopQuote.tickArrayTwo0, twoHopQuote.tickArrayTwo1, twoHopQuote.tickArrayTwo2, ], ); const inputAmount = quoteOne.amountSpecifiedIsInput ? quoteOne.estimatedAmountIn : quoteOne.otherAmountThreshold; addOrNative(mintOneA.toString(), quoteOne.aToB ? inputAmount : ZERO); addOrNative(mintOneB.toString(), !quoteOne.aToB ? inputAmount : ZERO); addOrNative(mintTwoA.toString(), ZERO); addOrNative(mintTwoB.toString(), ZERO); requiredIntermediateAtas.add( quoteOne.aToB ? mintOneB.toString() : mintOneA.toString(), ); } } // No need to check if TickArrays are initialized after SparseSwap implementation // Handle non-native mints only first requiredAtas.delete(NATIVE_MINT.toBase58()); const ataInstructionMap = await cachedResolveOrCreateNonNativeATAs( wallet, requiredAtas, requiredIntermediateAtas, (keys) => { // TODO: if atas are not up to date, there might be failures, not sure if there's // any good way, other than to re-fetch each time? if (resolvedAtaAccounts != null) { return Promise.resolve( keys.map((key) => resolvedAtaAccounts.find( (ata) => ata.address?.toBase58() === key.toBase58(), ), ) as Account[], ); } else { return ctx.fetcher .getTokenInfos(keys, opts) .then((result) => Array.from(result.values())); } }, undefined, // use default ctx.accountResolverOpts.allowPDAOwnerAddress, ); const ataIxes = Object.values(ataInstructionMap); if (hasNativeMint) { const solIx = TokenUtil.createWrappedNativeAccountInstruction( wallet, nativeMintAmount, await ctx.fetcher.getAccountRentExempt(), undefined, // use default undefined, // use default ctx.accountResolverOpts.createWrappedSolAccountMethod, ); txBuilder.addInstruction(solIx); ataInstructionMap[NATIVE_MINT.toBase58()] = solIx; } txBuilder.addInstructions(ataIxes); // Slippage adjustment const slippageAdjustedQuotes = route.subRoutes.map((quote) => adjustQuoteForSlippage(quote, slippage), ); for (let i = 0; i < slippageAdjustedQuotes.length; i++) { const routeFragment = slippageAdjustedQuotes[i]; if (routeFragment.hopQuotes.length == 1) { const { quote, whirlpool, mintA, mintB, vaultA, vaultB } = routeFragment.hopQuotes[0]; const [wp, tokenVaultA, tokenVaultB] = AddressUtil.toPubKeys([ whirlpool, vaultA, vaultB, ]); const accA = ataInstructionMap[mintA.toString()].address; const accB = ataInstructionMap[mintB.toString()].address; const oraclePda = PDAUtil.getOracle(ctx.program.programId, wp); txBuilder.addInstruction( swapIx(ctx.program, { whirlpool: wp, tokenOwnerAccountA: accA, tokenOwnerAccountB: accB, tokenVaultA, tokenVaultB, oracle: oraclePda.publicKey, tokenAuthority: wallet, ...quote, }), ); } else if (routeFragment.hopQuotes.length == 2) { const { quote: quoteOne, whirlpool: whirlpoolOne, mintA: mintOneA, mintB: mintOneB, vaultA: vaultOneA, vaultB: vaultOneB, } = routeFragment.hopQuotes[0]; const { quote: quoteTwo, whirlpool: whirlpoolTwo, mintA: mintTwoA, mintB: mintTwoB, vaultA: vaultTwoA, vaultB: vaultTwoB, } = routeFragment.hopQuotes[1]; const [ wpOne, wpTwo, tokenVaultOneA, tokenVaultOneB, tokenVaultTwoA, tokenVaultTwoB, ] = AddressUtil.toPubKeys([ whirlpoolOne, whirlpoolTwo, vaultOneA, vaultOneB, vaultTwoA, vaultTwoB, ]); const twoHopQuote = twoHopSwapQuoteFromSwapQuotes(quoteOne, quoteTwo); const oracleOne = PDAUtil.getOracle( ctx.program.programId, wpOne, ).publicKey; const oracleTwo = PDAUtil.getOracle( ctx.program.programId, wpTwo, ).publicKey; const tokenOwnerAccountOneA = ataInstructionMap[mintOneA.toString()].address; const tokenOwnerAccountOneB = ataInstructionMap[mintOneB.toString()].address; const tokenOwnerAccountTwoA = ataInstructionMap[mintTwoA.toString()].address; const tokenOwnerAccountTwoB = ataInstructionMap[mintTwoB.toString()].address; txBuilder.addInstruction( twoHopSwapIx(ctx.program, { ...twoHopQuote, whirlpoolOne: wpOne, whirlpoolTwo: wpTwo, tokenOwnerAccountOneA, tokenOwnerAccountOneB, tokenOwnerAccountTwoA, tokenOwnerAccountTwoB, tokenVaultOneA, tokenVaultOneB, tokenVaultTwoA, tokenVaultTwoB, oracleOne, oracleTwo, tokenAuthority: wallet, }), ); } } return txBuilder; } function adjustQuoteForSlippage( quote: SubTradeRoute, slippage: Percentage, ): SubTradeRoute { const { hopQuotes } = quote; if (hopQuotes.length === 1) { return { ...quote, hopQuotes: [ { ...hopQuotes[0], quote: { ...hopQuotes[0].quote, ...SwapUtils.calculateSwapAmountsFromQuote( hopQuotes[0].quote.amount, hopQuotes[0].quote.estimatedAmountIn, hopQuotes[0].quote.estimatedAmountOut, slippage, hopQuotes[0].quote.amountSpecifiedIsInput, ), }, }, ], }; } else if (quote.hopQuotes.length === 2) { const swapQuoteOne = quote.hopQuotes[0]; const swapQuoteTwo = quote.hopQuotes[1]; const amountSpecifiedIsInput = swapQuoteOne.quote.amountSpecifiedIsInput; let updatedQuote = { ...quote, }; if (amountSpecifiedIsInput) { updatedQuote.hopQuotes = [ updatedQuote.hopQuotes[0], { ...swapQuoteTwo, quote: { ...swapQuoteTwo.quote, otherAmountThreshold: adjustForSlippage( swapQuoteTwo.quote.estimatedAmountOut, slippage, false, ), }, }, ]; } else { updatedQuote.hopQuotes = [ { ...swapQuoteOne, quote: { ...swapQuoteOne.quote, otherAmountThreshold: adjustForSlippage( swapQuoteOne.quote.estimatedAmountIn, slippage, true, ), }, }, updatedQuote.hopQuotes[1], ]; } return updatedQuote; } return quote; } /** * Internal duplicate of resolveOrCreateAta * This could be ported over to common-sdk? * * IMPORTANT: wrappedSolAmountIn should only be used for input/source token that * could be SOL. This is because when SOL is the output, it is the end * destination, and thus does not need to be wrapped with an amount. * * @param ownerAddress The user's public key * @param tokenMint Token mint address * @param intermediateTokenMints Any mints from the tokenMint set that are intermediates in a two-hop swap * @param getTokenAccounts Function to get token accounts * @param payer Payer that would pay the rent for the creation of the ATAs * @param allowPDAOwnerAddress Optional. Allow PDA to be used as the ATA owner address * @returns */ async function cachedResolveOrCreateNonNativeATAs( ownerAddress: PublicKey, tokenMints: Set<string>, intermediateTokenMints: Set<string>, getTokenAccounts: ( keys: PublicKey[], ) => Promise<Array<AtaAccountInfo | null>>, payer = ownerAddress, allowPDAOwnerAddress: boolean = false, ): Promise<{ [tokenMint: string]: ResolvedTokenAddressInstruction }> { const instructionMap: { [tokenMint: string]: ResolvedTokenAddressInstruction; } = {}; const tokenMintArray = Array.from(tokenMints).map((tm) => new PublicKey(tm)); const tokenAtas = tokenMintArray.map((tm) => getAssociatedTokenAddressSync(tm, ownerAddress, allowPDAOwnerAddress), ); const tokenAccounts = await getTokenAccounts(tokenAtas); tokenAccounts.forEach((tokenAccount, index) => { const ataAddress = tokenAtas[index]!; let resolvedInstruction; if (tokenAccount) { // ATA whose owner has been changed is abnormal entity. // To prevent to send swap/withdraw/collect output to the ATA, an error should be thrown. if (!tokenAccount.owner.equals(ownerAddress)) { throw new Error( `ATA with change of ownership detected: ${ataAddress.toBase58()}`, ); } resolvedInstruction = { address: ataAddress, ...EMPTY_INSTRUCTION }; } else { const tokenMint = tokenMintArray[index]; const createAtaInstructions = [ createAssociatedTokenAccountInstruction( payer, ataAddress, ownerAddress, tokenMint, ), ]; let cleanupInstructions: TransactionInstruction[] = []; if (intermediateTokenMints.has(tokenMint.toBase58())) { cleanupInstructions = [ createCloseAccountInstruction(ataAddress, ownerAddress, ownerAddress), ]; } resolvedInstruction = { address: ataAddress, instructions: createAtaInstructions, cleanupInstructions: cleanupInstructions, signers: [], }; } // WhirlpoolRouter does not handle TokenExtension, so token program is always standard TokenProgram. instructionMap[tokenMintArray[index].toBase58()] = { tokenProgram: TOKEN_PROGRAM_ID, ...resolvedInstruction, }; }); return instructionMap; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/collect-all-txn.ts
import type { Address } from "@coral-xyz/anchor"; import type { Instruction, ResolvedTokenAddressInstruction, } from "@orca-so/common-sdk"; import { TokenUtil, TransactionBuilder, ZERO, resolveOrCreateATAs, } from "@orca-so/common-sdk"; import { NATIVE_MINT, getAssociatedTokenAddressSync } from "@solana/spl-token"; import { PublicKey } from "@solana/web3.js"; import type { PositionData, WhirlpoolContext } from "../.."; import { WhirlpoolIx } from "../../ix"; import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher"; import { PREFER_CACHE } from "../../network/public/fetcher"; import type { WhirlpoolData } from "../../types/public"; import { PDAUtil, PoolUtil, TickUtil } from "../../utils/public"; import { checkMergedTransactionSizeIsValid, convertListToMap, } from "../../utils/txn-utils"; import { getTokenMintsFromWhirlpools } from "../../utils/whirlpool-ata-utils"; import { updateFeesAndRewardsIx } from "../update-fees-and-rewards-ix"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; /** * Parameters to collect all fees and rewards from a list of positions. * * @category Instruction Types * @param positionAddrs - An array of Whirlpool position addresses. * @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key. * @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key. * @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key. * @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key. */ export type CollectAllPositionAddressParams = { positions: Address[]; } & CollectAllParams; /** * Parameters to collect all fees and rewards from a list of positions. * * @category Instruction Types * @param positions - An array of Whirlpool positions. * @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key. * @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key. * @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key. * @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key. */ export type CollectAllPositionParams = { positions: Record<string, PositionData>; } & CollectAllParams; /** * Common parameters between {@link CollectAllPositionParams} & {@link CollectAllPositionAddressParams} * * @category Instruction Types * @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key. * @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key. * @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key. * @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key. */ export type CollectAllParams = { receiver?: PublicKey; positionOwner?: PublicKey; positionAuthority?: PublicKey; payer?: PublicKey; }; /** * Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions. * * @category Instructions * @experimental * @param ctx - WhirlpoolContext object for the current environment. * @param params - CollectAllPositionAddressParams object * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions. */ export async function collectAllForPositionAddressesTxns( ctx: WhirlpoolContext, params: CollectAllPositionAddressParams, opts: WhirlpoolAccountFetchOptions = PREFER_CACHE, ): Promise<TransactionBuilder[]> { const { positions, ...rest } = params; const fetchedPositions = await ctx.fetcher.getPositions(positions, opts); const positionMap: Record<string, PositionData> = {}; fetchedPositions.forEach((pos, addr) => { if (pos) { positionMap[addr] = pos; } }); return collectAllForPositionsTxns(ctx, { positions: positionMap, ...rest }); } /** * Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions. * * @experimental * @param ctx - WhirlpoolContext object for the current environment. * @param params - CollectAllPositionParams object * @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions. */ export async function collectAllForPositionsTxns( ctx: WhirlpoolContext, params: CollectAllPositionParams, ): Promise<TransactionBuilder[]> { const { positions, receiver, positionAuthority, positionOwner, payer } = params; const receiverKey = receiver ?? ctx.wallet.publicKey; const positionAuthorityKey = positionAuthority ?? ctx.wallet.publicKey; const positionOwnerKey = positionOwner ?? ctx.wallet.publicKey; const payerKey = payer ?? ctx.wallet.publicKey; const positionList = Object.entries(positions); if (positionList.length === 0) { return []; } const whirlpoolAddrs = positionList.map(([, pos]) => pos.whirlpool.toBase58(), ); const whirlpools = await ctx.fetcher.getPools(whirlpoolAddrs, PREFER_CACHE); const allMints = getTokenMintsFromWhirlpools(Array.from(whirlpools.values())); const accountExemption = await ctx.fetcher.getAccountRentExempt(); const positionMintAddrs = positionList.map(([, pos]) => pos.positionMint); const positionMintInfos = await ctx.fetcher.getMintInfos(positionMintAddrs); // make cache await ctx.fetcher.getMintInfos(allMints.mintMap); // resolvedAtas[mint] => Instruction & { address } // if already ATA exists, Instruction will be EMPTY_INSTRUCTION const resolvedAtas = convertListToMap( await resolveOrCreateATAs( ctx.connection, receiverKey, allMints.mintMap.map((tokenMint) => ({ tokenMint })), async () => accountExemption, payerKey, true, // CreateIdempotent ctx.accountResolverOpts.allowPDAOwnerAddress, ctx.accountResolverOpts.createWrappedSolAccountMethod, ), allMints.mintMap.map((mint) => mint.toBase58()), ); const latestBlockhash = await ctx.connection.getLatestBlockhash(); const txBuilders: TransactionBuilder[] = []; // build tasks // For TokenProgram-TokenProgram pair pool, collectFees and 3 collectReward instructions can be packed into one transaction. // But if pool has TokenExtension, especially TransferHook, we can no longer pack all instructions into one transaction. // So transactions need to be broken up at a finer granularity. const collectionTasks: CollectionTask[] = []; positionList.forEach(([positionAddr, position]) => { const whirlpool = whirlpools.get(position.whirlpool.toBase58()); if (!whirlpool) { throw new Error( `Unable to process positionMint ${position.positionMint.toBase58()} - unable to derive whirlpool ${position.whirlpool.toBase58()}`, ); } const positionMintInfo = positionMintInfos.get( position.positionMint.toBase58(), ); if (!positionMintInfo) { throw new Error( `Unable to process positionMint ${position.positionMint.toBase58()} - missing mint info`, ); } // add fee collection task collectionTasks.push({ collectionType: "fee", positionAddr, position, whirlpool, positionMintTokenProgramId: positionMintInfo.tokenProgram, }); // add reward collection task whirlpool.rewardInfos.forEach((rewardInfo, index) => { if (PoolUtil.isRewardInitialized(rewardInfo)) { collectionTasks.push({ collectionType: "reward", rewardIndex: index, positionAddr, position, whirlpool, positionMintTokenProgramId: positionMintInfo.tokenProgram, }); } }); }); let cursor = 0; let pendingTxBuilder = null; let touchedMints = null; let lastUpdatedPosition = null; let reattempt = false; while (cursor < collectionTasks.length) { if (!pendingTxBuilder || !touchedMints) { pendingTxBuilder = new TransactionBuilder( ctx.connection, ctx.wallet, ctx.txBuilderOpts, ); touchedMints = new Set<string>(); resolvedAtas[NATIVE_MINT.toBase58()] = TokenUtil.createWrappedNativeAccountInstruction( receiverKey, ZERO, accountExemption, undefined, // use default undefined, // use default ctx.accountResolverOpts.createWrappedSolAccountMethod, ); } // Build collect instructions const task = collectionTasks[cursor]; const alreadyUpdated = lastUpdatedPosition === task.positionAddr; const collectIxForPosition = await constructCollectIxForPosition( ctx, task, alreadyUpdated, positionOwnerKey, positionAuthorityKey, resolvedAtas, touchedMints, ); const positionTxBuilder = new TransactionBuilder( ctx.connection, ctx.wallet, ctx.txBuilderOpts, ); positionTxBuilder.addInstructions(collectIxForPosition); // Attempt to push the new instructions into the pending builder // Iterate to the next task if possible // Create a builder and reattempt if the current one is full. const mergeable = await checkMergedTransactionSizeIsValid( ctx, [pendingTxBuilder, positionTxBuilder], latestBlockhash, ); if (mergeable) { pendingTxBuilder.addInstruction(positionTxBuilder.compressIx(false)); cursor += 1; lastUpdatedPosition = task.positionAddr; reattempt = false; } else { if (reattempt) { throw new Error( `Unable to fit collection ix for ${task.position.positionMint.toBase58()} in a Transaction.`, ); } txBuilders.push(pendingTxBuilder); pendingTxBuilder = null; touchedMints = null; lastUpdatedPosition = null; reattempt = true; } } if (pendingTxBuilder) { txBuilders.push(pendingTxBuilder); } return txBuilders; } type CollectionTask = FeeCollectionTask | RewardCollectionTask; type FeeCollectionTask = { collectionType: "fee"; } & CollectionTaskBase; type RewardCollectionTask = { collectionType: "reward"; rewardIndex: number; } & CollectionTaskBase; type CollectionTaskBase = { positionAddr: string; position: PositionData; positionMintTokenProgramId: PublicKey; whirlpool: WhirlpoolData; }; // TODO: Once individual collect ix for positions is implemented, maybe migrate over if it can take custom ATA? const constructCollectIxForPosition = async ( ctx: WhirlpoolContext, task: CollectionTask, alreadyUpdated: boolean, positionOwner: PublicKey, positionAuthority: PublicKey, resolvedAtas: Record<string, ResolvedTokenAddressInstruction>, touchedMints: Set<string>, ) => { const ixForPosition: Instruction[] = []; const { whirlpool: whirlpoolKey, liquidity, tickLowerIndex, tickUpperIndex, positionMint, } = task.position; const positionMintTokenProgramId = task.positionMintTokenProgramId; const whirlpool = task.whirlpool; const { tickSpacing } = whirlpool; const mintA = whirlpool.tokenMintA.toBase58(); const mintB = whirlpool.tokenMintB.toBase58(); const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, whirlpool, PREFER_CACHE, ); const positionTokenAccount = getAssociatedTokenAddressSync( positionMint, positionOwner, ctx.accountResolverOpts.allowPDAOwnerAddress, positionMintTokenProgramId, ); // Update fee and reward values if necessary if (!liquidity.eq(ZERO) && !alreadyUpdated) { ixForPosition.push( updateFeesAndRewardsIx(ctx.program, { position: new PublicKey(task.positionAddr), whirlpool: whirlpoolKey, tickArrayLower: PDAUtil.getTickArray( ctx.program.programId, whirlpoolKey, TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing), ).publicKey, tickArrayUpper: PDAUtil.getTickArray( ctx.program.programId, whirlpoolKey, TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing), ).publicKey, }), ); } if (task.collectionType === "fee") { // Collect Fee if (!touchedMints.has(mintA)) { ixForPosition.push(resolvedAtas[mintA]); touchedMints.add(mintA); } if (!touchedMints.has(mintB)) { ixForPosition.push(resolvedAtas[mintB]); touchedMints.add(mintB); } const collectFeesBaseParams = { whirlpool: whirlpoolKey, position: new PublicKey(task.positionAddr), positionAuthority, positionTokenAccount, tokenOwnerAccountA: resolvedAtas[mintA].address, tokenOwnerAccountB: resolvedAtas[mintB].address, tokenVaultA: whirlpool.tokenVaultA, tokenVaultB: whirlpool.tokenVaultB, }; ixForPosition.push( !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx) ? WhirlpoolIx.collectFeesIx(ctx.program, collectFeesBaseParams) : WhirlpoolIx.collectFeesV2Ix(ctx.program, { ...collectFeesBaseParams, tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address, tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address, tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram, tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram, ...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool( ctx.connection, tokenExtensionCtx, collectFeesBaseParams.tokenVaultA, collectFeesBaseParams.tokenOwnerAccountA, collectFeesBaseParams.whirlpool, // vault to owner, so pool is authority collectFeesBaseParams.tokenVaultB, collectFeesBaseParams.tokenOwnerAccountB, collectFeesBaseParams.whirlpool, // vault to owner, so pool is authority )), }), ); } else { // Collect Rewards // TODO: handle empty vault values? const index = task.rewardIndex; const rewardInfo = whirlpool.rewardInfos[index]; const mintReward = rewardInfo.mint.toBase58(); if (!touchedMints.has(mintReward)) { ixForPosition.push(resolvedAtas[mintReward]); touchedMints.add(mintReward); } const collectRewardBaseParams = { whirlpool: whirlpoolKey, position: new PublicKey(task.positionAddr), positionAuthority, positionTokenAccount, rewardIndex: index, rewardOwnerAccount: resolvedAtas[mintReward].address, rewardVault: rewardInfo.vault, }; ixForPosition.push( !TokenExtensionUtil.isV2IxRequiredReward(tokenExtensionCtx, index) ? WhirlpoolIx.collectRewardIx(ctx.program, collectRewardBaseParams) : WhirlpoolIx.collectRewardV2Ix(ctx.program, { ...collectRewardBaseParams, rewardMint: tokenExtensionCtx.rewardTokenMintsWithProgram[index]!.address, rewardTokenProgram: tokenExtensionCtx.rewardTokenMintsWithProgram[index]! .tokenProgram, rewardTransferHookAccounts: await TokenExtensionUtil.getExtraAccountMetasForTransferHook( ctx.connection, tokenExtensionCtx.rewardTokenMintsWithProgram[index]!, collectRewardBaseParams.rewardVault, collectRewardBaseParams.rewardOwnerAccount, collectRewardBaseParams.whirlpool, // vault to owner, so pool is authority ), }), ); } return ixForPosition; };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/index.ts
export * from "./collect-all-txn"; export * from "./collect-protocol-fees"; export * from "./swap-async";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/collect-protocol-fees.ts
import type { Address } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import { AddressUtil, TokenUtil, TransactionBuilder, } from "@orca-so/common-sdk"; import { NATIVE_MINT } from "@solana/spl-token"; import { PACKET_DATA_SIZE } from "@solana/web3.js"; import type { WhirlpoolContext } from "../.."; import { PREFER_CACHE } from "../../network/public/fetcher"; import { TokenMintTypes, addNativeMintHandlingIx, getTokenMintsFromWhirlpools, resolveAtaForMints, } from "../../utils/whirlpool-ata-utils"; import { collectProtocolFeesIx } from "../collect-protocol-fees-ix"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; import { collectProtocolFeesV2Ix } from "../v2"; export async function collectProtocolFees( ctx: WhirlpoolContext, poolAddresses: Address[], ): Promise<TransactionBuilder> { const receiverKey = ctx.wallet.publicKey; const payerKey = ctx.wallet.publicKey; const whirlpoolDatas = Array.from( (await ctx.fetcher.getPools(poolAddresses, PREFER_CACHE)).values(), ); // make cache const mints = getTokenMintsFromWhirlpools( whirlpoolDatas, TokenMintTypes.POOL_ONLY, ).mintMap; await ctx.fetcher.getMintInfos(mints); const accountExemption = await ctx.fetcher.getAccountRentExempt(); const { ataTokenAddresses, resolveAtaIxs } = await resolveAtaForMints(ctx, { mints: mints, accountExemption, receiver: receiverKey, payer: payerKey, }); const latestBlockhash = await ctx.connection.getLatestBlockhash(); let txBuilder = new TransactionBuilder( ctx.connection, ctx.wallet, ctx.txBuilderOpts, ).addInstructions(resolveAtaIxs); const instructions: Instruction[] = []; for (const poolAddress of poolAddresses) { const pool = await ctx.fetcher.getPool(poolAddress); if (!pool) { throw new Error(`Pool not found: ${poolAddress}`); } const poolConfig = await ctx.fetcher.getConfig(pool.whirlpoolsConfig); if (!poolConfig) { throw new Error(`Config not found: ${pool.whirlpoolsConfig}`); } if ( poolConfig.collectProtocolFeesAuthority.toBase58() !== ctx.wallet.publicKey.toBase58() ) { throw new Error(`Wallet is not the collectProtocolFeesAuthority`); } const poolHandlesNativeMint = TokenUtil.isNativeMint(pool.tokenMintA) || TokenUtil.isNativeMint(pool.tokenMintB); const txBuilderHasNativeMint = !!ataTokenAddresses[NATIVE_MINT.toBase58()]; if (poolHandlesNativeMint && !txBuilderHasNativeMint) { addNativeMintHandlingIx( txBuilder, ataTokenAddresses, receiverKey, accountExemption, ctx.accountResolverOpts.createWrappedSolAccountMethod, ); } const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, pool, PREFER_CACHE, ); const baseParams = { whirlpoolsConfig: pool.whirlpoolsConfig, whirlpool: AddressUtil.toPubKey(poolAddress), tokenVaultA: pool.tokenVaultA, tokenVaultB: pool.tokenVaultB, tokenOwnerAccountA: ataTokenAddresses[pool.tokenMintA.toBase58()], tokenOwnerAccountB: ataTokenAddresses[pool.tokenMintB.toBase58()], collectProtocolFeesAuthority: poolConfig.collectProtocolFeesAuthority, }; // add collect ixn instructions.push( !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx) ? collectProtocolFeesIx(ctx.program, baseParams) : collectProtocolFeesV2Ix(ctx.program, { ...baseParams, tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address, tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address, tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram, tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram, ...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool( ctx.connection, tokenExtensionCtx, baseParams.tokenVaultA, baseParams.tokenOwnerAccountA, baseParams.whirlpool, // vault to protocol, so pool is authority baseParams.tokenVaultB, baseParams.tokenOwnerAccountB, baseParams.whirlpool, // vault to protocol, so pool is authority )), }), ); } txBuilder.addInstructions(instructions); const txSize = await txBuilder.txnSize({ latestBlockhash }); if (txSize > PACKET_DATA_SIZE) { throw new Error(`Transaction size is too large: ${txSize}`); } return txBuilder; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/composites/swap-async.ts
import { resolveOrCreateATAs, TransactionBuilder, U64_MAX, ZERO, } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool, WhirlpoolContext } from "../.."; import { SwapUtils } from "../.."; import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher"; import type { SwapInput } from "../swap-ix"; import { swapIx } from "../swap-ix"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; import { swapV2Ix } from "../v2"; import { NATIVE_MINT } from "@solana/spl-token"; export type SwapAsyncParams = { swapInput: SwapInput; whirlpool: Whirlpool; wallet: PublicKey; }; /** * Swap instruction builder method with resolveATA & additional checks. * @param ctx - WhirlpoolContext object for the current environment. * @param params - {@link SwapAsyncParams} * @param opts - {@link WhirlpoolAccountFetchOptions} to use for account fetching. * @returns */ export async function swapAsync( ctx: WhirlpoolContext, params: SwapAsyncParams, _opts: WhirlpoolAccountFetchOptions, ): Promise<TransactionBuilder> { const { wallet, whirlpool, swapInput } = params; const { aToB, amount, otherAmountThreshold, amountSpecifiedIsInput } = swapInput; const txBuilder = new TransactionBuilder( ctx.connection, ctx.wallet, ctx.txBuilderOpts, ); // No need to check if TickArrays are initialized after SparseSwap implementation const data = whirlpool.getData(); // In ExactOut mode, max input amount is otherAmountThreshold const inputTokenMint = aToB ? data.tokenMintA : data.tokenMintB; const maxInputAmount = amountSpecifiedIsInput ? amount : otherAmountThreshold; if (inputTokenMint.equals(NATIVE_MINT) && maxInputAmount.eq(U64_MAX)) { // Strictly speaking, the upper limit would be the wallet balance minus rent and fees, // but that calculation is impractical. // Since this function is called to perform a transaction, we can expect the otherAmountThreshold // to be smaller than the wallet balance, and a run-time error would make the problem clear at worst. // Here, the obviously impossible case (a value using defaultOtherAmountThreshold) will be an error. throw new Error("Wrapping U64_MAX amount of SOL is not possible"); } const [resolvedAtaA, resolvedAtaB] = await resolveOrCreateATAs( ctx.connection, wallet, [ { tokenMint: data.tokenMintA, wrappedSolAmountIn: aToB ? maxInputAmount : ZERO, }, { tokenMint: data.tokenMintB, wrappedSolAmountIn: !aToB ? maxInputAmount : ZERO, }, ], () => ctx.fetcher.getAccountRentExempt(), undefined, // use default true, // use idempotent to allow multiple simultaneous calls ctx.accountResolverOpts.allowPDAOwnerAddress, ctx.accountResolverOpts.createWrappedSolAccountMethod, ); const { address: ataAKey, ...tokenOwnerAccountAIx } = resolvedAtaA; const { address: ataBKey, ...tokenOwnerAccountBIx } = resolvedAtaB; txBuilder.addInstructions([tokenOwnerAccountAIx, tokenOwnerAccountBIx]); const inputTokenAccount = aToB ? ataAKey : ataBKey; const outputTokenAccount = aToB ? ataBKey : ataAKey; const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext( ctx.fetcher, data, ); const baseParams = SwapUtils.getSwapParamsFromQuote( swapInput, ctx, whirlpool, inputTokenAccount, outputTokenAccount, wallet, ); return txBuilder.addInstruction( !TokenExtensionUtil.isV2IxRequiredPool(tokenExtensionCtx) && !params.swapInput.supplementalTickArrays ? swapIx(ctx.program, baseParams) : swapV2Ix(ctx.program, { ...baseParams, tokenMintA: tokenExtensionCtx.tokenMintWithProgramA.address, tokenMintB: tokenExtensionCtx.tokenMintWithProgramB.address, tokenProgramA: tokenExtensionCtx.tokenMintWithProgramA.tokenProgram, tokenProgramB: tokenExtensionCtx.tokenMintWithProgramB.tokenProgram, ...(await TokenExtensionUtil.getExtraAccountMetasForTransferHookForPool( ctx.connection, tokenExtensionCtx, baseParams.aToB ? baseParams.tokenOwnerAccountA : baseParams.tokenVaultA, baseParams.aToB ? baseParams.tokenVaultA : baseParams.tokenOwnerAccountA, baseParams.aToB ? baseParams.tokenAuthority : baseParams.whirlpool, baseParams.aToB ? baseParams.tokenVaultB : baseParams.tokenOwnerAccountB, baseParams.aToB ? baseParams.tokenOwnerAccountB : baseParams.tokenVaultB, baseParams.aToB ? baseParams.whirlpool : baseParams.tokenAuthority, )), supplementalTickArrays: params.swapInput.supplementalTickArrays, }), ); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/set-config-extension-authority-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to set the token badge authority in a WhirlpoolsConfigExtension * * @category Instruction Types * @param whirlpoolsConfig - PublicKey for the whirlpools config account * @param whirlpoolsConfigExtension - The public key for the WhirlpoolsConfigExtension * @param configExtensionAuthority - The current configExtensionAuthority in the WhirlpoolsConfigExtension * @param newConfigExtensionAuthority - The new configExtensionAuthority in the WhirlpoolsConfigExtension */ export type SetConfigExtensionAuthorityParams = { whirlpoolsConfig: PublicKey; whirlpoolsConfigExtension: PublicKey; configExtensionAuthority: PublicKey; newConfigExtensionAuthority: PublicKey; }; /** * Sets the config extension authority for a WhirlpoolsConfigExtension. * Only the current config extension authority has permission to invoke this instruction. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetTokenBadgeAuthorityParams object * @returns - Instruction to perform the action. */ export function setConfigExtensionAuthorityIx( program: Program<Whirlpool>, params: SetConfigExtensionAuthorityParams, ): Instruction { const { whirlpoolsConfig, whirlpoolsConfigExtension, configExtensionAuthority, newConfigExtensionAuthority, } = params; const ix = program.instruction.setConfigExtensionAuthority({ accounts: { whirlpoolsConfig, whirlpoolsConfigExtension, configExtensionAuthority, newConfigExtensionAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/swap-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import type { SwapInput } from "../../types/public"; import { MEMO_PROGRAM_ADDRESS } from "../../types/public"; import { RemainingAccountsBuilder, RemainingAccountsType, toSupplementalTickArrayAccountMetas, } from "../../utils/remaining-accounts-util"; /** * Raw parameters and accounts to swap on a Whirlpool * * @category Instruction Types * @param swapInput - Parameters in {@link SwapInput} * @param whirlpool - PublicKey for the whirlpool that the swap will occur on * @param tokenMintA - PublicKey for the token A mint. * @param tokenMintB - PublicKey for the token B mint. * @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet * @param tokenOwnerAccountB - PublicKey for the associated token account for tokenB in the collection wallet * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A. * @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B. * @param tokenProgramA - PublicKey for the token program for token A. * @param tokenProgramB - PublicKey for the token program for token B. * @param oracle - PublicKey for the oracle account for this Whirlpool. * @param tokenAuthority - authority to withdraw tokens from the input token account */ export type SwapV2Params = SwapInput & { whirlpool: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenTransferHookAccountsA?: AccountMeta[]; tokenTransferHookAccountsB?: AccountMeta[]; tokenProgramA: PublicKey; tokenProgramB: PublicKey; oracle: PublicKey; tokenAuthority: PublicKey; }; /** * Perform a swap in this Whirlpool * * #### Special Errors * - `ZeroTradableAmount` - User provided parameter `amount` is 0. * - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade. * - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price. * - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction. * - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick. * - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing. * - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing. * - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0. * - `AmountCalcOverflow` - The required token amount exceeds the u64 range. * - `AmountRemainingOverflow` - Result does not match the specified amount. * - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool. * - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false. * * ### Parameters * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - {@link SwapV2Params} * @returns - Instruction to perform the action. */ export function swapV2Ix( program: Program<Whirlpool>, params: SwapV2Params, ): Instruction { const { amount, otherAmountThreshold, sqrtPriceLimit, amountSpecifiedIsInput, aToB, whirlpool, tokenAuthority, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenVaultA, tokenOwnerAccountB, tokenVaultB, tokenTransferHookAccountsA, tokenTransferHookAccountsB, tokenProgramA, tokenProgramB, tickArray0, tickArray1, tickArray2, oracle, supplementalTickArrays, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA) .addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB) .addSlice( RemainingAccountsType.SupplementalTickArrays, toSupplementalTickArrayAccountMetas(supplementalTickArrays), ) .build(); const ix = program.instruction.swapV2( amount, otherAmountThreshold, sqrtPriceLimit, amountSpecifiedIsInput, aToB, remainingAccountsInfo, { accounts: { tokenProgramA, tokenProgramB, memoProgram: MEMO_PROGRAM_ADDRESS, tokenAuthority: tokenAuthority, whirlpool, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenVaultA, tokenOwnerAccountB, tokenVaultB, tickArray0, tickArray1, tickArray2, oracle, }, remainingAccounts, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/delete-token-badge-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to delete a TokenBadge account. * * @category Instruction Types * @param whirlpoolsConfig - PublicKey for the whirlpools config account * @param whirlpoolsConfigExtension - PublicKey for the whirlpools config extension account * @param tokenBadgeAuthority - PublicKey for the token badge authority * @param tokenMint - Publickey for the mint for which the TokenBadge have been initialized * @param tokenBadge - PublicKey for the token badge account to be deleted * @param receiver - PublicKey for the account that will receive the rent */ export type DeleteTokenBadgeParams = { whirlpoolsConfig: PublicKey; whirlpoolsConfigExtension: PublicKey; tokenBadgeAuthority: PublicKey; tokenMint: PublicKey; tokenBadge: PublicKey; receiver: PublicKey; }; /** * Deletes a TokenBadge account. * * @category Instructions * @param program - program object containing services required to generate the instruction * @param params - DeleteTokenBadgeParams object * @returns - Instruction to perform the action. */ export function deleteTokenBadgeIx( program: Program<Whirlpool>, params: DeleteTokenBadgeParams, ): Instruction { const { whirlpoolsConfig, whirlpoolsConfigExtension, tokenBadgeAuthority, tokenMint, tokenBadge, receiver, } = params; const ix = program.instruction.deleteTokenBadge({ accounts: { whirlpoolsConfig, whirlpoolsConfigExtension, tokenBadgeAuthority, tokenMint, tokenBadge, receiver, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/decrease-liquidity-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import type { DecreaseLiquidityInput } from "../.."; import { MEMO_PROGRAM_ADDRESS } from "../.."; import { RemainingAccountsBuilder, RemainingAccountsType, } from "../../utils/remaining-accounts-util"; /** * Parameters to remove liquidity from a position. * * @category Instruction Types * @param liquidityAmount - The total amount of Liquidity the user is withdrawing * @param tokenMinA - The minimum amount of token A to remove from the position. * @param tokenMinB - The minimum amount of token B to remove from the position. * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param positionAuthority - authority that owns the token corresponding to this desired position. * @param tokenMintA - PublicKey for the token A mint. * @param tokenMintB - PublicKey for the token B mint. * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from. * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A. * @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B. * @param tokenProgramA - PublicKey for the token program for token A. * @param tokenProgramB - PublicKey for the token program for token B. * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index. * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index. */ export type DecreaseLiquidityV2Params = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenTransferHookAccountsA?: AccountMeta[]; tokenTransferHookAccountsB?: AccountMeta[]; tokenProgramA: PublicKey; tokenProgramB: PublicKey; tickArrayLower: PublicKey; tickArrayUpper: PublicKey; } & DecreaseLiquidityInput; /** * Remove liquidity to a position in the Whirlpool. * * #### Special Errors * - `LiquidityZero` - Provided liquidity amount is zero. * - `LiquidityTooHigh` - Provided liquidity exceeds u128::max. * - `TokenMinSubceeded` - The required token to perform this operation subceeds the user defined amount. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - DecreaseLiquidityV2Params object * @returns - Instruction to perform the action. */ export function decreaseLiquidityV2Ix( program: Program<Whirlpool>, params: DecreaseLiquidityV2Params, ): Instruction { const { liquidityAmount, tokenMinA, tokenMinB, whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenTransferHookAccountsA, tokenTransferHookAccountsB, tokenProgramA, tokenProgramB, tickArrayLower, tickArrayUpper, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA) .addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB) .build(); const ix = program.instruction.decreaseLiquidityV2( liquidityAmount, tokenMinA, tokenMinB, remainingAccountsInfo, { accounts: { whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenProgramA, tokenProgramB, tickArrayLower, tickArrayUpper, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/collect-reward-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import { MEMO_PROGRAM_ADDRESS } from "../.."; import { RemainingAccountsBuilder, RemainingAccountsType, } from "../../utils/remaining-accounts-util"; /** * Parameters to collect rewards from a reward index in a position. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param positionAuthority - authority that owns the token corresponding to this desired position. * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS). * @param rewardMint - PublicKey for the reward token mint. * @param rewardOwnerAccount - PublicKey for the reward token account that the reward will deposit into. * @param rewardVault - PublicKey of the vault account that reward will be withdrawn from. * @param rewardTransferHookAccounts - Optional array of token transfer hook accounts for the reward token. * @param rewardTokenProgram - PublicKey for the token program. */ export type CollectRewardV2Params = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; rewardIndex: number; rewardMint: PublicKey; rewardOwnerAccount: PublicKey; rewardVault: PublicKey; rewardTransferHookAccounts?: AccountMeta[]; rewardTokenProgram: PublicKey; }; /** * Collect rewards accrued for this reward index in a position. * Call updateFeesAndRewards before this to update the position to the newest accrued values. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - CollectRewardV2Params object * @returns - Instruction to perform the action. */ export function collectRewardV2Ix( program: Program<Whirlpool>, params: CollectRewardV2Params, ): Instruction { const { whirlpool, positionAuthority, position, positionTokenAccount, rewardMint, rewardOwnerAccount, rewardVault, rewardTransferHookAccounts, rewardIndex, rewardTokenProgram, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice( RemainingAccountsType.TransferHookReward, rewardTransferHookAccounts, ) .build(); const ix = program.instruction.collectRewardV2( rewardIndex, remainingAccountsInfo, { accounts: { whirlpool, positionAuthority, position, positionTokenAccount, rewardMint, rewardOwnerAccount, rewardVault, rewardTokenProgram, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/initialize-config-extension-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to initialize a WhirlpoolsConfigExtension account. * * @category Instruction Types * @ */ export type InitConfigExtensionParams = { whirlpoolsConfig: PublicKey; whirlpoolsConfigExtensionPda: PDA; funder: PublicKey; feeAuthority: PublicKey; }; /** * Initializes a WhirlpoolsConfigExtension account that hosts info & authorities * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitConfigExtensionParams object * @returns - Instruction to perform the action. */ export function initializeConfigExtensionIx( program: Program<Whirlpool>, params: InitConfigExtensionParams, ): Instruction { const { whirlpoolsConfig, whirlpoolsConfigExtensionPda, funder, feeAuthority, } = params; const ix = program.instruction.initializeConfigExtension({ accounts: { config: whirlpoolsConfig, configExtension: whirlpoolsConfigExtensionPda.publicKey, funder, feeAuthority, systemProgram: SystemProgram.programId, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/two-hop-swap-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import { MEMO_PROGRAM_ADDRESS } from "../../types/public"; import { RemainingAccountsBuilder, RemainingAccountsType, toSupplementalTickArrayAccountMetas, } from "../../utils/remaining-accounts-util"; import type { TwoHopSwapInput } from "../two-hop-swap-ix"; /** * Parameters to execute a two-hop swap on a Whirlpool. * * @category Instruction Types * @param whirlpoolOne - PublicKey for the whirlpool that the swap-one will occur on * @param whirlpoolTwo - PublicKey for the whirlpool that the swap-two will occur on * @param tokenMintInput - PublicKey for the input token mint. * @param tokenMintIntermediate - PublicKey for the intermediate token mint. * @param tokenMintOutput - PublicKey for the output token mint. * @param tokenOwnerAccountInput - PublicKey for the input token owner account. * @param tokenOwnerAccountOutput - PublicKey for the output token owner account. * @param tokenVaultOneInput - PublicKey for the input token vault of whirlpoolOne. * @param tokenVaultOneIntermediate - PublicKey for the intermediate token vault of whirlpoolOne. * @param tokenVaultTwoIntermediate - PublicKey for the intermediate token vault of whirlpoolTwo. * @param tokenVaultTwoOutput - PublicKey for the output token vault of whirlpoolTwo. * @param tokenTransferHookAccountsInput - AccountMeta[] for the input token transfer hook accounts. * @param tokenTransferHookAccountsIntermediate - AccountMeta[] for the intermediate token transfer hook accounts. * @param tokenTransferHookAccountsOutput - AccountMeta[] for the output token transfer hook accounts. * @param oracleOne - PublicKey for the oracle account for this whirlpoolOne. * @param oracleTwo - PublicKey for the oracle account for this whirlpoolTwo. * @param tokenAuthority - authority to withdraw tokens from the input token account * @param swapInput - Parameters in {@link TwoHopSwapInput} */ export type TwoHopSwapV2Params = TwoHopSwapInput & { whirlpoolOne: PublicKey; whirlpoolTwo: PublicKey; tokenMintInput: PublicKey; tokenMintIntermediate: PublicKey; tokenMintOutput: PublicKey; tokenOwnerAccountInput: PublicKey; tokenOwnerAccountOutput: PublicKey; tokenVaultOneInput: PublicKey; tokenVaultOneIntermediate: PublicKey; tokenVaultTwoIntermediate: PublicKey; tokenVaultTwoOutput: PublicKey; tokenTransferHookAccountsInput?: AccountMeta[]; tokenTransferHookAccountsIntermediate?: AccountMeta[]; tokenTransferHookAccountsOutput?: AccountMeta[]; tokenProgramInput: PublicKey; tokenProgramIntermediate: PublicKey; tokenProgramOutput: PublicKey; oracleOne: PublicKey; oracleTwo: PublicKey; tokenAuthority: PublicKey; }; /** * Perform a two-hop swap in this Whirlpool * * #### Special Errors * - `ZeroTradableAmount` - User provided parameter `amount` is 0. * - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade. * - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price. * - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction. * - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick. * - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing. * - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing. * - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0. * - `InvalidIntermediaryMint` - Error if the intermediary mint between hop one and two do not equal. * - `DuplicateTwoHopPool` - Error if whirlpool one & two are the same pool. * - `AmountCalcOverflow` - The required token amount exceeds the u64 range. * - `AmountRemainingOverflow` - Result does not match the specified amount. * - `DifferentWhirlpoolTickArrayAccount` - The provided tick array account does not belong to the whirlpool. * - `PartialFillError` - Partially filled when sqrtPriceLimit = 0 and amountSpecifiedIsInput = false. * - `IntermediateTokenAmountMismatch` - The amount of tokens received from the first hop does not match the amount sent to the second hop. * * ### Parameters * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - {@link TwoHopSwapV2Params} object * @returns - Instruction to perform the action. */ export function twoHopSwapV2Ix( program: Program<Whirlpool>, params: TwoHopSwapV2Params, ): Instruction { const { amount, otherAmountThreshold, amountSpecifiedIsInput, aToBOne, aToBTwo, sqrtPriceLimitOne, sqrtPriceLimitTwo, whirlpoolOne, whirlpoolTwo, tokenMintInput, tokenMintIntermediate, tokenMintOutput, tokenProgramInput, tokenProgramIntermediate, tokenProgramOutput, tokenVaultOneInput, tokenVaultOneIntermediate, tokenVaultTwoIntermediate, tokenVaultTwoOutput, tokenAuthority, tokenTransferHookAccountsInput, tokenTransferHookAccountsIntermediate, tokenTransferHookAccountsOutput, tokenOwnerAccountInput, tokenOwnerAccountOutput, tickArrayOne0, tickArrayOne1, tickArrayOne2, tickArrayTwo0, tickArrayTwo1, tickArrayTwo2, oracleOne, oracleTwo, supplementalTickArraysOne, supplementalTickArraysTwo, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice( RemainingAccountsType.TransferHookInput, tokenTransferHookAccountsInput, ) .addSlice( RemainingAccountsType.TransferHookIntermediate, tokenTransferHookAccountsIntermediate, ) .addSlice( RemainingAccountsType.TransferHookOutput, tokenTransferHookAccountsOutput, ) .addSlice( RemainingAccountsType.SupplementalTickArraysOne, toSupplementalTickArrayAccountMetas(supplementalTickArraysOne), ) .addSlice( RemainingAccountsType.SupplementalTickArraysTwo, toSupplementalTickArrayAccountMetas(supplementalTickArraysTwo), ) .build(); const ix = program.instruction.twoHopSwapV2( amount, otherAmountThreshold, amountSpecifiedIsInput, aToBOne, aToBTwo, sqrtPriceLimitOne, sqrtPriceLimitTwo, remainingAccountsInfo, { accounts: { whirlpoolOne, whirlpoolTwo, tokenMintInput, tokenMintIntermediate, tokenMintOutput, tokenProgramInput, tokenProgramIntermediate, tokenProgramOutput, tokenOwnerAccountInput, tokenVaultOneInput, tokenVaultOneIntermediate, tokenVaultTwoIntermediate, tokenVaultTwoOutput, tokenOwnerAccountOutput, tokenAuthority, tickArrayOne0, tickArrayOne1, tickArrayOne2, tickArrayTwo0, tickArrayTwo1, tickArrayTwo2, oracleOne, oracleTwo, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/set-token-badge-authority-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to set the token badge authority in a WhirlpoolsConfigExtension * * @category Instruction Types * @param whirlpoolsConfig - PublicKey for the whirlpools config account * @param whirlpoolsConfigExtension - The public key for the WhirlpoolsConfigExtension * @param configExtensionAuthority - The current configExtensionAuthority in the WhirlpoolsConfigExtension * @param newTokenBadgeAuthority - The new tokenBadgeAuthority in the WhirlpoolsConfigExtension */ export type SetTokenBadgeAuthorityParams = { whirlpoolsConfig: PublicKey; whirlpoolsConfigExtension: PublicKey; configExtensionAuthority: PublicKey; newTokenBadgeAuthority: PublicKey; }; /** * Sets the token badge authority for a WhirlpoolsConfigExtension. * The token badge authority can initialize TokenBadge. * Only the config extension authority has permission to invoke this instruction. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetTokenBadgeAuthorityParams object * @returns - Instruction to perform the action. */ export function setTokenBadgeAuthorityIx( program: Program<Whirlpool>, params: SetTokenBadgeAuthorityParams, ): Instruction { const { whirlpoolsConfig, whirlpoolsConfigExtension, configExtensionAuthority, newTokenBadgeAuthority, } = params; const ix = program.instruction.setTokenBadgeAuthority({ accounts: { whirlpoolsConfig, whirlpoolsConfigExtension, configExtensionAuthority, newTokenBadgeAuthority, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/initialize-reward-ix.ts
import * as anchor from "@coral-xyz/anchor"; import type { Program } from "@coral-xyz/anchor"; import type { Keypair, PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import type { Instruction } from "@orca-so/common-sdk"; /** * Parameters to initialize a rewards for a Whirlpool * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool config space that the fee-tier will be initialized for. * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS). * @param rewardMint - PublicKey for the reward mint that we'd use for the reward index. * @param rewardTokenBadge - PublicKey for the TokenBadge for this reward mint. * @param rewardVaultKeypair - Keypair of the vault for this reward index. * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool * @param funder - The account that would fund the creation of this account * @param rewardTokenProgram - PublicKey for the token program. */ export type InitializeRewardV2Params = { whirlpool: PublicKey; rewardIndex: number; rewardMint: PublicKey; rewardTokenBadge: PublicKey; rewardVaultKeypair: Keypair; rewardAuthority: PublicKey; funder: PublicKey; rewardTokenProgram: PublicKey; }; /** * Initialize reward for a Whirlpool. A pool can only support up to a set number of rewards. * The initial emissionsPerSecond is set to 0. * * #### Special Errors * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool, * or exceeds NUM_REWARDS, or all reward slots for this pool has been initialized. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitializeRewardV2Params object * @returns - Instruction to perform the action. */ export function initializeRewardV2Ix( program: Program<Whirlpool>, params: InitializeRewardV2Params, ): Instruction { const { rewardAuthority, funder, whirlpool, rewardMint, rewardTokenBadge, rewardVaultKeypair, rewardIndex, rewardTokenProgram, } = params; const ix = program.instruction.initializeRewardV2(rewardIndex, { accounts: { rewardAuthority, funder, whirlpool, rewardMint, rewardTokenBadge, rewardVault: rewardVaultKeypair.publicKey, rewardTokenProgram, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [rewardVaultKeypair], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/collect-protocol-fees-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import { MEMO_PROGRAM_ADDRESS } from "../.."; import { RemainingAccountsBuilder, RemainingAccountsType, } from "../../utils/remaining-accounts-util"; /** * Parameters to collect protocol fees for a Whirlpool * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param collectProtocolFeesAuthority - assigned authority in the WhirlpoolsConfig that can collect protocol fees * @param tokenMintA - PublicKey for the token A mint. * @param tokenMintB - PublicKey for the token B mint. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet * @param tokenOwnerAccountB - PublicKey for the associated token account for tokenA in the collection wallet * @param tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A. * @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B. * @param tokenProgramA - PublicKey for the token program for token A. * @param tokenProgramB - PublicKey for the token program for token B. */ export type CollectProtocolFeesV2Params = { whirlpoolsConfig: PublicKey; whirlpool: PublicKey; collectProtocolFeesAuthority: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenTransferHookAccountsA?: AccountMeta[]; tokenTransferHookAccountsB?: AccountMeta[]; tokenProgramA: PublicKey; tokenProgramB: PublicKey; }; /** * Collect protocol fees accrued in this Whirlpool. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - CollectProtocolFeesV2Params object * @returns - Instruction to perform the action. */ export function collectProtocolFeesV2Ix( program: Program<Whirlpool>, params: CollectProtocolFeesV2Params, ): Instruction { const { whirlpoolsConfig, whirlpool, collectProtocolFeesAuthority, tokenMintA, tokenMintB, tokenVaultA, tokenVaultB, tokenTransferHookAccountsA, tokenTransferHookAccountsB, tokenOwnerAccountA: tokenDestinationA, tokenOwnerAccountB: tokenDestinationB, tokenProgramA, tokenProgramB, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA) .addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB) .build(); const ix = program.instruction.collectProtocolFeesV2(remainingAccountsInfo, { accounts: { whirlpoolsConfig, whirlpool, collectProtocolFeesAuthority, tokenMintA, tokenMintB, tokenVaultA, tokenVaultB, tokenDestinationA, tokenDestinationB, tokenProgramA, tokenProgramB, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/index.ts
export * from "./collect-fees-ix"; export * from "./collect-protocol-fees-ix"; export * from "./collect-reward-ix"; export * from "./decrease-liquidity-ix"; export * from "./increase-liquidity-ix"; export * from "./initialize-pool-ix"; export * from "./initialize-reward-ix"; export * from "./set-reward-emissions-ix"; export * from "./swap-ix"; export * from "./two-hop-swap-ix"; export * from "./initialize-config-extension-ix"; export * from "./set-config-extension-authority-ix"; export * from "./set-token-badge-authority-ix"; export * from "./initialize-token-badge-ix"; export * from "./delete-token-badge-ix";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/collect-fees-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import { MEMO_PROGRAM_ADDRESS } from "../.."; import type { Instruction } from "@orca-so/common-sdk"; import { RemainingAccountsBuilder, RemainingAccountsType, } from "../../utils/remaining-accounts-util"; /** * Parameters to collect fees from a position. * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param positionAuthority - authority that owns the token corresponding to this desired position. * @param tokenMintA - PublicKey for the token A mint. * @param tokenMintB - PublicKey for the token B mint. * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from. * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A. * @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B. * @param tokenProgramA - PublicKey for the token program for token A. * @param tokenProgramB - PublicKey for the token program for token B. */ export type CollectFeesV2Params = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenTransferHookAccountsA?: AccountMeta[]; tokenTransferHookAccountsB?: AccountMeta[]; tokenProgramA: PublicKey; tokenProgramB: PublicKey; }; /** * Collect fees accrued for this position. * Call updateFeesAndRewards before this to update the position to the newest accrued values. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - CollectFeesV2Params object * @returns - Instruction to perform the action. */ export function collectFeesV2Ix( program: Program<Whirlpool>, params: CollectFeesV2Params, ): Instruction { const { whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenTransferHookAccountsA, tokenTransferHookAccountsB, tokenProgramA, tokenProgramB, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA) .addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB) .build(); const ix = program.instruction.collectFeesV2(remainingAccountsInfo, { accounts: { whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenProgramA, tokenProgramB, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/initialize-pool-ix.ts
import type { BN, Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { Keypair, PublicKey } from "@solana/web3.js"; import { SystemProgram, SYSVAR_RENT_PUBKEY } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to initialize a Whirlpool account. * * @category Instruction Types * @param initSqrtPrice - The desired initial sqrt-price for this pool * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in * @param whirlpoolPda - PDA for the whirlpool account that would be initialized * @param tokenMintA - Mint public key for token A * @param tokenMintB - Mint public key for token B * @param tokenBadgeA - TokenBadge public key for token A * @param tokenBadgeB - TokenBadge public key for token B * @param tokenProgramA - Token program public key for token A * @param tokenProgramB - Token program public key for token B * @param tokenVaultAKeypair - Keypair of the token A vault for this pool * @param tokenVaultBKeypair - Keypair of the token B vault for this pool * @param feeTierKey - PublicKey of the fee-tier account that this pool would use for the fee-rate * @param tickSpacing - The desired tick spacing for this pool. * @param funder - The account that would fund the creation of this account */ export type InitPoolV2Params = { initSqrtPrice: BN; whirlpoolsConfig: PublicKey; whirlpoolPda: PDA; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenBadgeA: PublicKey; tokenBadgeB: PublicKey; tokenProgramA: PublicKey; tokenProgramB: PublicKey; tokenVaultAKeypair: Keypair; tokenVaultBKeypair: Keypair; feeTierKey: PublicKey; tickSpacing: number; funder: PublicKey; }; /** * Initializes a tick_array account to represent a tick-range in a Whirlpool. * * Special Errors * `InvalidTokenMintOrder` - The order of mints have to be ordered by * `SqrtPriceOutOfBounds` - provided initial_sqrt_price is not between 2^-64 to 2^64 * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - InitPoolV2Params object * @returns - Instruction to perform the action. */ export function initializePoolV2Ix( program: Program<Whirlpool>, params: InitPoolV2Params, ): Instruction { const { initSqrtPrice, tokenMintA, tokenMintB, tokenBadgeA, tokenBadgeB, tokenProgramA, tokenProgramB, whirlpoolsConfig, whirlpoolPda, feeTierKey, tokenVaultAKeypair, tokenVaultBKeypair, tickSpacing, funder, } = params; const ix = program.instruction.initializePoolV2(tickSpacing, initSqrtPrice, { accounts: { whirlpoolsConfig, tokenMintA, tokenMintB, tokenBadgeA, tokenBadgeB, funder, whirlpool: whirlpoolPda.publicKey, tokenVaultA: tokenVaultAKeypair.publicKey, tokenVaultB: tokenVaultBKeypair.publicKey, feeTier: feeTierKey, systemProgram: SystemProgram.programId, tokenProgramA, tokenProgramB, rent: SYSVAR_RENT_PUBKEY, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [tokenVaultAKeypair, tokenVaultBKeypair], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/initialize-token-badge-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { Instruction, PDA } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { SystemProgram } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to initialize a TokenBadge account. * * @category Instruction Types * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig * @param whirlpoolsConfigExtension - The public key for the WhirlpoolsConfigExtension * @param tokenBadgeAuthority - The public key for the tokenBadgeAuthority * @param tokenMint - The public key for the mint for which the TokenBadge is being initialized * @param tokenBadgePda - The PDA for the TokenBadge account * @param funder - The account that would fund the creation of this account */ export type InitializeTokenBadgeParams = { whirlpoolsConfig: PublicKey; whirlpoolsConfigExtension: PublicKey; tokenBadgeAuthority: PublicKey; tokenMint: PublicKey; tokenBadgePda: PDA; funder: PublicKey; }; /** * Initializes a TokenBadge account. * * @category Instructions * @param program - program object containing services required to generate the instruction * @param params - InitializeTokenBadgeParams object * @returns - Instruction to perform the action. */ export function initializeTokenBadgeIx( program: Program<Whirlpool>, params: InitializeTokenBadgeParams, ): Instruction { const { whirlpoolsConfig, whirlpoolsConfigExtension, tokenBadgeAuthority, tokenMint, tokenBadgePda, funder, } = params; const ix = program.instruction.initializeTokenBadge({ accounts: { whirlpoolsConfig, whirlpoolsConfigExtension, tokenBadgeAuthority, tokenMint, tokenBadge: tokenBadgePda.publicKey, funder, systemProgram: SystemProgram.programId, }, }); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/set-reward-emissions-ix.ts
import type { BN, Program } from "@coral-xyz/anchor"; import type { Instruction } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; /** * Parameters to set rewards emissions for a reward in a Whirlpool * * @category Instruction Types * @param whirlpool - PublicKey for the whirlpool which the reward resides in. * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS). * @param rewardVaultKey - PublicKey of the vault for this reward index. * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool * @param emissionsPerSecondX64 - The new emissions per second to set for this reward. */ export type SetRewardEmissionsV2Params = { whirlpool: PublicKey; rewardIndex: number; rewardVaultKey: PublicKey; rewardAuthority: PublicKey; emissionsPerSecondX64: BN; }; /** * Set the reward emissions for a reward in a Whirlpool. * * #### Special Errors * - `RewardVaultAmountInsufficient` - The amount of rewards in the reward vault cannot emit more than a day of desired emissions. * - `InvalidTimestamp` - Provided timestamp is not in order with the previous timestamp. * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool, * or exceeds NUM_REWARDS. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - SetRewardEmissionsV2Params object * @returns - Instruction to perform the action. */ export function setRewardEmissionsV2Ix( program: Program<Whirlpool>, params: SetRewardEmissionsV2Params, ): Instruction { const { rewardAuthority, whirlpool, rewardIndex, rewardVaultKey: rewardVault, emissionsPerSecondX64, } = params; const ix = program.instruction.setRewardEmissionsV2( rewardIndex, emissionsPerSecondX64, { accounts: { rewardAuthority, whirlpool, rewardVault, }, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/instructions/v2/increase-liquidity-ix.ts
import type { Program } from "@coral-xyz/anchor"; import type { AccountMeta, PublicKey } from "@solana/web3.js"; import type { Whirlpool } from "../../artifacts/whirlpool"; import type { IncreaseLiquidityInput } from "../.."; import { MEMO_PROGRAM_ADDRESS } from "../.."; import type { Instruction } from "@orca-so/common-sdk"; import { RemainingAccountsBuilder, RemainingAccountsType, } from "../../utils/remaining-accounts-util"; /** * Parameters to increase liquidity for a position. * * @category Instruction Types * @param liquidityAmount - The total amount of Liquidity the user is willing to deposit. * @param tokenMaxA - The maximum amount of token A to add to the position. * @param tokenMaxB - The maximum amount of token B to add to the position. * @param whirlpool - PublicKey for the whirlpool that the position will be opened for. * @param position - PublicKey for the position will be opened for. * @param positionTokenAccount - PublicKey for the position token's associated token address. * @param positionAuthority - authority that owns the token corresponding to this desired position. * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from. * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from. * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool. * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool. * @param tokenTransferHookAccountsA - Optional array of token transfer hook accounts for token A. * @param tokenTransferHookAccountsB - Optional array of token transfer hook accounts for token B. * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index. * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index. */ export type IncreaseLiquidityV2Params = { whirlpool: PublicKey; position: PublicKey; positionTokenAccount: PublicKey; positionAuthority: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tokenOwnerAccountA: PublicKey; tokenOwnerAccountB: PublicKey; tokenVaultA: PublicKey; tokenVaultB: PublicKey; tokenTransferHookAccountsA?: AccountMeta[]; tokenTransferHookAccountsB?: AccountMeta[]; tokenProgramA: PublicKey; tokenProgramB: PublicKey; tickArrayLower: PublicKey; tickArrayUpper: PublicKey; } & IncreaseLiquidityInput; /** * Add liquidity to a position in the Whirlpool. * * #### Special Errors * `LiquidityZero` - Provided liquidity amount is zero. * `LiquidityTooHigh` - Provided liquidity exceeds u128::max. * `TokenMaxExceeded` - The required token to perform this operation exceeds the user defined amount. * * @category Instructions * @param context - Context object containing services required to generate the instruction * @param params - IncreaseLiquidityV2Params object * @returns - Instruction to perform the action. */ export function increaseLiquidityV2Ix( program: Program<Whirlpool>, params: IncreaseLiquidityV2Params, ): Instruction { const { liquidityAmount, tokenMaxA, tokenMaxB, whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenTransferHookAccountsA, tokenTransferHookAccountsB, tokenProgramA, tokenProgramB, tickArrayLower, tickArrayUpper, } = params; const [remainingAccountsInfo, remainingAccounts] = new RemainingAccountsBuilder() .addSlice(RemainingAccountsType.TransferHookA, tokenTransferHookAccountsA) .addSlice(RemainingAccountsType.TransferHookB, tokenTransferHookAccountsB) .build(); const ix = program.instruction.increaseLiquidityV2( liquidityAmount, tokenMaxA, tokenMaxB, remainingAccountsInfo, { accounts: { whirlpool, positionAuthority, position, positionTokenAccount, tokenMintA, tokenMintB, tokenOwnerAccountA, tokenOwnerAccountB, tokenVaultA, tokenVaultB, tokenProgramA, tokenProgramB, tickArrayLower, tickArrayUpper, memoProgram: MEMO_PROGRAM_ADDRESS, }, remainingAccounts, }, ); return { instructions: [ix], cleanupInstructions: [], signers: [], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/prices/calculate-pool-prices.ts
import type { Address } from "@coral-xyz/anchor"; import { AddressUtil, DecimalUtil, Percentage } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type BN from "bn.js"; import Decimal from "decimal.js"; import type { DecimalsMap, GetPricesConfig, GetPricesThresholdConfig, PoolMap, PriceMap, TickArrayMap, } from "."; import { defaultGetPricesConfig } from "."; import { swapQuoteWithParams } from "../quotes/public/swap-quote"; import type { TickArray, WhirlpoolData } from "../types/public"; import { PoolUtil, PriceMath, SwapUtils } from "../utils/public"; import { NO_TOKEN_EXTENSION_CONTEXT } from "../utils/public/token-extension-util"; import { getTickArrayPublicKeysWithStartTickIndex } from "../utils/swap-utils"; function checkLiquidity( pool: WhirlpoolData, tickArrays: TickArray[], aToB: boolean, thresholdConfig: GetPricesThresholdConfig, decimalsMap: DecimalsMap, ): boolean { const { amountOut, priceImpactThreshold } = thresholdConfig; let estimatedAmountIn; try { ({ estimatedAmountIn } = swapQuoteWithParams( { whirlpoolData: pool, aToB, amountSpecifiedIsInput: false, tokenAmount: amountOut, otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(false), sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB), tickArrays, // To calculate token price, transfer fee is NOT taken into account. tokenExtensionCtx: NO_TOKEN_EXTENSION_CONTEXT, }, Percentage.fromDecimal(new Decimal(0)), )); } catch { // If a quote could not be generated, assume there is insufficient liquidity return false; } // Calculate the maximum amount in that is allowed against the desired output let price, inputDecimals, outputDecimals; if (aToB) { price = getPrice(pool, decimalsMap); inputDecimals = decimalsMap[pool.tokenMintA.toBase58()]; outputDecimals = decimalsMap[pool.tokenMintB.toBase58()]; } else { price = getPrice(pool, decimalsMap).pow(-1); inputDecimals = decimalsMap[pool.tokenMintB.toBase58()]; outputDecimals = decimalsMap[pool.tokenMintA.toBase58()]; } const amountOutDecimals = DecimalUtil.fromBN(amountOut, outputDecimals); const estimatedAmountInDecimals = DecimalUtil.fromBN( estimatedAmountIn, inputDecimals, ); const maxAmountInDecimals = amountOutDecimals .div(price) .mul(priceImpactThreshold) .toDecimalPlaces(inputDecimals); return estimatedAmountInDecimals.lte(maxAmountInDecimals); } type PoolObject = { pool: WhirlpoolData; address: PublicKey }; function getMostLiquidPools( quoteTokenMint: PublicKey, poolMap: PoolMap, ): Record<string, PoolObject> { const mostLiquidPools = new Map<string, PoolObject>(); Object.entries(poolMap).forEach(([address, pool]) => { const mintA = pool.tokenMintA.toBase58(); const mintB = pool.tokenMintB.toBase58(); if (pool.liquidity.isZero()) { return; } if ( !pool.tokenMintA.equals(quoteTokenMint) && !pool.tokenMintB.equals(quoteTokenMint) ) { return; } const baseTokenMint = pool.tokenMintA.equals(quoteTokenMint) ? mintB : mintA; const existingPool = mostLiquidPools.get(baseTokenMint); if (!existingPool || pool.liquidity.gt(existingPool.pool.liquidity)) { mostLiquidPools.set(baseTokenMint, { address: AddressUtil.toPubKey(address), pool, }); } }); return Object.fromEntries(mostLiquidPools); } export function calculatePricesForQuoteToken( mints: Address[], quoteTokenMint: PublicKey, poolMap: PoolMap, tickArrayMap: TickArrayMap, decimalsMap: DecimalsMap, config: GetPricesConfig, thresholdConfig: GetPricesThresholdConfig, ): PriceMap { const mostLiquidPools = getMostLiquidPools(quoteTokenMint, poolMap); return Object.fromEntries( mints.map((mintAddr) => { const mint = AddressUtil.toPubKey(mintAddr); if (mint.equals(quoteTokenMint)) { return [mint.toBase58(), new Decimal(1)]; } const [mintA, mintB] = PoolUtil.orderMints(mint, quoteTokenMint); // The quote token is the output token. // Therefore, if the quote token is mintB, then we are swapping from mintA to mintB. const aToB = AddressUtil.toPubKey(mintB).equals(quoteTokenMint); const baseTokenMint = aToB ? mintA : mintB; const poolCandidate = mostLiquidPools[AddressUtil.toString(baseTokenMint)]; if (poolCandidate === undefined) { return [mint.toBase58(), null]; } const { pool, address } = poolCandidate; const tickArrays = getTickArrays( pool, address, aToB, tickArrayMap, config, ); const isPoolLiquid = checkLiquidity( pool, tickArrays, aToB, thresholdConfig, decimalsMap, ); if (!isPoolLiquid) { return [mint.toBase58(), null]; } const price = getPrice(pool, decimalsMap); const quotePrice = aToB ? price : price.pow(-1); return [mint.toBase58(), quotePrice]; }), ); } function getTickArrays( pool: WhirlpoolData, address: PublicKey, aToB: boolean, tickArrayMap: TickArrayMap, config = defaultGetPricesConfig, ): TickArray[] { const { programId } = config; const tickArrayAddresses = getTickArrayPublicKeysWithStartTickIndex( pool.tickCurrentIndex, pool.tickSpacing, aToB, programId, address, ); return tickArrayAddresses.map((a) => { return { address: a.pubkey, startTickIndex: a.startTickIndex, data: tickArrayMap[a.pubkey.toBase58()], }; }); } function getPrice(pool: WhirlpoolData, decimalsMap: DecimalsMap) { const tokenAAddress = pool.tokenMintA.toBase58(); const tokenBAddress = pool.tokenMintB.toBase58(); if (!(tokenAAddress in decimalsMap) || !(tokenBAddress in decimalsMap)) { throw new Error("Missing token decimals"); } return PriceMath.sqrtPriceX64ToPrice( pool.sqrtPrice, decimalsMap[tokenAAddress], decimalsMap[tokenBAddress], ); } export function isSubset(listA: string[], listB: string[]): boolean { return listA.every((itemA) => listB.includes(itemA)); } export function convertAmount( amount: BN, price: Decimal, amountDecimal: number, resultDecimal: number, ): BN { return DecimalUtil.toBN( DecimalUtil.fromBN(amount, amountDecimal).div(price), resultDecimal, ); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/prices/price-module.ts
import type { Address } from "@coral-xyz/anchor"; import { AddressUtil } from "@orca-so/common-sdk"; import { PublicKey } from "@solana/web3.js"; import type { DecimalsMap, PoolMap, PriceCalculationData, PriceMap, TickArrayMap, } from "."; import { defaultGetPricesConfig, defaultGetPricesThresholdConfig } from "."; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, } from "../network/public/fetcher"; import { IGNORE_CACHE, PREFER_CACHE } from "../network/public/fetcher"; import { PDAUtil, PoolUtil, SwapUtils } from "../utils/public"; import { convertListToMap, filterNullObjects } from "../utils/txn-utils"; import { calculatePricesForQuoteToken, convertAmount, isSubset, } from "./calculate-pool-prices"; /** * PriceModule is a static class that provides functions for fetching and calculating * token prices for a set of pools or mints. * * @category PriceModule * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ export class PriceModule { /** * Fetches and calculates the prices for a set of tokens. * This method will derive the pools that need to be queried from the mints and is not performant. * * @param fetcher {@link WhirlpoolAccountFetcherInterface} * @param mints The mints to fetch prices for. * @param config The configuration for the price calculation. * @param thresholdConfig - The threshold configuration for the price calculation. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @param availableData - Data that is already available to avoid redundant fetches. * @returns A map of token addresses to prices. * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static async fetchTokenPricesByMints( fetcher: WhirlpoolAccountFetcherInterface, mints: Address[], config = defaultGetPricesConfig, thresholdConfig = defaultGetPricesThresholdConfig, opts = IGNORE_CACHE, availableData: Partial<PriceCalculationData> = {}, ): Promise<PriceMap> { const poolMap = availableData?.poolMap ? availableData?.poolMap : await PriceModuleUtils.fetchPoolDataFromMints( fetcher, mints, config, opts, ); const tickArrayMap = availableData?.tickArrayMap ? availableData.tickArrayMap : await PriceModuleUtils.fetchTickArraysForPools( fetcher, poolMap, config, opts, ); const decimalsMap = availableData?.decimalsMap ? availableData.decimalsMap : await PriceModuleUtils.fetchDecimalsForMints( fetcher, mints, PREFER_CACHE, ); return PriceModule.calculateTokenPrices( mints, { poolMap, tickArrayMap, decimalsMap, }, config, thresholdConfig, ); } /** * Fetches and calculates the token prices from a set of pools. * * @param fetcher {@link WhirlpoolAccountFetcherInterface} * @param pools The pools to fetch prices for. * @param config The configuration for the price calculation. * @param thresholdConfig The threshold configuration for the price calculation. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A map of token addresses to prices * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static async fetchTokenPricesByPools( fetcher: WhirlpoolAccountFetcherInterface, pools: Address[], config = defaultGetPricesConfig, thresholdConfig = defaultGetPricesThresholdConfig, opts: WhirlpoolAccountFetchOptions = IGNORE_CACHE, ): Promise<PriceMap> { const poolDatas = Array.from( (await fetcher.getPools(pools, opts)).values(), ); const [filteredPoolDatas, filteredPoolAddresses] = filterNullObjects( poolDatas, pools, ); const poolMap = convertListToMap( filteredPoolDatas, AddressUtil.toStrings(filteredPoolAddresses), ); const tickArrayMap = await PriceModuleUtils.fetchTickArraysForPools( fetcher, poolMap, config, opts, ); const mints = Array.from( Object.values(poolMap).reduce((acc, pool) => { acc.add(pool.tokenMintA.toBase58()); acc.add(pool.tokenMintB.toBase58()); return acc; }, new Set<string>()), ); const decimalsMap = await PriceModuleUtils.fetchDecimalsForMints( fetcher, mints, PREFER_CACHE, ); return PriceModule.calculateTokenPrices( mints, { poolMap, tickArrayMap, decimalsMap, }, config, thresholdConfig, ); } /** * Calculate the price of each token in the mints array. * * Each token will be priced against the first quote token in the config.quoteTokens array * with sufficient liquidity. If a token does not have sufficient liquidity against the * first quote token, then it will be priced against the next quote token in the array. * If a token does not have sufficient liquidity against any quote token, * then the price will be set to null. * * @category PriceModule * @param mints The mints to calculate prices for. * @param priceCalcData The data required to calculate prices. * @param config The configuration for the price calculation. * @param thresholdConfig The threshold configuration for the price calculation. * @returns A map of token addresses to prices. * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static calculateTokenPrices( mints: Address[], priceCalcData: PriceCalculationData, config = defaultGetPricesConfig, thresholdConfig = defaultGetPricesThresholdConfig, ): PriceMap { const { poolMap, decimalsMap, tickArrayMap } = priceCalcData; const mintStrings = AddressUtil.toStrings(mints); // Ensure that quote tokens are in the mints array if ( !isSubset( config.quoteTokens.map((mint) => AddressUtil.toString(mint)), mintStrings.map((mint) => mint), ) ) { throw new Error("Quote tokens must be in mints array"); } const results: PriceMap = Object.fromEntries( mintStrings.map((mint) => [mint, null]), ); const remainingQuoteTokens = config.quoteTokens.slice(); let remainingMints = mints.slice(); while (remainingQuoteTokens.length > 0 && remainingMints.length > 0) { // Get prices for mints using the next token in remainingQuoteTokens as the quote token const quoteToken = remainingQuoteTokens.shift(); if (!quoteToken) { throw new Error("Unreachable: remainingQuoteTokens is an empty array"); } // Convert the threshold amount out from the first quote token to the current quote token let amountOutThresholdAgainstFirstQuoteToken; // If the quote token is the first quote token, then the amount out is the threshold amount if (quoteToken.equals(config.quoteTokens[0])) { amountOutThresholdAgainstFirstQuoteToken = thresholdConfig.amountOut; } else { const quoteTokenStr = quoteToken.toBase58(); const quoteTokenPrice = results[quoteTokenStr]; if (!quoteTokenPrice) { throw new Error( `Quote token - ${quoteTokenStr} must have a price against the first quote token`, ); } amountOutThresholdAgainstFirstQuoteToken = convertAmount( thresholdConfig.amountOut, quoteTokenPrice, decimalsMap[config.quoteTokens[0].toBase58()], decimalsMap[quoteTokenStr], ); } const prices = calculatePricesForQuoteToken( remainingMints, quoteToken, poolMap, tickArrayMap, decimalsMap, config, { amountOut: amountOutThresholdAgainstFirstQuoteToken, priceImpactThreshold: thresholdConfig.priceImpactThreshold, }, ); const quoteTokenPrice = results[quoteToken.toBase58()] || prices[quoteToken.toBase58()]; // Populate the results map with the calculated prices. // Ensure that the price is quoted against the first quote token and not the current quote token. remainingMints.forEach((mintAddr) => { const mint = AddressUtil.toString(mintAddr); const mintPrice = prices[mint]; if (mintPrice != null && quoteTokenPrice != null) { results[mint] = mintPrice.mul(quoteTokenPrice); } }); // Filter out any mints that do not have a price remainingMints = remainingMints.filter( (mint) => results[AddressUtil.toString(mint)] == null, ); } return results; } } /** * A list of utility functions for the price module. * @category PriceModule * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ export class PriceModuleUtils { /** * Fetch pool data for the given mints by deriving the PDA from all combinations of mints & tick-arrays. * Note that this method can be slow. * * @param fetcher {@link WhirlpoolAccountFetcherInterface} * @param mints The mints to fetch pool data for. * @param config The configuration for the price calculation. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A {@link PoolMap} of pool addresses to pool data. * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static async fetchPoolDataFromMints( fetcher: WhirlpoolAccountFetcherInterface, mints: Address[], config = defaultGetPricesConfig, opts = IGNORE_CACHE, ): Promise<PoolMap> { const { quoteTokens, tickSpacings, programId, whirlpoolsConfig } = config; const poolAddresses: string[] = mints .map((mint): string[] => tickSpacings .map((tickSpacing): string[] => { return quoteTokens.map((quoteToken): string => { const [mintA, mintB] = PoolUtil.orderMints(mint, quoteToken); return PDAUtil.getWhirlpool( programId, whirlpoolsConfig, AddressUtil.toPubKey(mintA), AddressUtil.toPubKey(mintB), tickSpacing, ).publicKey.toBase58(); }); }) .flat(), ) .flat(); const poolDatas = Array.from( (await fetcher.getPools(poolAddresses, opts)).values(), ); const [filteredPoolDatas, filteredPoolAddresses] = filterNullObjects( poolDatas, poolAddresses, ); return convertListToMap(filteredPoolDatas, filteredPoolAddresses); } /** * Fetch tick-array data for the given pools * * @param fetcher {@link WhirlpoolAccountFetcherInterface} * @param pools The pools to fetch tick-array data for. * @param config The configuration for the price calculation. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A {@link TickArrayMap} of tick-array addresses to tick-array data. * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static async fetchTickArraysForPools( fetcher: WhirlpoolAccountFetcherInterface, pools: PoolMap, config = defaultGetPricesConfig, opts: WhirlpoolAccountFetchOptions = IGNORE_CACHE, ): Promise<TickArrayMap> { const { programId } = config; const getQuoteTokenOrder = (mint: PublicKey) => { const index = config.quoteTokens.findIndex((quoteToken) => quoteToken.equals(mint), ); return index === -1 ? config.quoteTokens.length : index; }; // select tick arrays based on the direction of swapQuote // TickArray is a large account, which affects decoding time. // Fetching can be performed in parallel, but it is preferable to fetch the minimum number of accounts necessary. const tickArrayAddressSet = new Set<string>(); Object.entries(pools).forEach(([address, pool]) => { const orderA = getQuoteTokenOrder(pool.tokenMintA); const orderB = getQuoteTokenOrder(pool.tokenMintB); if (orderA === orderB) { // neither tokenMintA nor tokenMintB is a quote token return; } const aToB = orderA > orderB; const tickArrayPubkeys = SwapUtils.getTickArrayPublicKeys( pool.tickCurrentIndex, pool.tickSpacing, aToB, programId, new PublicKey(address), ); tickArrayPubkeys.forEach((p) => tickArrayAddressSet.add(p.toBase58())); }); const tickArrayAddresses = Array.from(tickArrayAddressSet); const tickArrays = await fetcher.getTickArrays(tickArrayAddresses, opts); const [filteredTickArrays, filteredTickArrayAddresses] = filterNullObjects( tickArrays, tickArrayAddresses, ); return convertListToMap(filteredTickArrays, filteredTickArrayAddresses); } /** * Fetch the decimals to token mapping for the given mints. * @param fetcher {@link WhirlpoolAccountFetcherInterface} * @param mints The mints to fetch decimals for. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A {@link DecimalsMap} of mint addresses to decimals. * * @deprecated PriceModule will be removed in the future release. Please use endpoint which provides prices. */ static async fetchDecimalsForMints( fetcher: WhirlpoolAccountFetcherInterface, mints: Address[], opts = IGNORE_CACHE, ): Promise<DecimalsMap> { const mintInfos = Array.from( (await fetcher.getMintInfos(mints, opts)).values(), ); return mintInfos.reduce((acc, mintInfo, index) => { const mint = AddressUtil.toString(mints[index]); if (!mintInfo) { throw new Error(`Mint account does not exist: ${mint}`); } acc[mint] = mintInfo.decimals; return acc; }, {} as DecimalsMap); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/prices/index.ts
import { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; import type Decimal from "decimal.js"; import type { TickArrayData, WhirlpoolData } from "../types/public"; import { ORCA_SUPPORTED_TICK_SPACINGS, ORCA_WHIRLPOOLS_CONFIG, ORCA_WHIRLPOOL_PROGRAM_ID, } from "../types/public"; import { TOKEN_MINTS } from "../utils/constants"; export * from "./price-module"; /** * A config object for the {@link PriceModule} functions. * * @category PriceModule * @param quoteTokens The group of quote tokens that you want to search Whirlpools for. * The first token must be the token that is being priced against the other tokens. * The subsequent tokens are alternative tokens that can be used to price the first token. * @param tickSpacings The group of tick spacings that you want to search Whirlpools for. * @param programId The public key of the Whirlpool Program account that you want to search Whirlpools for. * @param whirlpoolsConfig The public key of the {@link WhirlpoolsConfig} account that you want to search Whirlpools for. */ export type GetPricesConfig = { quoteTokens: PublicKey[]; tickSpacings: number[]; programId: PublicKey; whirlpoolsConfig: PublicKey; }; /** * A config object for the {@link PriceModule} functions to define thresholds for price calculations. * Whirlpools that do not fit the criteria set by the parameters below will be excluded in the price calculation. * * @category PriceModule * @param amountOut The token amount in terms of the first quote token amount to evaluate a Whirlpool's liquidity against. * @param priceImpactThreshold Using amountOut to perform a swap quote on a pool, this value is the maximum price impact * that a Whirlpool can have to be included in the price calculation. */ export type GetPricesThresholdConfig = { amountOut: BN; priceImpactThreshold: number; }; /** * A set of fetched accounts that are used for price calculations in {@link PriceModule} functions. * * @category PriceModule * @param poolMap A map of {@link WhirlpoolData} accounts that are used for price calculations. * @param tickArrayMap A map of {@link TickArrayData} accounts that are used for price calculations. * @param decimalsMap A map of token decimals that are used for price calculations. */ export type PriceCalculationData = { poolMap: PoolMap; tickArrayMap: TickArrayMap; decimalsMap: DecimalsMap; }; /** * A map of whirlpool addresses against {@link WhirlpoolData} accounts * @category PriceModule */ export type PoolMap = Record<string, WhirlpoolData>; /** * A map of tick-array addresses against {@link TickArrayData} accounts * @category PriceModule */ export type TickArrayMap = Record<string, TickArrayData>; /** * A map of token mint addresses against price values. If a price is not available, the value will be null. * @category PriceModule */ export type PriceMap = Record<string, Decimal | null>; /** * A map of token mint addresses against token decimals. * @category PriceModule */ export type DecimalsMap = Record<string, number>; /** * The default quote tokens used for Orca's mainnet deployment. * Supply your own if you are using a different deployment. * @category PriceModule */ export const defaultQuoteTokens: PublicKey[] = [ TOKEN_MINTS["USDC"], TOKEN_MINTS["SOL"], TOKEN_MINTS["mSOL"], TOKEN_MINTS["stSOL"], ].map((mint) => new PublicKey(mint)); /** * The default {@link GetPricesConfig} config for Orca's mainnet deployment. * @category PriceModule */ export const defaultGetPricesConfig: GetPricesConfig = { quoteTokens: defaultQuoteTokens, tickSpacings: ORCA_SUPPORTED_TICK_SPACINGS, programId: ORCA_WHIRLPOOL_PROGRAM_ID, whirlpoolsConfig: ORCA_WHIRLPOOLS_CONFIG, }; /** * The default {@link GetPricesThresholdConfig} config for Orca's mainnet deployment. * @category PriceModule */ export const defaultGetPricesThresholdConfig: GetPricesThresholdConfig = { amountOut: new BN(1_000_000_000), priceImpactThreshold: 1.05, };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types/public/client-types.ts
import type { PublicKey } from "@solana/web3.js"; import type BN from "bn.js"; import type { TickArrayData, WhirlpoolRewardInfoData } from "./anchor-types"; import type { AccountWithTokenProgram, MintWithTokenProgram, } from "@orca-so/common-sdk"; /** * Extended Mint type to host token info. * @category WhirlpoolClient */ export type TokenInfo = MintWithTokenProgram & { mint: PublicKey }; /** * Extended (token) Account type to host account info for a Token. * @category WhirlpoolClient */ export type TokenAccountInfo = AccountWithTokenProgram; /** * Type to represent a reward for a reward index on a Whirlpool. * @category WhirlpoolClient */ export type WhirlpoolRewardInfo = WhirlpoolRewardInfoData & { initialized: boolean; vaultAmount: BN; }; /** * A wrapper class of a TickArray on a Whirlpool * @category WhirlpoolClient */ export type TickArray = { address: PublicKey; startTickIndex: number; data: TickArrayData | null; };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types/public/constants.ts
import { BN } from "@coral-xyz/anchor"; import { PublicKey } from "@solana/web3.js"; /** * Program ID hosting Orca's Whirlpool program. * @category Constants */ export const ORCA_WHIRLPOOL_PROGRAM_ID = new PublicKey( "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc", ); /** * Orca's WhirlpoolsConfig PublicKey. * @category Constants */ export const ORCA_WHIRLPOOLS_CONFIG = new PublicKey( "2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ", ); /** * Orca's WhirlpoolsConfig PublicKey for Eclipse * @category Constants */ export const ORCA_WHIRLPOOLS_CONFIG_ECLIPSE = new PublicKey( "FVG4oDbGv16hqTUbovjyGmtYikn6UBEnazz6RVDMEFwv", ); /** * Orca's WhirlpoolsConfig PublicKey. * @category Constants */ export const ORCA_WHIRLPOOLS_CONFIG_EXTENSION = new PublicKey( "777H5H3Tp9U11uRVRzFwM8BinfiakbaLT8vQpeuhvEiH", ); /** * Orca's supported tick spacings. * @category Constants */ export const ORCA_SUPPORTED_TICK_SPACINGS = [ 1, 2, 4, 8, 16, 64, 96, 128, 256, 32896, ]; /** * The number of rewards supported by this whirlpool. * @category Constants */ export const NUM_REWARDS = 3; /** * The maximum tick index supported by the Whirlpool program. * @category Constants */ export const MAX_TICK_INDEX = 443636; /** * The minimum tick index supported by the Whirlpool program. * @category Constants */ export const MIN_TICK_INDEX = -443636; /** * The maximum sqrt-price supported by the Whirlpool program. * @category Constants */ export const MAX_SQRT_PRICE = "79226673515401279992447579055"; /** * The minimum sqrt-price supported by the Whirlpool program. * @category Constants */ export const MIN_SQRT_PRICE = "4295048016"; /** * The minimum sqrt-price supported by the Whirlpool program. * @category Constants */ export const MIN_SQRT_PRICE_BN = new BN(MIN_SQRT_PRICE); /** * The maximum sqrt-price supported by the Whirlpool program. * @category Constants */ export const MAX_SQRT_PRICE_BN = new BN(MAX_SQRT_PRICE); /** * The number of initialized ticks that a tick-array account can hold. * @category Constants */ export const TICK_ARRAY_SIZE = 88; /** * The number of bundled positions that a position-bundle account can hold. * @category Constants */ export const POSITION_BUNDLE_SIZE = 256; /** * @category Constants */ export const METADATA_PROGRAM_ADDRESS = new PublicKey( "metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s", ); /** * @category Constants */ export const MEMO_PROGRAM_ADDRESS = new PublicKey( "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", ); /** * The maximum number of tick-arrays that can traversed across in a swap. * @category Constants */ export const MAX_SWAP_TICK_ARRAYS = 3; /** * The maximum number of supplemental tick-arrays that can be provided in a swap. * @category Constants */ export const MAX_SUPPLEMENTAL_TICK_ARRAYS = 3; /** * The denominator which the protocol fee rate is divided on. * @category Constants */ export const PROTOCOL_FEE_RATE_MUL_VALUE = new BN(10_000); /** * The denominator which the fee rate is divided on. * @category Constants */ export const FEE_RATE_MUL_VALUE = new BN(1_000_000); /** * The public key that is allowed to update the metadata of Whirlpool NFTs. * @category Constants */ export const WHIRLPOOL_NFT_UPDATE_AUTH = new PublicKey( "3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr", ); /** * The tick spacing (inclusive) at which a whirlpool only supports full-range positions. * @category Constants */ export const FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD = 32768; /** * The tick spacing for splash pools. * @category Constants */ export const SPLASH_POOL_TICK_SPACING = 32896;
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types/public/ix-types.ts
export type { ClosePositionParams, CollectFeesParams, CollectProtocolFeesParams, CollectRewardParams, DecreaseLiquidityInput, DecreaseLiquidityParams, DevFeeSwapInput, IncreaseLiquidityInput, IncreaseLiquidityParams, InitConfigParams, InitFeeTierParams, InitializeRewardParams, InitPoolParams, InitTickArrayParams, OpenPositionParams, SetCollectProtocolFeesAuthorityParams, SetDefaultFeeRateParams, SetDefaultProtocolFeeRateParams, SetFeeAuthorityParams, SetFeeRateParams, SetProtocolFeeRateParams, SetRewardAuthorityBySuperAuthorityParams, SetRewardAuthorityParams, SetRewardEmissionsParams, SetRewardEmissionsSuperAuthorityParams, SwapInput, SwapParams, UpdateFeesAndRewardsParams, InitializePositionBundleParams, DeletePositionBundleParams, OpenBundledPositionParams, CloseBundledPositionParams, } from "../../instructions"; export type { CollectFeesV2Params, CollectProtocolFeesV2Params, CollectRewardV2Params, DecreaseLiquidityV2Params, IncreaseLiquidityV2Params, InitPoolV2Params, InitializeRewardV2Params, SetRewardEmissionsV2Params, SwapV2Params, TwoHopSwapV2Params, InitConfigExtensionParams, SetConfigExtensionAuthorityParams, SetTokenBadgeAuthorityParams, InitializeTokenBadgeParams, DeleteTokenBadgeParams, } from "../../instructions/v2"; export type { CollectAllParams, CollectAllPositionAddressParams, CollectAllPositionParams, } from "../../instructions/composites";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types/public/index.ts
export * from "./anchor-types"; export type * from "./client-types"; export * from "./constants"; export type * from "./ix-types";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/types/public/anchor-types.ts
import type { BN, Idl } from "@coral-xyz/anchor"; import { BorshAccountsCoder } from "@coral-xyz/anchor"; import type { PublicKey } from "@solana/web3.js"; import WhirlpoolIDL from "../../artifacts/whirlpool.json"; /** * This file contains the types that has the same structure as the types anchor functions returns. * These types are hard-casted by the client function. * * This file must be manually updated every time the idl updates as accounts will * be hard-casted to fit the type. */ /** * Supported parasable account names from the Whirlpool contract. * @category Network */ export enum AccountName { WhirlpoolsConfig = "WhirlpoolsConfig", Position = "Position", TickArray = "TickArray", Whirlpool = "Whirlpool", FeeTier = "FeeTier", PositionBundle = "PositionBundle", WhirlpoolsConfigExtension = "WhirlpoolsConfigExtension", TokenBadge = "TokenBadge", } export const WHIRLPOOL_IDL = WhirlpoolIDL as Idl; /** * The Anchor coder for the Whirlpool program. * @category Solana Accounts */ export const WHIRLPOOL_CODER = new BorshAccountsCoder(WHIRLPOOL_IDL); /** * Get the size of an account owned by the Whirlpool program in bytes. * @param accountName Whirlpool account name * @returns Size in bytes of the account */ export function getAccountSize(accountName: AccountName) { const size = WHIRLPOOL_CODER.size( WHIRLPOOL_IDL.accounts!.find((account) => account.name === accountName)!, ); return size + RESERVED_BYTES[accountName]; } /** * Reserved bytes for each account used for calculating the account size. */ const RESERVED_BYTES: ReservedBytes = { [AccountName.WhirlpoolsConfig]: 2, [AccountName.Position]: 0, [AccountName.TickArray]: 0, [AccountName.Whirlpool]: 0, [AccountName.FeeTier]: 0, [AccountName.PositionBundle]: 64, [AccountName.WhirlpoolsConfigExtension]: 512, [AccountName.TokenBadge]: 128, }; type ReservedBytes = { [name in AccountName]: number; }; /** * Size of the Whirlpool account in bytes. * @deprecated Please use {@link getAccountSize} instead. * @category Solana Accounts */ export const WHIRLPOOL_ACCOUNT_SIZE = getAccountSize(AccountName.Whirlpool); /** * @category Solana Accounts */ export type WhirlpoolsConfigData = { feeAuthority: PublicKey; collectProtocolFeesAuthority: PublicKey; rewardEmissionsSuperAuthority: PublicKey; defaultFeeRate: number; defaultProtocolFeeRate: number; }; /** * @category Solana Accounts */ export type WhirlpoolRewardInfoData = { mint: PublicKey; vault: PublicKey; authority: PublicKey; emissionsPerSecondX64: BN; growthGlobalX64: BN; }; /** * @category Solana Accounts */ export type WhirlpoolBumpsData = { whirlpoolBump: number; }; /** * @category Solana Accounts */ export type WhirlpoolData = { whirlpoolsConfig: PublicKey; whirlpoolBump: number[]; feeRate: number; protocolFeeRate: number; liquidity: BN; sqrtPrice: BN; tickCurrentIndex: number; protocolFeeOwedA: BN; protocolFeeOwedB: BN; tokenMintA: PublicKey; tokenVaultA: PublicKey; feeGrowthGlobalA: BN; tokenMintB: PublicKey; tokenVaultB: PublicKey; feeGrowthGlobalB: BN; rewardLastUpdatedTimestamp: BN; rewardInfos: WhirlpoolRewardInfoData[]; tickSpacing: number; }; /** * @category Solana Accounts */ export type TickArrayData = { whirlpool: PublicKey; startTickIndex: number; ticks: TickData[]; }; /** * @category Solana Accounts */ export type TickData = { initialized: boolean; liquidityNet: BN; liquidityGross: BN; feeGrowthOutsideA: BN; feeGrowthOutsideB: BN; rewardGrowthsOutside: BN[]; }; /** * @category Solana Accounts */ export type PositionRewardInfoData = { growthInsideCheckpoint: BN; amountOwed: BN; }; /** * @category Solana Accounts */ export type OpenPositionBumpsData = { positionBump: number; }; /** * @category Solana Accounts */ export type OpenPositionWithMetadataBumpsData = { positionBump: number; metadataBump: number; }; /** * @category Solana Accounts */ export type PositionData = { whirlpool: PublicKey; positionMint: PublicKey; liquidity: BN; tickLowerIndex: number; tickUpperIndex: number; feeGrowthCheckpointA: BN; feeOwedA: BN; feeGrowthCheckpointB: BN; feeOwedB: BN; rewardInfos: PositionRewardInfoData[]; }; /** * @category Solana Accounts */ export type FeeTierData = { whirlpoolsConfig: PublicKey; tickSpacing: number; defaultFeeRate: number; }; /** * @category Solana Accounts */ export type PositionBundleData = { positionBundleMint: PublicKey; positionBitmap: number[]; }; /** * @category Solana Accounts */ export type WhirlpoolsConfigExtensionData = { whirlpoolsConfig: PublicKey; configExtensionAuthority: PublicKey; tokenBadgeAuthority: PublicKey; }; /** * @category Solana Accounts */ export type TokenBadgeData = { whirlpoolsConfig: PublicKey; tokenMint: PublicKey; };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/swap/swap-manager.ts
import { U64_MAX, ZERO } from "@orca-so/common-sdk"; import BN from "bn.js"; import type { WhirlpoolData } from "../../types/public"; import { PROTOCOL_FEE_RATE_MUL_VALUE } from "../../types/public"; import { computeSwapStep } from "../../utils/math/swap-math"; import { PriceMath } from "../../utils/public"; import type { TickArraySequence } from "./tick-array-sequence"; import { SwapErrorCode, WhirlpoolsError } from "../../errors/errors"; export type SwapResult = { amountA: BN; amountB: BN; nextTickIndex: number; nextSqrtPrice: BN; totalFeeAmount: BN; }; export function computeSwap( whirlpoolData: WhirlpoolData, tickSequence: TickArraySequence, tokenAmount: BN, sqrtPriceLimit: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ): SwapResult { let amountRemaining = tokenAmount; let amountCalculated = ZERO; let currSqrtPrice = whirlpoolData.sqrtPrice; let currLiquidity = whirlpoolData.liquidity; let currTickIndex = whirlpoolData.tickCurrentIndex; let totalFeeAmount = ZERO; const feeRate = whirlpoolData.feeRate; const protocolFeeRate = whirlpoolData.protocolFeeRate; let currProtocolFee = new BN(0); let currFeeGrowthGlobalInput = aToB ? whirlpoolData.feeGrowthGlobalA : whirlpoolData.feeGrowthGlobalB; while (amountRemaining.gt(ZERO) && !sqrtPriceLimit.eq(currSqrtPrice)) { let { nextIndex: nextTickIndex } = tickSequence.findNextInitializedTickIndex(currTickIndex); let { nextTickPrice, nextSqrtPriceLimit: targetSqrtPrice } = getNextSqrtPrices(nextTickIndex, sqrtPriceLimit, aToB); const swapComputation = computeSwapStep( amountRemaining, feeRate, currLiquidity, currSqrtPrice, targetSqrtPrice, amountSpecifiedIsInput, aToB, ); totalFeeAmount = totalFeeAmount.add(swapComputation.feeAmount); if (amountSpecifiedIsInput) { amountRemaining = amountRemaining.sub(swapComputation.amountIn); amountRemaining = amountRemaining.sub(swapComputation.feeAmount); amountCalculated = amountCalculated.add(swapComputation.amountOut); } else { amountRemaining = amountRemaining.sub(swapComputation.amountOut); amountCalculated = amountCalculated.add(swapComputation.amountIn); amountCalculated = amountCalculated.add(swapComputation.feeAmount); } if (amountRemaining.isNeg()) { throw new WhirlpoolsError( "Amount remaining is negative.", SwapErrorCode.AmountRemainingOverflow, ); } if (amountCalculated.gt(U64_MAX)) { throw new WhirlpoolsError( "Amount calculated is greater than U64_MAX.", SwapErrorCode.AmountCalcOverflow, ); } let { nextProtocolFee, nextFeeGrowthGlobalInput } = calculateFees( swapComputation.feeAmount, protocolFeeRate, currLiquidity, currProtocolFee, currFeeGrowthGlobalInput, ); currProtocolFee = nextProtocolFee; currFeeGrowthGlobalInput = nextFeeGrowthGlobalInput; if (swapComputation.nextPrice.eq(nextTickPrice)) { const nextTick = tickSequence.getTick(nextTickIndex); if (nextTick.initialized) { currLiquidity = calculateNextLiquidity( nextTick.liquidityNet, currLiquidity, aToB, ); } currTickIndex = aToB ? nextTickIndex - 1 : nextTickIndex; } else { currTickIndex = PriceMath.sqrtPriceX64ToTickIndex( swapComputation.nextPrice, ); } currSqrtPrice = swapComputation.nextPrice; } let { amountA, amountB } = calculateEstTokens( tokenAmount, amountRemaining, amountCalculated, aToB, amountSpecifiedIsInput, ); return { amountA, amountB, nextTickIndex: currTickIndex, nextSqrtPrice: currSqrtPrice, totalFeeAmount, }; } function getNextSqrtPrices( nextTick: number, sqrtPriceLimit: BN, aToB: boolean, ) { const nextTickPrice = PriceMath.tickIndexToSqrtPriceX64(nextTick); const nextSqrtPriceLimit = aToB ? BN.max(sqrtPriceLimit, nextTickPrice) : BN.min(sqrtPriceLimit, nextTickPrice); return { nextTickPrice, nextSqrtPriceLimit }; } function calculateFees( feeAmount: BN, protocolFeeRate: number, currLiquidity: BN, currProtocolFee: BN, currFeeGrowthGlobalInput: BN, ) { let nextProtocolFee = currProtocolFee; let nextFeeGrowthGlobalInput = currFeeGrowthGlobalInput; let globalFee = feeAmount; if (protocolFeeRate > 0) { let delta = calculateProtocolFee(globalFee, protocolFeeRate); globalFee = globalFee.sub(delta); nextProtocolFee = nextProtocolFee.add(currProtocolFee); } if (currLiquidity.gt(ZERO)) { const globalFeeIncrement = globalFee.shln(64).div(currLiquidity); nextFeeGrowthGlobalInput = nextFeeGrowthGlobalInput.add(globalFeeIncrement); } return { nextProtocolFee, nextFeeGrowthGlobalInput, }; } function calculateProtocolFee(globalFee: BN, protocolFeeRate: number) { return globalFee.mul( new BN(protocolFeeRate).div(PROTOCOL_FEE_RATE_MUL_VALUE), ); } function calculateEstTokens( amount: BN, amountRemaining: BN, amountCalculated: BN, aToB: boolean, amountSpecifiedIsInput: boolean, ) { return aToB === amountSpecifiedIsInput ? { amountA: amount.sub(amountRemaining), amountB: amountCalculated, } : { amountA: amountCalculated, amountB: amount.sub(amountRemaining), }; } function calculateNextLiquidity( tickNetLiquidity: BN, currLiquidity: BN, aToB: boolean, ) { return aToB ? currLiquidity.sub(tickNetLiquidity) : currLiquidity.add(tickNetLiquidity); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/swap/tick-array-index.ts
import { TICK_ARRAY_SIZE } from "../../types/public"; export class TickArrayIndex { static fromTickIndex(index: number, tickSpacing: number) { const arrayIndex = Math.floor( Math.floor(index / tickSpacing) / TICK_ARRAY_SIZE, ); let offsetIndex = Math.floor( (index % (tickSpacing * TICK_ARRAY_SIZE)) / tickSpacing, ); if (offsetIndex < 0) { offsetIndex = TICK_ARRAY_SIZE + offsetIndex; } return new TickArrayIndex(arrayIndex, offsetIndex, tickSpacing); } constructor( readonly arrayIndex: number, readonly offsetIndex: number, readonly tickSpacing: number, ) { if (offsetIndex >= TICK_ARRAY_SIZE) { throw new Error( "Invalid offsetIndex - value has to be smaller than TICK_ARRAY_SIZE", ); } if (offsetIndex < 0) { throw new Error("Invalid offsetIndex - value is smaller than 0"); } if (tickSpacing < 0) { throw new Error("Invalid tickSpacing - value is less than 0"); } } toTickIndex() { return ( this.arrayIndex * TICK_ARRAY_SIZE * this.tickSpacing + this.offsetIndex * this.tickSpacing ); } toNextInitializableTickIndex() { return TickArrayIndex.fromTickIndex( this.toTickIndex() + this.tickSpacing, this.tickSpacing, ); } toPrevInitializableTickIndex() { return TickArrayIndex.fromTickIndex( this.toTickIndex() - this.tickSpacing, this.tickSpacing, ); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/swap/swap-quote-impl.ts
import { BN } from "@coral-xyz/anchor"; import { ZERO } from "@orca-so/common-sdk"; import { SwapErrorCode, WhirlpoolsError } from "../../errors/errors"; import { MAX_SQRT_PRICE, MAX_SWAP_TICK_ARRAYS, MIN_SQRT_PRICE, } from "../../types/public"; import type { SwapQuote, SwapQuoteParam } from "../public"; import { computeSwap } from "./swap-manager"; import { TickArraySequence } from "./tick-array-sequence"; import type { TransferFeeIncludedAmount } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; /** * Figure out the quote parameters needed to successfully complete this trade on chain * @param param * @returns * @exceptions */ export function simulateSwap(params: SwapQuoteParam): SwapQuote { const { aToB, whirlpoolData, tickArrays, tokenAmount, sqrtPriceLimit, otherAmountThreshold, amountSpecifiedIsInput, tokenExtensionCtx, } = params; if ( sqrtPriceLimit.gt(new BN(MAX_SQRT_PRICE)) || sqrtPriceLimit.lt(new BN(MIN_SQRT_PRICE)) ) { throw new WhirlpoolsError( "Provided SqrtPriceLimit is out of bounds.", SwapErrorCode.SqrtPriceOutOfBounds, ); } if ( (aToB && sqrtPriceLimit.gt(whirlpoolData.sqrtPrice)) || (!aToB && sqrtPriceLimit.lt(whirlpoolData.sqrtPrice)) ) { throw new WhirlpoolsError( "Provided SqrtPriceLimit is in the opposite direction of the trade.", SwapErrorCode.InvalidSqrtPriceLimitDirection, ); } if (tokenAmount.eq(ZERO)) { throw new WhirlpoolsError( "Provided tokenAmount is zero.", SwapErrorCode.ZeroTradableAmount, ); } const tickSequence = new TickArraySequence( tickArrays, whirlpoolData.tickSpacing, aToB, ); // Ensure 1st search-index resides on the 1st array in the sequence to match smart contract expectation. if (!tickSequence.isValidTickArray0(whirlpoolData.tickCurrentIndex)) { throw new WhirlpoolsError( "TickArray at index 0 does not contain the Whirlpool current tick index.", SwapErrorCode.TickArraySequenceInvalid, ); } if (amountSpecifiedIsInput) { // For ExactIn // computeSwap should be executed with "tokenAmount - transfer fee". const transferFeeExcludedIn = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenAmount, aToB ? tokenExtensionCtx.tokenMintWithProgramA : tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); if (transferFeeExcludedIn.amount.eq(ZERO)) { throw new WhirlpoolsError( "Provided tokenAmount is virtually zero due to transfer fee.", SwapErrorCode.ZeroTradableAmount, ); } const swapResults = computeSwap( whirlpoolData, tickSequence, transferFeeExcludedIn.amount, sqrtPriceLimit, amountSpecifiedIsInput, aToB, ); // otherAmountThreshold should be applied to transfer fee EXCLUDED output amount. const transferFeeExcludedOut = TokenExtensionUtil.calculateTransferFeeExcludedAmount( aToB ? swapResults.amountB : swapResults.amountA, aToB ? tokenExtensionCtx.tokenMintWithProgramB : tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); if (transferFeeExcludedOut.amount.lt(otherAmountThreshold)) { throw new WhirlpoolsError( "Quoted amount for the other token is below the otherAmountThreshold.", SwapErrorCode.AmountOutBelowMinimum, ); } const fullfilled = (aToB ? swapResults.amountA : swapResults.amountB).eq( transferFeeExcludedIn.amount, ); const transferFeeIncludedIn: TransferFeeIncludedAmount = fullfilled ? { amount: tokenAmount, fee: transferFeeExcludedIn.fee } : TokenExtensionUtil.calculateTransferFeeIncludedAmount( aToB ? swapResults.amountA : swapResults.amountB, aToB ? tokenExtensionCtx.tokenMintWithProgramA : tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const numOfTickCrossings = tickSequence.getNumOfTouchedArrays(); if (numOfTickCrossings > MAX_SWAP_TICK_ARRAYS) { throw new WhirlpoolsError( `Input amount causes the quote to traverse more than the allowable amount of tick-arrays ${numOfTickCrossings}`, SwapErrorCode.TickArrayCrossingAboveMax, ); } const touchedArrays = tickSequence.getTouchedArrays(MAX_SWAP_TICK_ARRAYS); return { estimatedAmountIn: transferFeeIncludedIn.amount, estimatedAmountOut: transferFeeExcludedOut.amount, estimatedEndTickIndex: swapResults.nextTickIndex, estimatedEndSqrtPrice: swapResults.nextSqrtPrice, estimatedFeeAmount: swapResults.totalFeeAmount, transferFee: { deductingFromEstimatedAmountIn: transferFeeIncludedIn.fee, deductedFromEstimatedAmountOut: transferFeeExcludedOut.fee, }, amount: tokenAmount, amountSpecifiedIsInput, aToB, otherAmountThreshold, sqrtPriceLimit, tickArray0: touchedArrays[0], tickArray1: touchedArrays[1], tickArray2: touchedArrays[2], }; } // For ExactOut // For ExactOut, computeSwap should be executed with "tokenAmount + transfer fee". const transferFeeIncludedOut = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenAmount, aToB ? tokenExtensionCtx.tokenMintWithProgramB : tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const swapResults = computeSwap( whirlpoolData, tickSequence, transferFeeIncludedOut.amount, sqrtPriceLimit, amountSpecifiedIsInput, aToB, ); // otherAmountThreshold should be applied to transfer fee INCLUDED input amount. const transferFeeIncludedIn = TokenExtensionUtil.calculateTransferFeeIncludedAmount( aToB ? swapResults.amountA : swapResults.amountB, aToB ? tokenExtensionCtx.tokenMintWithProgramA : tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); if (transferFeeIncludedIn.amount.gt(otherAmountThreshold)) { throw new WhirlpoolsError( "Quoted amount for the other token is above the otherAmountThreshold.", SwapErrorCode.AmountInAboveMaximum, ); } const transferFeeExcludedOut = TokenExtensionUtil.calculateTransferFeeExcludedAmount( aToB ? swapResults.amountB : swapResults.amountA, aToB ? tokenExtensionCtx.tokenMintWithProgramB : tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const numOfTickCrossings = tickSequence.getNumOfTouchedArrays(); if (numOfTickCrossings > MAX_SWAP_TICK_ARRAYS) { throw new WhirlpoolsError( `Input amount causes the quote to traverse more than the allowable amount of tick-arrays ${numOfTickCrossings}`, SwapErrorCode.TickArrayCrossingAboveMax, ); } const touchedArrays = tickSequence.getTouchedArrays(MAX_SWAP_TICK_ARRAYS); return { estimatedAmountIn: transferFeeIncludedIn.amount, estimatedAmountOut: transferFeeExcludedOut.amount, estimatedEndTickIndex: swapResults.nextTickIndex, estimatedEndSqrtPrice: swapResults.nextSqrtPrice, estimatedFeeAmount: swapResults.totalFeeAmount, transferFee: { deductingFromEstimatedAmountIn: transferFeeIncludedIn.fee, deductedFromEstimatedAmountOut: transferFeeExcludedOut.fee, }, amount: tokenAmount, amountSpecifiedIsInput, aToB, otherAmountThreshold, sqrtPriceLimit, tickArray0: touchedArrays[0], tickArray1: touchedArrays[1], tickArray2: touchedArrays[2], }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/swap/tick-array-sequence.ts
import { SwapErrorCode, WhirlpoolsError } from "../../errors/errors"; import type { TickArray, TickArrayData, TickData } from "../../types/public"; import { MAX_TICK_INDEX, MIN_TICK_INDEX, TICK_ARRAY_SIZE, } from "../../types/public"; import { TickArrayIndex } from "./tick-array-index"; import type { PublicKey } from "@solana/web3.js"; type InitializedTickArray = TickArray & { // override data: TickArrayData; }; /** * NOTE: differs from contract method of having the swap manager keep track of array index. * This is due to the initial requirement to lazy load tick-arrays. This requirement is no longer necessary. */ export class TickArraySequence { private sequence: InitializedTickArray[]; private touchedArrays: boolean[]; private startArrayIndex: number; constructor( tickArrays: Readonly<TickArray[]>, readonly tickSpacing: number, readonly aToB: boolean, ) { if (!tickArrays[0] || !tickArrays[0].data) { throw new Error("TickArray index 0 must be initialized"); } // If an uninitialized TickArray appears, truncate all TickArrays after it (inclusive). this.sequence = []; for (const tickArray of tickArrays) { if (!tickArray || !tickArray.data) { break; } this.sequence.push({ address: tickArray.address, startTickIndex: tickArray.data.startTickIndex, data: tickArray.data, }); } this.touchedArrays = [...Array<boolean>(this.sequence.length).fill(false)]; this.startArrayIndex = TickArrayIndex.fromTickIndex( this.sequence[0].data.startTickIndex, this.tickSpacing, ).arrayIndex; } isValidTickArray0(tickCurrentIndex: number) { const shift = this.aToB ? 0 : this.tickSpacing; const tickArray = this.sequence[0].data; return this.checkIfIndexIsInTickArrayRange( tickArray.startTickIndex, tickCurrentIndex + shift, ); } getNumOfTouchedArrays() { return this.touchedArrays.filter((val) => !!val).length; } getTouchedArrays(minArraySize: number): PublicKey[] { let result = this.touchedArrays.reduce<PublicKey[]>((prev, curr, index) => { if (curr) { prev.push(this.sequence[index].address); } return prev; }, []); // Edge case: nothing was ever touched. if (result.length === 0) { return []; } // The quote object should contain the specified amount of tick arrays to be plugged // directly into the swap instruction. // If the result does not fit minArraySize, pad the rest with the last touched array const sizeDiff = minArraySize - result.length; if (sizeDiff > 0) { result = result.concat(Array(sizeDiff).fill(result[result.length - 1])); } return result; } getTick(index: number): TickData { const targetTaIndex = TickArrayIndex.fromTickIndex(index, this.tickSpacing); if (!this.isArrayIndexInBounds(targetTaIndex, this.aToB)) { throw new Error( "Provided tick index is out of bounds for this sequence.", ); } const localArrayIndex = this.getLocalArrayIndex( targetTaIndex.arrayIndex, this.aToB, ); const tickArray = this.sequence[localArrayIndex].data; this.touchedArrays[localArrayIndex] = true; if (!tickArray) { throw new WhirlpoolsError( `TickArray at index ${localArrayIndex} is not initialized.`, SwapErrorCode.TickArrayIndexNotInitialized, ); } if (!this.checkIfIndexIsInTickArrayRange(tickArray.startTickIndex, index)) { throw new WhirlpoolsError( `TickArray at index ${localArrayIndex} is unexpected for this sequence.`, SwapErrorCode.TickArraySequenceInvalid, ); } return tickArray.ticks[targetTaIndex.offsetIndex]; } /** * if a->b, currIndex is included in the search * if b->a, currIndex is always ignored * @param currIndex * @returns */ findNextInitializedTickIndex(currIndex: number) { const searchIndex = this.aToB ? currIndex : currIndex + this.tickSpacing; let currTaIndex = TickArrayIndex.fromTickIndex( searchIndex, this.tickSpacing, ); // Throw error if the search attempted to search for an index out of bounds if (!this.isArrayIndexInBounds(currTaIndex, this.aToB)) { throw new WhirlpoolsError( `Swap input value traversed too many arrays. Out of bounds at attempt to traverse tick index - ${currTaIndex.toTickIndex()}.`, SwapErrorCode.TickArraySequenceInvalid, ); } while (this.isArrayIndexInBounds(currTaIndex, this.aToB)) { const currTickData = this.getTick(currTaIndex.toTickIndex()); if (currTickData.initialized) { return { nextIndex: currTaIndex.toTickIndex(), nextTickData: currTickData, }; } currTaIndex = this.aToB ? currTaIndex.toPrevInitializableTickIndex() : currTaIndex.toNextInitializableTickIndex(); } const lastIndexInArray = Math.max( Math.min( this.aToB ? currTaIndex.toTickIndex() + this.tickSpacing : currTaIndex.toTickIndex() - 1, MAX_TICK_INDEX, ), MIN_TICK_INDEX, ); return { nextIndex: lastIndexInArray, nextTickData: null }; } private getLocalArrayIndex(arrayIndex: number, aToB: boolean) { return aToB ? this.startArrayIndex - arrayIndex : arrayIndex - this.startArrayIndex; } /** * Check whether the array index potentially exists in this sequence. * Note: assumes the sequence of tick-arrays are sequential * @param index */ private isArrayIndexInBounds(index: TickArrayIndex, aToB: boolean) { // a+0...a+n-1 array index is ok const localArrayIndex = this.getLocalArrayIndex(index.arrayIndex, aToB); const seqLength = this.sequence.length; return localArrayIndex >= 0 && localArrayIndex < seqLength; } private checkIfIndexIsInTickArrayRange(startTick: number, tickIndex: number) { const upperBound = startTick + this.tickSpacing * TICK_ARRAY_SIZE; return tickIndex >= startTick && tickIndex < upperBound; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/collect-rewards-quote.ts
import { BN } from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import invariant from "tiny-invariant"; import type { PositionData, TickData, WhirlpoolData } from "../../types/public"; import { NUM_REWARDS } from "../../types/public"; import { BitMath } from "../../utils/math/bit-math"; import { PoolUtil } from "../../utils/public/pool-utils"; import type { TokenExtensionContextForReward } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; /** * Parameters needed to generate a quote on collectible rewards on a position. * @category Quotes * @param whirlpool - the account data for the whirlpool this position belongs to * @param position - the account data for the position * @param tickLower - the TickData account for the lower bound of this position * @param tickUpper - the TickData account for the upper bound of this position * @param timeStampInSeconds - optional parameter to generate this quote to a unix time stamp. */ export type CollectRewardsQuoteParam = { whirlpool: WhirlpoolData; position: PositionData; tickLower: TickData; tickUpper: TickData; tokenExtensionCtx: TokenExtensionContextForReward; timeStampInSeconds?: BN; }; /** * An array of reward amounts that is collectible on a position. * @category Quotes */ export type CollectRewardsQuote = { rewardOwed: [BN | undefined, BN | undefined, BN | undefined]; transferFee: { deductedFromRewardOwed: [BN | undefined, BN | undefined, BN | undefined]; }; }; /** * Get a quote on the outstanding rewards owed to a position. * * @category Quotes * @param param A collection of fetched Whirlpool accounts to faciliate the quote. * @returns A quote object containing the rewards owed for each reward in the pool. */ export function collectRewardsQuote( param: CollectRewardsQuoteParam, ): CollectRewardsQuote { const { whirlpool, position, tickLower, tickUpper, timeStampInSeconds, tokenExtensionCtx, } = param; const { tickCurrentIndex, rewardInfos: whirlpoolRewardsInfos, rewardLastUpdatedTimestamp, } = whirlpool; const { tickLowerIndex, tickUpperIndex, liquidity, rewardInfos: positionRewardInfos, } = position; const currTimestampInSeconds = timeStampInSeconds ?? new BN(Date.now()).div(new BN(1000)); const timestampDelta = currTimestampInSeconds.sub( new BN(rewardLastUpdatedTimestamp), ); const rewardOwed: [BN | undefined, BN | undefined, BN | undefined] = [ undefined, undefined, undefined, ]; const transferFee: [BN | undefined, BN | undefined, BN | undefined] = [ undefined, undefined, undefined, ]; for (let i = 0; i < NUM_REWARDS; i++) { // Calculate the reward growth on the outside of the position (growth_above, growth_below) const rewardInfo = whirlpoolRewardsInfos[i]; const positionRewardInfo = positionRewardInfos[i]; invariant(!!rewardInfo, "whirlpoolRewardsInfos cannot be undefined"); const isRewardInitialized = PoolUtil.isRewardInitialized(rewardInfo); if (!isRewardInitialized) { continue; } // Increment the global reward growth tracker based on time elasped since the last whirlpool update. let adjustedRewardGrowthGlobalX64 = rewardInfo.growthGlobalX64; if (!whirlpool.liquidity.isZero()) { const rewardGrowthDelta = BitMath.mulDiv( timestampDelta, rewardInfo.emissionsPerSecondX64, whirlpool.liquidity, 128, ); adjustedRewardGrowthGlobalX64 = rewardInfo.growthGlobalX64.add(rewardGrowthDelta); } // Calculate the reward growth outside of the position const tickLowerRewardGrowthsOutsideX64 = tickLower.rewardGrowthsOutside[i]; const tickUpperRewardGrowthsOutsideX64 = tickUpper.rewardGrowthsOutside[i]; let rewardGrowthsBelowX64: BN = adjustedRewardGrowthGlobalX64; if (tickLower.initialized) { rewardGrowthsBelowX64 = tickCurrentIndex < tickLowerIndex ? MathUtil.subUnderflowU128( adjustedRewardGrowthGlobalX64, tickLowerRewardGrowthsOutsideX64, ) : tickLowerRewardGrowthsOutsideX64; } let rewardGrowthsAboveX64: BN = new BN(0); if (tickUpper.initialized) { rewardGrowthsAboveX64 = tickCurrentIndex < tickUpperIndex ? tickUpperRewardGrowthsOutsideX64 : MathUtil.subUnderflowU128( adjustedRewardGrowthGlobalX64, tickUpperRewardGrowthsOutsideX64, ); } const rewardGrowthInsideX64 = MathUtil.subUnderflowU128( MathUtil.subUnderflowU128( adjustedRewardGrowthGlobalX64, rewardGrowthsBelowX64, ), rewardGrowthsAboveX64, ); // Knowing the growth of the reward checkpoint for the position, calculate and increment the amount owed for each reward. const amountOwedX64 = positionRewardInfo.amountOwed.shln(64); const amountOwed = amountOwedX64 .add( MathUtil.subUnderflowU128( rewardGrowthInsideX64, positionRewardInfo.growthInsideCheckpoint, ).mul(liquidity), ) .shrn(64); const transferFeeExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( amountOwed, tokenExtensionCtx.rewardTokenMintsWithProgram[i]!, tokenExtensionCtx.currentEpoch, ); rewardOwed[i] = transferFeeExcluded.amount; transferFee[i] = transferFeeExcluded.fee; } return { rewardOwed, transferFee: { deductedFromRewardOwed: transferFee, }, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/increase-liquidity-quote.ts
import type { Address } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { AddressUtil, DecimalUtil, ZERO } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; import type Decimal from "decimal.js"; import invariant from "tiny-invariant"; import type { IncreaseLiquidityInput } from "../../instructions"; import { PositionStatus, PositionUtil, adjustForSlippage, getLiquidityFromTokenA, getLiquidityFromTokenB, getTokenAFromLiquidity, getTokenBFromLiquidity, } from "../../utils/position-util"; import { PriceMath, TickUtil } from "../../utils/public"; import type { Whirlpool } from "../../whirlpool-client"; import type { TokenExtensionContextForPool } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; /*** --------- Quote by Input Token --------- ***/ /** * @category Quotes * @param inputTokenAmount - The amount of input tokens to deposit. * @param inputTokenMint - The mint of the input token the user would like to deposit. * @param tokenMintA - The mint of tokenA in the Whirlpool the user is depositing into. * @param tokenMintB -The mint of tokenB in the Whirlpool the user is depositing into. * @param tickCurrentIndex - The Whirlpool's current tickIndex * @param sqrtPrice - The Whirlpool's current sqrtPrice * @param tickLowerIndex - The lower index of the position that we are withdrawing from. * @param tickUpperIndex - The upper index of the position that we are withdrawing from. * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. */ export type IncreaseLiquidityQuoteParam = { inputTokenAmount: BN; inputTokenMint: PublicKey; tokenMintA: PublicKey; tokenMintB: PublicKey; tickCurrentIndex: number; sqrtPrice: BN; tickLowerIndex: number; tickUpperIndex: number; tokenExtensionCtx: TokenExtensionContextForPool; slippageTolerance: Percentage; }; /** * Return object from increase liquidity quote functions. * @category Quotes */ export type IncreaseLiquidityQuote = IncreaseLiquidityInput & IncreaseLiquidityEstimate; type IncreaseLiquidityEstimate = { liquidityAmount: BN; tokenEstA: BN; tokenEstB: BN; transferFee: { deductingFromTokenMaxA: BN; deductingFromTokenMaxB: BN; deductingFromTokenEstA: BN; deductingFromTokenEstB: BN; }; }; /** * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount. * This new version calculates slippage based on price percentage movement, rather than setting the percentage threshold based on token estimates. * * @category Quotes * @param inputTokenAmount - The amount of input tokens to deposit. * @param inputTokenMint - The mint of the input token the user would like to deposit. * @param tickLower - The lower index of the position that we are depositing into. * @param tickUpper - The upper index of the position that we are depositing into. * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. * @param whirlpool - A Whirlpool helper class to help interact with the Whirlpool account. * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix. */ export function increaseLiquidityQuoteByInputTokenUsingPriceSlippage( inputTokenMint: Address, inputTokenAmount: Decimal, tickLower: number, tickUpper: number, slippageTolerance: Percentage, whirlpool: Whirlpool, tokenExtensionCtx: TokenExtensionContextForPool, ) { const data = whirlpool.getData(); const tokenAInfo = whirlpool.getTokenAInfo(); const tokenBInfo = whirlpool.getTokenBInfo(); const inputMint = AddressUtil.toPubKey(inputTokenMint); const inputTokenInfo = inputMint.equals(tokenAInfo.mint) ? tokenAInfo : tokenBInfo; return increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage({ inputTokenMint: inputMint, inputTokenAmount: DecimalUtil.toBN( inputTokenAmount, inputTokenInfo.decimals, ), tickLowerIndex: TickUtil.getInitializableTickIndex( tickLower, data.tickSpacing, ), tickUpperIndex: TickUtil.getInitializableTickIndex( tickUpper, data.tickSpacing, ), slippageTolerance, tokenExtensionCtx, ...data, }); } /** * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount. * This new version calculates slippage based on price percentage movement, rather than setting the percentage threshold based on token estimates. * * @category Quotes * @param param IncreaseLiquidityQuoteParam * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix. */ export function increaseLiquidityQuoteByInputTokenWithParamsUsingPriceSlippage( param: IncreaseLiquidityQuoteParam, ): IncreaseLiquidityQuote { invariant( TickUtil.checkTickInBounds(param.tickLowerIndex), "tickLowerIndex is out of bounds.", ); invariant( TickUtil.checkTickInBounds(param.tickUpperIndex), "tickUpperIndex is out of bounds.", ); invariant( param.inputTokenMint.equals(param.tokenMintA) || param.inputTokenMint.equals(param.tokenMintB), `input token mint ${param.inputTokenMint.toBase58()} does not match any tokens in the provided pool.`, ); const liquidity = getLiquidityFromInputToken(param); if (liquidity.eq(ZERO)) { return { liquidityAmount: ZERO, tokenMaxA: ZERO, tokenMaxB: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductingFromTokenMaxA: ZERO, deductingFromTokenMaxB: ZERO, deductingFromTokenEstA: ZERO, deductingFromTokenEstB: ZERO, }, }; } return increaseLiquidityQuoteByLiquidityWithParams({ liquidity, tickCurrentIndex: param.tickCurrentIndex, sqrtPrice: param.sqrtPrice, tickLowerIndex: param.tickLowerIndex, tickUpperIndex: param.tickUpperIndex, slippageTolerance: param.slippageTolerance, tokenExtensionCtx: param.tokenExtensionCtx, }); } function getLiquidityFromInputToken(params: IncreaseLiquidityQuoteParam) { const { inputTokenMint, inputTokenAmount, tickLowerIndex, tickUpperIndex, sqrtPrice, tokenExtensionCtx, } = params; invariant( tickLowerIndex < tickUpperIndex, `tickLowerIndex(${tickLowerIndex}) must be less than tickUpperIndex(${tickUpperIndex})`, ); if (inputTokenAmount.eq(ZERO)) { return ZERO; } const isTokenA = params.tokenMintA.equals(inputTokenMint); const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); const positionStatus = PositionUtil.getStrictPositionStatus( sqrtPrice, tickLowerIndex, tickUpperIndex, ); if (positionStatus === PositionStatus.BelowRange) { if (!isTokenA) { return ZERO; } const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); return getLiquidityFromTokenA( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPriceUpperX64, false, ); } if (positionStatus === PositionStatus.AboveRange) { if (isTokenA) { return ZERO; } const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return getLiquidityFromTokenB( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPriceUpperX64, false, ); } if (isTokenA) { const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); return getLiquidityFromTokenA( transferFeeExcludedInputTokenAmount.amount, sqrtPrice, sqrtPriceUpperX64, false, ); } else { const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return getLiquidityFromTokenB( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPrice, false, ); } } /*** --------- Quote by Liquidity --------- ***/ /** * @category Quotes * @param liquidity - The amount of liquidity value to deposit into the Whirlpool. * @param tokenMintA - The mint of tokenA in the Whirlpool the user is depositing into. * @param tokenMintB -The mint of tokenB in the Whirlpool the user is depositing into. * @param tickCurrentIndex - The Whirlpool's current tickIndex * @param sqrtPrice - The Whirlpool's current sqrtPrice * @param tickLowerIndex - The lower index of the position that we are withdrawing from. * @param tickUpperIndex - The upper index of the position that we are withdrawing from. * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. */ export type IncreaseLiquidityQuoteByLiquidityParam = { liquidity: BN; tickCurrentIndex: number; sqrtPrice: BN; tickLowerIndex: number; tickUpperIndex: number; tokenExtensionCtx: TokenExtensionContextForPool; slippageTolerance: Percentage; }; export function increaseLiquidityQuoteByLiquidityWithParams( params: IncreaseLiquidityQuoteByLiquidityParam, ): IncreaseLiquidityQuote { if (params.liquidity.eq(ZERO)) { return { liquidityAmount: ZERO, tokenMaxA: ZERO, tokenMaxB: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductingFromTokenMaxA: ZERO, deductingFromTokenMaxB: ZERO, deductingFromTokenEstA: ZERO, deductingFromTokenEstB: ZERO, }, }; } const { tokenEstA, tokenEstB } = getTokenEstimatesFromLiquidity(params); const { lowerBound: [sLowerSqrtPrice, sLowerIndex], upperBound: [sUpperSqrtPrice, sUpperIndex], } = PriceMath.getSlippageBoundForSqrtPrice( params.sqrtPrice, params.slippageTolerance, ); const { tokenEstA: tokenEstALower, tokenEstB: tokenEstBLower } = getTokenEstimatesFromLiquidity({ ...params, sqrtPrice: sLowerSqrtPrice, tickCurrentIndex: sLowerIndex, }); const { tokenEstA: tokenEstAUpper, tokenEstB: tokenEstBUpper } = getTokenEstimatesFromLiquidity({ ...params, sqrtPrice: sUpperSqrtPrice, tickCurrentIndex: sUpperIndex, }); const tokenMaxA = BN.max(BN.max(tokenEstA, tokenEstALower), tokenEstAUpper); const tokenMaxB = BN.max(BN.max(tokenEstB, tokenEstBLower), tokenEstBUpper); const tokenExtensionCtx = params.tokenExtensionCtx; const tokenMaxAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenEstAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenMaxBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const tokenEstBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { liquidityAmount: params.liquidity, tokenMaxA: tokenMaxAIncluded.amount, tokenMaxB: tokenMaxBIncluded.amount, tokenEstA: tokenEstAIncluded.amount, tokenEstB: tokenEstBIncluded.amount, transferFee: { deductingFromTokenMaxA: tokenMaxAIncluded.fee, deductingFromTokenMaxB: tokenMaxBIncluded.fee, deductingFromTokenEstA: tokenEstAIncluded.fee, deductingFromTokenEstB: tokenEstBIncluded.fee, }, }; } function getTokenEstimatesFromLiquidity( params: IncreaseLiquidityQuoteByLiquidityParam, ) { const { liquidity, sqrtPrice, tickLowerIndex, tickUpperIndex } = params; if (liquidity.eq(ZERO)) { throw new Error("liquidity must be greater than 0"); } let tokenEstA = ZERO; let tokenEstB = ZERO; const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); const positionStatus = PositionUtil.getStrictPositionStatus( sqrtPrice, tickLowerIndex, tickUpperIndex, ); if (positionStatus === PositionStatus.BelowRange) { tokenEstA = getTokenAFromLiquidity( liquidity, lowerSqrtPrice, upperSqrtPrice, true, ); } else if (positionStatus === PositionStatus.InRange) { tokenEstA = getTokenAFromLiquidity( liquidity, sqrtPrice, upperSqrtPrice, true, ); tokenEstB = getTokenBFromLiquidity( liquidity, lowerSqrtPrice, sqrtPrice, true, ); } else { tokenEstB = getTokenBFromLiquidity( liquidity, lowerSqrtPrice, upperSqrtPrice, true, ); } return { tokenEstA, tokenEstB }; } /** * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount. * * @category Quotes * @param inputTokenMint - The mint of the input token the user would like to deposit. * @param inputTokenAmount - The amount of input tokens to deposit. * @param tickLower - The lower index of the position that we are withdrawing from. * @param tickUpper - The upper index of the position that we are withdrawing from. * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. * @param whirlpool - A Whirlpool helper class to help interact with the Whirlpool account. * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix. */ export function increaseLiquidityQuoteByInputToken( inputTokenMint: Address, inputTokenAmount: Decimal, tickLower: number, tickUpper: number, slippageTolerance: Percentage, whirlpool: Whirlpool, tokenExtensionCtx: TokenExtensionContextForPool, ) { const data = whirlpool.getData(); const tokenAInfo = whirlpool.getTokenAInfo(); const tokenBInfo = whirlpool.getTokenBInfo(); const inputMint = AddressUtil.toPubKey(inputTokenMint); const inputTokenInfo = inputMint.equals(tokenAInfo.mint) ? tokenAInfo : tokenBInfo; return increaseLiquidityQuoteByInputTokenWithParams({ inputTokenMint: inputMint, inputTokenAmount: DecimalUtil.toBN( inputTokenAmount, inputTokenInfo.decimals, ), tickLowerIndex: TickUtil.getInitializableTickIndex( tickLower, data.tickSpacing, ), tickUpperIndex: TickUtil.getInitializableTickIndex( tickUpper, data.tickSpacing, ), slippageTolerance, tokenExtensionCtx, ...data, }); } /** * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount. * * @category Quotes * @param param IncreaseLiquidityQuoteParam * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix. */ export function increaseLiquidityQuoteByInputTokenWithParams( param: IncreaseLiquidityQuoteParam, ): IncreaseLiquidityQuote { invariant( TickUtil.checkTickInBounds(param.tickLowerIndex), "tickLowerIndex is out of bounds.", ); invariant( TickUtil.checkTickInBounds(param.tickUpperIndex), "tickUpperIndex is out of bounds.", ); invariant( param.inputTokenMint.equals(param.tokenMintA) || param.inputTokenMint.equals(param.tokenMintB), `input token mint ${param.inputTokenMint.toBase58()} does not match any tokens in the provided pool.`, ); const positionStatus = PositionUtil.getStrictPositionStatus( param.sqrtPrice, param.tickLowerIndex, param.tickUpperIndex, ); switch (positionStatus) { case PositionStatus.BelowRange: return quotePositionBelowRange(param); case PositionStatus.InRange: return quotePositionInRange(param); case PositionStatus.AboveRange: return quotePositionAboveRange(param); default: throw new Error(`type ${positionStatus} is an unknown PositionStatus`); } } /** * @deprecated */ function quotePositionBelowRange( param: IncreaseLiquidityQuoteParam, ): IncreaseLiquidityQuote { const { tokenMintA, inputTokenMint, inputTokenAmount, tickLowerIndex, tickUpperIndex, tokenExtensionCtx, slippageTolerance, } = param; if (!tokenMintA.equals(inputTokenMint)) { return { liquidityAmount: ZERO, tokenMaxA: ZERO, tokenMaxB: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductingFromTokenMaxA: ZERO, deductingFromTokenMaxB: ZERO, deductingFromTokenEstA: ZERO, deductingFromTokenEstB: ZERO, }, }; } const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const liquidityAmount = getLiquidityFromTokenA( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPriceUpperX64, false, ); const tokenEstA = getTokenAFromLiquidity( liquidityAmount, sqrtPriceLowerX64, sqrtPriceUpperX64, true, ); const tokenMaxA = adjustForSlippage(tokenEstA, slippageTolerance, true); const tokenMaxAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenEstAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); return { liquidityAmount, tokenMaxA: tokenMaxAIncluded.amount, tokenMaxB: ZERO, tokenEstA: tokenEstAIncluded.amount, tokenEstB: ZERO, transferFee: { deductingFromTokenMaxA: tokenMaxAIncluded.fee, deductingFromTokenMaxB: ZERO, deductingFromTokenEstA: tokenEstAIncluded.fee, deductingFromTokenEstB: ZERO, }, }; } /** * @deprecated */ function quotePositionInRange( param: IncreaseLiquidityQuoteParam, ): IncreaseLiquidityQuote { const { tokenMintA, tokenMintB, sqrtPrice, inputTokenMint, inputTokenAmount, tickLowerIndex, tickUpperIndex, tokenExtensionCtx, slippageTolerance, } = param; const sqrtPriceX64 = sqrtPrice; const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); let tokenEstA: BN; let tokenEstB: BN; let liquidityAmount: BN; if (tokenMintA.equals(inputTokenMint)) { const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); liquidityAmount = getLiquidityFromTokenA( transferFeeExcludedInputTokenAmount.amount, sqrtPriceX64, sqrtPriceUpperX64, false, ); tokenEstA = getTokenAFromLiquidity( liquidityAmount, sqrtPriceX64, sqrtPriceUpperX64, true, ); tokenEstB = getTokenBFromLiquidity( liquidityAmount, sqrtPriceLowerX64, sqrtPriceX64, true, ); } else if (tokenMintB.equals(inputTokenMint)) { const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); liquidityAmount = getLiquidityFromTokenB( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPriceX64, false, ); tokenEstA = getTokenAFromLiquidity( liquidityAmount, sqrtPriceX64, sqrtPriceUpperX64, true, ); tokenEstB = getTokenBFromLiquidity( liquidityAmount, sqrtPriceLowerX64, sqrtPriceX64, true, ); } else { throw new Error("invariant violation"); } const tokenMaxA = adjustForSlippage(tokenEstA, slippageTolerance, true); const tokenMaxB = adjustForSlippage(tokenEstB, slippageTolerance, true); const tokenMaxAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenEstAIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenMaxBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const tokenEstBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { liquidityAmount, tokenMaxA: tokenMaxAIncluded.amount, tokenMaxB: tokenMaxBIncluded.amount, tokenEstA: tokenEstAIncluded.amount, tokenEstB: tokenEstBIncluded.amount, transferFee: { deductingFromTokenMaxA: tokenMaxAIncluded.fee, deductingFromTokenMaxB: tokenMaxBIncluded.fee, deductingFromTokenEstA: tokenEstAIncluded.fee, deductingFromTokenEstB: tokenEstBIncluded.fee, }, }; } /** * @deprecated */ function quotePositionAboveRange( param: IncreaseLiquidityQuoteParam, ): IncreaseLiquidityQuote { const { tokenMintB, inputTokenMint, inputTokenAmount, tickLowerIndex, tickUpperIndex, tokenExtensionCtx, slippageTolerance, } = param; if (!tokenMintB.equals(inputTokenMint)) { return { liquidityAmount: ZERO, tokenMaxA: ZERO, tokenMaxB: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductingFromTokenMaxA: ZERO, deductingFromTokenMaxB: ZERO, deductingFromTokenEstA: ZERO, deductingFromTokenEstB: ZERO, }, }; } const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); const transferFeeExcludedInputTokenAmount = TokenExtensionUtil.calculateTransferFeeExcludedAmount( inputTokenAmount, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const liquidityAmount = getLiquidityFromTokenB( transferFeeExcludedInputTokenAmount.amount, sqrtPriceLowerX64, sqrtPriceUpperX64, false, ); const tokenEstB = getTokenBFromLiquidity( liquidityAmount, sqrtPriceLowerX64, sqrtPriceUpperX64, true, ); const tokenMaxB = adjustForSlippage(tokenEstB, slippageTolerance, true); const tokenMaxBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenMaxB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const tokenEstBIncluded = TokenExtensionUtil.calculateTransferFeeIncludedAmount( tokenEstB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { liquidityAmount, tokenMaxA: ZERO, tokenMaxB: tokenMaxBIncluded.amount, tokenEstA: ZERO, tokenEstB: tokenEstBIncluded.amount, transferFee: { deductingFromTokenMaxA: ZERO, deductingFromTokenMaxB: tokenMaxBIncluded.fee, deductingFromTokenEstA: ZERO, deductingFromTokenEstB: tokenEstBIncluded.fee, }, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/swap-quote.ts
import type { Address } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { AddressUtil } from "@orca-so/common-sdk"; import type BN from "bn.js"; import invariant from "tiny-invariant"; import type { SwapInput } from "../../instructions"; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, } from "../../network/public/fetcher"; import { IGNORE_CACHE } from "../../network/public/fetcher"; import type { TickArray, WhirlpoolData } from "../../types/public"; import { TICK_ARRAY_SIZE } from "../../types/public"; import { PoolUtil, SwapDirection } from "../../utils/public"; import { SwapUtils } from "../../utils/public/swap-utils"; import type { Whirlpool } from "../../whirlpool-client"; import { simulateSwap } from "../swap/swap-quote-impl"; import type { DevFeeSwapQuote } from "./dev-fee-swap-quote"; import type { TokenExtensionContextForPool } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; import { PublicKey } from "@solana/web3.js"; /** * An enum to specify when to use fallback tick array in a swap quote. * @category Quotes */ export enum UseFallbackTickArray { // Always try to include fallback tick array in the swap quote Always = "Always", // Never include fallback tick array in the swap quote Never = "Never", // Use fallback tick array only when tickCurrentIndex is the edge (last quoter) of the first tick array Situational = "Situational", } /** * @category Quotes * * @param tokenAmount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput). * @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput). * @param sqrtPriceLimit - The maximum/minimum price the swap will swap to. * @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A. * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents * the input token of the swap. * @param tickArrays - An sequential array of tick-array objects in the direction of the trade to swap on * @param tokenExtensionCtx - TokenExtensions info for the whirlpool * @param fallbackTickArray - Optional. A reserve in case prices move in the opposite direction */ export type SwapQuoteParam = { whirlpoolData: WhirlpoolData; tokenAmount: BN; otherAmountThreshold: BN; sqrtPriceLimit: BN; aToB: boolean; amountSpecifiedIsInput: boolean; tickArrays: TickArray[]; tokenExtensionCtx: TokenExtensionContextForPool; fallbackTickArray?: PublicKey; }; /** * A collection of estimated values from quoting a swap. * @category Quotes * @link {BaseSwapQuote} * @link {DevFeeSwapQuote} */ export type SwapQuote = NormalSwapQuote | DevFeeSwapQuote; /** * A collection of estimated values from quoting a swap. * @category Quotes * @param estimatedAmountIn - Approximate number of input token swapped in the swap * @param estimatedAmountOut - Approximate number of output token swapped in the swap * @param estimatedEndTickIndex - Approximate tick-index the Whirlpool will land on after this swap * @param estimatedEndSqrtPrice - Approximate sqrtPrice the Whirlpool will land on after this swap * @param estimatedFeeAmount - Approximate feeAmount (all fees) charged on this swap */ export type SwapEstimates = { estimatedAmountIn: BN; estimatedAmountOut: BN; estimatedEndTickIndex: number; estimatedEndSqrtPrice: BN; estimatedFeeAmount: BN; transferFee: { deductingFromEstimatedAmountIn: BN; deductedFromEstimatedAmountOut: BN; }; }; /** * A collection of estimated values from quoting a swap. Object can be directly used in a swap transaction. * @category Quotes */ export type NormalSwapQuote = SwapInput & SwapEstimates; /** * Get an estimated swap quote using input token amount. * * @category Quotes * @param whirlpool - Whirlpool to perform the swap on * @param inputTokenMint - PublicKey for the input token mint to swap with * @param tokenAmount - The amount of input token to swap from * @param slippageTolerance - The amount of slippage to account for in this quote * @param programId - PublicKey for the Whirlpool ProgramId * @param cache - WhirlpoolAccountCacheInterface instance object to fetch solana accounts * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @param useFallbackTickArray - An enum to specify when to use fallback tick array in a swap quote. * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states. */ export async function swapQuoteByInputToken( whirlpool: Whirlpool, inputTokenMint: Address, tokenAmount: BN, slippageTolerance: Percentage, programId: Address, fetcher: WhirlpoolAccountFetcherInterface, opts?: WhirlpoolAccountFetchOptions, useFallbackTickArray: UseFallbackTickArray = UseFallbackTickArray.Never, ): Promise<SwapQuote> { const params = await swapQuoteByToken( whirlpool, inputTokenMint, tokenAmount, true, useFallbackTickArray, programId, fetcher, opts, ); return swapQuoteWithParams(params, slippageTolerance); } /** * Get an estimated swap quote using an output token amount. * * Use this quote to get an estimated amount of input token needed to receive * the defined output token amount. * * @category Quotes * @param whirlpool - Whirlpool to perform the swap on * @param outputTokenMint - PublicKey for the output token mint to swap into * @param tokenAmount - The maximum amount of output token to receive in this swap. * @param slippageTolerance - The amount of slippage to account for in this quote * @param programId - PublicKey for the Whirlpool ProgramId * @param cache - WhirlpoolAccountCacheInterface instance to fetch solana accounts * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @param useFallbackTickArray - An enum to specify when to use fallback tick array in a swap quote. * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states. */ export async function swapQuoteByOutputToken( whirlpool: Whirlpool, outputTokenMint: Address, tokenAmount: BN, slippageTolerance: Percentage, programId: Address, fetcher: WhirlpoolAccountFetcherInterface, opts?: WhirlpoolAccountFetchOptions, useFallbackTickArray: UseFallbackTickArray = UseFallbackTickArray.Never, ): Promise<SwapQuote> { const params = await swapQuoteByToken( whirlpool, outputTokenMint, tokenAmount, false, useFallbackTickArray, programId, fetcher, opts, ); return swapQuoteWithParams(params, slippageTolerance); } /** * Perform a sync swap quote based on the basic swap instruction parameters. * * @category Quotes * @param params - SwapQuote parameters * @param slippageTolerance - The amount of slippage to account for when generating the final quote. * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states. */ export function swapQuoteWithParams( params: SwapQuoteParam, slippageTolerance: Percentage, ): SwapQuote { const quote = simulateSwap({ ...params, tickArrays: SwapUtils.interpolateUninitializedTickArrays( PublicKey.default, params.tickArrays, ), }); if (params.fallbackTickArray) { if (quote.tickArray2.equals(quote.tickArray1)) { // both V1 and V2 can use this fallback quote.tickArray2 = params.fallbackTickArray; } else { // no obvious room for fallback, but V2 can use this field quote.supplementalTickArrays = [params.fallbackTickArray]; } } const slippageAdjustedQuote: SwapQuote = { ...quote, ...SwapUtils.calculateSwapAmountsFromQuote( quote.amount, quote.estimatedAmountIn, quote.estimatedAmountOut, slippageTolerance, quote.amountSpecifiedIsInput, ), }; return slippageAdjustedQuote; } async function swapQuoteByToken( whirlpool: Whirlpool, inputTokenMint: Address, tokenAmount: BN, amountSpecifiedIsInput: boolean, useFallbackTickArray: UseFallbackTickArray, programId: Address, fetcher: WhirlpoolAccountFetcherInterface, opts?: WhirlpoolAccountFetchOptions, ): Promise<SwapQuoteParam> { // If we use whirlpool.getData() here, quote will not be the latest even if opts is IGNORE_CACHE const whirlpoolData = await fetcher.getPool(whirlpool.getAddress(), opts); invariant(!!whirlpoolData, "Whirlpool data not found"); const swapMintKey = AddressUtil.toPubKey(inputTokenMint); const swapTokenType = PoolUtil.getTokenType(whirlpoolData, swapMintKey); invariant( !!swapTokenType, "swapTokenMint does not match any tokens on this pool", ); const aToB = SwapUtils.getSwapDirection( whirlpoolData, swapMintKey, amountSpecifiedIsInput, ) === SwapDirection.AtoB; const tickArrays = await SwapUtils.getTickArrays( whirlpoolData.tickCurrentIndex, whirlpoolData.tickSpacing, aToB, AddressUtil.toPubKey(programId), whirlpool.getAddress(), fetcher, opts, ); const fallbackTickArray = getFallbackTickArray( useFallbackTickArray, tickArrays, aToB, whirlpool, programId, ); const tokenExtensionCtx = await TokenExtensionUtil.buildTokenExtensionContext( fetcher, whirlpoolData, IGNORE_CACHE, ); return { whirlpoolData, tokenAmount, aToB, amountSpecifiedIsInput, sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB), otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold( amountSpecifiedIsInput, ), tickArrays, tokenExtensionCtx, fallbackTickArray, }; } function getFallbackTickArray( useFallbackTickArray: UseFallbackTickArray, tickArrays: TickArray[], aToB: boolean, whirlpool: Whirlpool, programId: Address, ): PublicKey | undefined { if (useFallbackTickArray === UseFallbackTickArray.Never) { return undefined; } const fallbackTickArray = SwapUtils.getFallbackTickArrayPublicKey( tickArrays, whirlpool.getData().tickSpacing, aToB, AddressUtil.toPubKey(programId), whirlpool.getAddress(), ); if ( useFallbackTickArray === UseFallbackTickArray.Always || !fallbackTickArray ) { return fallbackTickArray; } invariant( useFallbackTickArray === UseFallbackTickArray.Situational, `Unexpected UseFallbackTickArray value: ${useFallbackTickArray}`, ); const ticksInArray = whirlpool.getData().tickSpacing * TICK_ARRAY_SIZE; const tickCurrentIndex = whirlpool.getData().tickCurrentIndex; if (aToB) { // A to B (direction is right to left): [ ta2 ][ ta1 ][ ta0 ===] // if tickCurrentIndex is within the rightmost quarter of ta0, use fallbackTickArray const threshold = tickArrays[0].startTickIndex + (ticksInArray / 4) * 3; return tickCurrentIndex >= threshold ? fallbackTickArray : undefined; } else { // B to A (direction is left to right): [=== ta0 ][ ta1 ][ ta2 ] // if tickCurrentIndex is within the leftmost quarter of ta0, use fallbackTickArray const threshold = tickArrays[0].startTickIndex + ticksInArray / 4; return tickCurrentIndex <= threshold ? fallbackTickArray : undefined; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/decrease-liquidity-quote.ts
import { BN } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { ZERO } from "@orca-so/common-sdk"; import invariant from "tiny-invariant"; import type { DecreaseLiquidityInput } from "../../instructions"; import { PositionStatus, PositionUtil, adjustForSlippage, getTokenAFromLiquidity, getTokenBFromLiquidity, } from "../../utils/position-util"; import { PriceMath, TickUtil } from "../../utils/public"; import type { TokenExtensionContextForPool } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; import type { Position, Whirlpool } from "../../whirlpool-client"; /** * @category Quotes * @param liquidity - The desired liquidity to withdraw from the Whirlpool * @param tickCurrentIndex - The Whirlpool's current tickIndex * @param sqrtPrice - The Whirlpool's current sqrtPrice * @param tickLowerIndex - The lower index of the position that we are withdrawing from. * @param tickUpperIndex - The upper index of the position that we are withdrawing from. * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. */ export type DecreaseLiquidityQuoteParam = { liquidity: BN; tickCurrentIndex: number; sqrtPrice: BN; tickLowerIndex: number; tickUpperIndex: number; tokenExtensionCtx: TokenExtensionContextForPool; slippageTolerance: Percentage; }; /** * Return object from decrease liquidity quote functions. * @category Quotes */ export type DecreaseLiquidityQuote = DecreaseLiquidityInput & { tokenEstA: BN; tokenEstB: BN; transferFee: { deductedFromTokenEstA: BN; deductedFromTokenEstB: BN; deductedFromTokenMinA: BN; deductedFromTokenMinB: BN; }; }; /** * Get an estimated quote on the minimum tokens receivable based on the desired withdraw liquidity value. * * @category Quotes * @param liquidity - The desired liquidity to withdraw from the Whirlpool * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received. * @param position - A Position helper class to help interact with the Position account. * @param whirlpool - A Whirlpool helper class to help interact with the Whirlpool account. * @returns An DecreaseLiquidityQuote object detailing the tokenMin & liquidity values to use when calling decrease-liquidity-ix. */ export function decreaseLiquidityQuoteByLiquidity( liquidity: BN, slippageTolerance: Percentage, position: Position, whirlpool: Whirlpool, tokenExtensionCtx: TokenExtensionContextForPool, ) { const positionData = position.getData(); const whirlpoolData = whirlpool.getData(); invariant( liquidity.lte(positionData.liquidity), "Quote liquidity is more than the position liquidity.", ); return decreaseLiquidityQuoteByLiquidityWithParams({ liquidity, slippageTolerance, tickLowerIndex: positionData.tickLowerIndex, tickUpperIndex: positionData.tickUpperIndex, sqrtPrice: whirlpoolData.sqrtPrice, tickCurrentIndex: whirlpoolData.tickCurrentIndex, tokenExtensionCtx, }); } /** * Get an estimated quote on the minimum tokens receivable based on the desired withdraw liquidity value. * * @category Quotes * @param param DecreaseLiquidityQuoteParam * @returns An DecreaseLiquidityInput object detailing the tokenMin & liquidity values to use when calling decrease-liquidity-ix. */ export function decreaseLiquidityQuoteByLiquidityWithParams( params: DecreaseLiquidityQuoteParam, ): DecreaseLiquidityQuote { invariant( TickUtil.checkTickInBounds(params.tickLowerIndex), "tickLowerIndex is out of bounds.", ); invariant( TickUtil.checkTickInBounds(params.tickUpperIndex), "tickUpperIndex is out of bounds.", ); invariant( TickUtil.checkTickInBounds(params.tickCurrentIndex), "tickCurrentIndex is out of bounds.", ); if (params.liquidity.eq(ZERO)) { return { tokenMinA: ZERO, tokenMinB: ZERO, liquidityAmount: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductedFromTokenMinA: ZERO, deductedFromTokenMinB: ZERO, deductedFromTokenEstA: ZERO, deductedFromTokenEstB: ZERO, }, }; } const { tokenExtensionCtx } = params; const { tokenEstA, tokenEstB } = getTokenEstimatesFromLiquidity(params); const [tokenMinA, tokenMinB] = [tokenEstA, tokenEstB].map((tokenEst) => adjustForSlippage(tokenEst, params.slippageTolerance, false), ); const tokenMinAExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenMinA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenEstAExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenEstA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenMinBExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenMinB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const tokenEstBExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenEstB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { tokenMinA: tokenMinAExcluded.amount, tokenMinB: tokenMinBExcluded.amount, tokenEstA: tokenEstAExcluded.amount, tokenEstB: tokenEstBExcluded.amount, liquidityAmount: params.liquidity, transferFee: { deductedFromTokenMinA: tokenMinAExcluded.fee, deductedFromTokenMinB: tokenMinBExcluded.fee, deductedFromTokenEstA: tokenEstAExcluded.fee, deductedFromTokenEstB: tokenEstBExcluded.fee, }, }; } /** * Get an estimated quote on the minimum tokens receivable based on the desired withdraw liquidity value. * This version calculates slippage based on price percentage movement, rather than setting the percentage threshold based on token estimates. * @param params DecreaseLiquidityQuoteParam * @returns A DecreaseLiquidityQuote object detailing the tokenMin & liquidity values to use when calling decrease-liquidity-ix. */ export function decreaseLiquidityQuoteByLiquidityWithParamsUsingPriceSlippage( params: DecreaseLiquidityQuoteParam, ): DecreaseLiquidityQuote { const { tokenExtensionCtx } = params; if (params.liquidity.eq(ZERO)) { return { tokenMinA: ZERO, tokenMinB: ZERO, liquidityAmount: ZERO, tokenEstA: ZERO, tokenEstB: ZERO, transferFee: { deductedFromTokenMinA: ZERO, deductedFromTokenMinB: ZERO, deductedFromTokenEstA: ZERO, deductedFromTokenEstB: ZERO, }, }; } const { tokenEstA, tokenEstB } = getTokenEstimatesFromLiquidity(params); const { lowerBound: [sLowerSqrtPrice, sLowerIndex], upperBound: [sUpperSqrtPrice, sUpperIndex], } = PriceMath.getSlippageBoundForSqrtPrice( params.sqrtPrice, params.slippageTolerance, ); const { tokenEstA: tokenEstALower, tokenEstB: tokenEstBLower } = getTokenEstimatesFromLiquidity({ ...params, sqrtPrice: sLowerSqrtPrice, tickCurrentIndex: sLowerIndex, }); const { tokenEstA: tokenEstAUpper, tokenEstB: tokenEstBUpper } = getTokenEstimatesFromLiquidity({ ...params, sqrtPrice: sUpperSqrtPrice, tickCurrentIndex: sUpperIndex, }); const tokenMinA = BN.min(BN.min(tokenEstA, tokenEstALower), tokenEstAUpper); const tokenMinB = BN.min(BN.min(tokenEstB, tokenEstBLower), tokenEstBUpper); const tokenMinAExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenMinA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenEstAExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenEstA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const tokenMinBExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenMinB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); const tokenEstBExcluded = TokenExtensionUtil.calculateTransferFeeExcludedAmount( tokenEstB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { tokenMinA: tokenMinAExcluded.amount, tokenMinB: tokenMinBExcluded.amount, tokenEstA: tokenEstAExcluded.amount, tokenEstB: tokenEstBExcluded.amount, liquidityAmount: params.liquidity, transferFee: { deductedFromTokenMinA: tokenMinAExcluded.fee, deductedFromTokenMinB: tokenMinBExcluded.fee, deductedFromTokenEstA: tokenEstAExcluded.fee, deductedFromTokenEstB: tokenEstBExcluded.fee, }, }; } function getTokenEstimatesFromLiquidity(params: DecreaseLiquidityQuoteParam) { const { liquidity, tickLowerIndex, tickUpperIndex, sqrtPrice } = params; if (liquidity.eq(ZERO)) { throw new Error("liquidity must be greater than 0"); } let tokenEstA = ZERO; let tokenEstB = ZERO; const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); const positionStatus = PositionUtil.getStrictPositionStatus( sqrtPrice, tickLowerIndex, tickUpperIndex, ); if (positionStatus === PositionStatus.BelowRange) { tokenEstA = getTokenAFromLiquidity( liquidity, lowerSqrtPrice, upperSqrtPrice, false, ); } else if (positionStatus === PositionStatus.InRange) { tokenEstA = getTokenAFromLiquidity( liquidity, sqrtPrice, upperSqrtPrice, false, ); tokenEstB = getTokenBFromLiquidity( liquidity, lowerSqrtPrice, sqrtPrice, false, ); } else { tokenEstB = getTokenBFromLiquidity( liquidity, lowerSqrtPrice, upperSqrtPrice, false, ); } return { tokenEstA, tokenEstB }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/two-hop-swap-quote.ts
import type { TwoHopSwapInput } from "../../instructions"; import type { SwapEstimates, SwapQuote } from "./swap-quote"; /** * A collection of estimated values from quoting a swap. * @category Quotes * @link {NormalTwoHopSwapQuote} * @experimental Not yet ready for use */ export type TwoHopSwapQuote = NormalTwoHopSwapQuote; // TODO dev swap /** * A collection of estimated values from quoting a two-hop-swap. * @category Quotes * @param swapOneEstimates - Estimates for the first leg of the two-hop-swap * @param swapTwoEstimates - Estimates for the second leg of the two-hop-swap * @experimental Not yet ready for use */ export type NormalTwoHopSwapQuote = { swapOneEstimates: SwapEstimates; swapTwoEstimates: SwapEstimates; } & TwoHopSwapInput; /** * Convert two individual swaps into a quote estimate * @category Quotes * @experimental Not yet ready for use */ export function twoHopSwapQuoteFromSwapQuotes( swapQuoteOne: SwapQuote, swapQuoteTwo: SwapQuote, ): TwoHopSwapQuote { const amountSpecifiedIsInput = swapQuoteOne.amountSpecifiedIsInput; // If amount specified is input, then we care about input of the first swap // otherwise we care about output of the second swap let [amount, otherAmountThreshold] = amountSpecifiedIsInput ? [swapQuoteOne.amount, swapQuoteTwo.otherAmountThreshold] : [swapQuoteTwo.amount, swapQuoteOne.otherAmountThreshold]; return { amount, otherAmountThreshold, amountSpecifiedIsInput, aToBOne: swapQuoteOne.aToB, aToBTwo: swapQuoteTwo.aToB, sqrtPriceLimitOne: swapQuoteOne.sqrtPriceLimit, sqrtPriceLimitTwo: swapQuoteTwo.sqrtPriceLimit, tickArrayOne0: swapQuoteOne.tickArray0, tickArrayOne1: swapQuoteOne.tickArray1, tickArrayOne2: swapQuoteOne.tickArray2, tickArrayTwo0: swapQuoteTwo.tickArray0, tickArrayTwo1: swapQuoteTwo.tickArray1, tickArrayTwo2: swapQuoteTwo.tickArray2, supplementalTickArraysOne: swapQuoteOne.supplementalTickArrays, supplementalTickArraysTwo: swapQuoteTwo.supplementalTickArrays, swapOneEstimates: { ...swapQuoteOne }, swapTwoEstimates: { ...swapQuoteTwo }, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/dev-fee-swap-quote.ts
import type { Address } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import type BN from "bn.js"; import { SwapErrorCode, WhirlpoolsError } from "../../errors/errors"; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, } from "../../network/public/fetcher"; import type { Whirlpool } from "../../whirlpool-client"; import type { NormalSwapQuote } from "./swap-quote"; import { swapQuoteByInputToken } from "./swap-quote"; /** * A collection of estimated values from quoting a swap that collects a developer-fee. * @category Quotes * @param estimatedAmountIn - Approximate number of input token swapped in the swap * @param estimatedAmountOut - Approximate number of output token swapped in the swap * @param estimatedEndTickIndex - Approximate tick-index the Whirlpool will land on after this swap * @param estimatedEndSqrtPrice - Approximate sqrtPrice the Whirlpool will land on after this swap * @param estimatedFeeAmount - Approximate feeAmount (all fees) charged on this swap * @param estimatedSwapFeeAmount - Approximate feeAmount (LP + protocol fees) charged on this swap * @param devFeeAmount - FeeAmount (developer fees) charged on this swap */ export type DevFeeSwapQuote = NormalSwapQuote & { // NOTE: DevFeeSwaps supports input-token based swaps only as it is difficult // to collect an exact % amount of dev-fees for output-token based swaps due to slippage. // If there are third party requests in the future for this functionality, we can launch it // but with the caveat that the % collected is only an estimate. amountSpecifiedIsInput: true; estimatedSwapFeeAmount: BN; devFeeAmount: BN; }; /** * Get an estimated swap quote using input token amount while collecting dev fees. * * @category Quotes * @param whirlpool - Whirlpool to perform the swap on * @param inputTokenMint - PublicKey for the input token mint to swap with * @param tokenAmount - The amount of input token to swap from * @param slippageTolerance - The amount of slippage to account for in this quote * @param programId - PublicKey for the Whirlpool ProgramId * @param cache - WhirlpoolAccountCacheInterface instance to fetch solana accounts * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @param devFeePercentage - The percentage amount to send to developer wallet prior to the swap. Percentage num/dem values has to match token decimal. * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states. */ export async function swapQuoteByInputTokenWithDevFees( whirlpool: Whirlpool, inputTokenMint: Address, tokenAmount: BN, slippageTolerance: Percentage, programId: Address, fetcher: WhirlpoolAccountFetcherInterface, devFeePercentage: Percentage, opts?: WhirlpoolAccountFetchOptions, ): Promise<DevFeeSwapQuote> { if (devFeePercentage.toDecimal().greaterThanOrEqualTo(1)) { throw new WhirlpoolsError( "Provided devFeePercentage must be less than 100%", SwapErrorCode.InvalidDevFeePercentage, ); } const devFeeAmount = tokenAmount .mul(devFeePercentage.numerator) .div(devFeePercentage.denominator); const slippageAdjustedQuote = await swapQuoteByInputToken( whirlpool, inputTokenMint, tokenAmount.sub(devFeeAmount), slippageTolerance, programId, fetcher, opts, ); const devFeeAdjustedQuote: DevFeeSwapQuote = { ...slippageAdjustedQuote, amountSpecifiedIsInput: true, estimatedAmountIn: slippageAdjustedQuote.estimatedAmountIn.add(devFeeAmount), estimatedFeeAmount: slippageAdjustedQuote.estimatedFeeAmount.add(devFeeAmount), estimatedSwapFeeAmount: slippageAdjustedQuote.estimatedFeeAmount, devFeeAmount, }; return devFeeAdjustedQuote; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/collect-fees-quote.ts
import type { BN } from "@coral-xyz/anchor"; import { MathUtil } from "@orca-so/common-sdk"; import type { PositionData, TickData, WhirlpoolData } from "../../types/public"; import type { TokenExtensionContextForPool } from "../../utils/public/token-extension-util"; import { TokenExtensionUtil } from "../../utils/public/token-extension-util"; /** * @category Quotes */ export type CollectFeesQuoteParam = { whirlpool: WhirlpoolData; position: PositionData; tickLower: TickData; tickUpper: TickData; tokenExtensionCtx: TokenExtensionContextForPool; }; /** * @category Quotes */ export type CollectFeesQuote = { feeOwedA: BN; feeOwedB: BN; transferFee: { deductedFromFeeOwedA: BN; deductedFromFeeOwedB: BN; }; }; /** * Get a quote on the outstanding fees owed to a position. * * @category Quotes * @param param A collection of fetched Whirlpool accounts to faciliate the quote. * @returns A quote object containing the fees owed for each token in the pool. */ export function collectFeesQuote( param: CollectFeesQuoteParam, ): CollectFeesQuote { const { whirlpool, position, tickLower, tickUpper, tokenExtensionCtx } = param; const { tickCurrentIndex, feeGrowthGlobalA: feeGrowthGlobalAX64, feeGrowthGlobalB: feeGrowthGlobalBX64, } = whirlpool; const { tickLowerIndex, tickUpperIndex, liquidity, feeOwedA, feeOwedB, feeGrowthCheckpointA: feeGrowthCheckpointAX64, feeGrowthCheckpointB: feeGrowthCheckpointBX64, } = position; const { feeGrowthOutsideA: tickLowerFeeGrowthOutsideAX64, feeGrowthOutsideB: tickLowerFeeGrowthOutsideBX64, } = tickLower; const { feeGrowthOutsideA: tickUpperFeeGrowthOutsideAX64, feeGrowthOutsideB: tickUpperFeeGrowthOutsideBX64, } = tickUpper; // Calculate the fee growths inside the position let feeGrowthBelowAX64: BN | null = null; let feeGrowthBelowBX64: BN | null = null; if (tickCurrentIndex < tickLowerIndex) { feeGrowthBelowAX64 = MathUtil.subUnderflowU128( feeGrowthGlobalAX64, tickLowerFeeGrowthOutsideAX64, ); feeGrowthBelowBX64 = MathUtil.subUnderflowU128( feeGrowthGlobalBX64, tickLowerFeeGrowthOutsideBX64, ); } else { feeGrowthBelowAX64 = tickLowerFeeGrowthOutsideAX64; feeGrowthBelowBX64 = tickLowerFeeGrowthOutsideBX64; } let feeGrowthAboveAX64: BN | null = null; let feeGrowthAboveBX64: BN | null = null; if (tickCurrentIndex < tickUpperIndex) { feeGrowthAboveAX64 = tickUpperFeeGrowthOutsideAX64; feeGrowthAboveBX64 = tickUpperFeeGrowthOutsideBX64; } else { feeGrowthAboveAX64 = MathUtil.subUnderflowU128( feeGrowthGlobalAX64, tickUpperFeeGrowthOutsideAX64, ); feeGrowthAboveBX64 = MathUtil.subUnderflowU128( feeGrowthGlobalBX64, tickUpperFeeGrowthOutsideBX64, ); } const feeGrowthInsideAX64 = MathUtil.subUnderflowU128( MathUtil.subUnderflowU128(feeGrowthGlobalAX64, feeGrowthBelowAX64), feeGrowthAboveAX64, ); const feeGrowthInsideBX64 = MathUtil.subUnderflowU128( MathUtil.subUnderflowU128(feeGrowthGlobalBX64, feeGrowthBelowBX64), feeGrowthAboveBX64, ); // Calculate the updated fees owed const feeOwedADelta = MathUtil.subUnderflowU128( feeGrowthInsideAX64, feeGrowthCheckpointAX64, ) .mul(liquidity) .shrn(64); const feeOwedBDelta = MathUtil.subUnderflowU128( feeGrowthInsideBX64, feeGrowthCheckpointBX64, ) .mul(liquidity) .shrn(64); const updatedFeeOwedA = feeOwedA.add(feeOwedADelta); const transferFeeExcludedAmountA = TokenExtensionUtil.calculateTransferFeeExcludedAmount( updatedFeeOwedA, tokenExtensionCtx.tokenMintWithProgramA, tokenExtensionCtx.currentEpoch, ); const updatedFeeOwedB = feeOwedB.add(feeOwedBDelta); const transferFeeExcludedAmountB = TokenExtensionUtil.calculateTransferFeeExcludedAmount( updatedFeeOwedB, tokenExtensionCtx.tokenMintWithProgramB, tokenExtensionCtx.currentEpoch, ); return { feeOwedA: transferFeeExcludedAmountA.amount, feeOwedB: transferFeeExcludedAmountB.amount, transferFee: { deductedFromFeeOwedA: transferFeeExcludedAmountA.fee, deductedFromFeeOwedB: transferFeeExcludedAmountB.fee, }, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/quotes/public/index.ts
export * from "./increase-liquidity-quote"; export * from "./decrease-liquidity-quote"; export * from "./collect-fees-quote"; export * from "./collect-rewards-quote"; export * from "./swap-quote"; export * from "./dev-fee-swap-quote"; export * from "./two-hop-swap-quote";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/index.ts
export * from "./fetcher"; export * from "./parsing";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/parsing.ts
import type { Idl } from "@coral-xyz/anchor"; import { BorshAccountsCoder } from "@coral-xyz/anchor"; import type { ParsableEntity } from "@orca-so/common-sdk"; import { staticImplements } from "@orca-so/common-sdk"; import type { AccountInfo, PublicKey } from "@solana/web3.js"; import * as WhirlpoolIDL from "../../artifacts/whirlpool.json"; import type { FeeTierData, PositionBundleData, PositionData, TickArrayData, TokenBadgeData, WhirlpoolData, WhirlpoolsConfigData, WhirlpoolsConfigExtensionData, } from "../../types/public"; import { AccountName } from "../../types/public"; /** * @category Network */ @staticImplements<ParsableEntity<WhirlpoolsConfigData>>() export class ParsableWhirlpoolsConfig { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): WhirlpoolsConfigData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.WhirlpoolsConfig, accountData); } catch (e) { console.error(`error while parsing WhirlpoolsConfig: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<WhirlpoolData>>() export class ParsableWhirlpool { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): WhirlpoolData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.Whirlpool, accountData); } catch (e) { console.error(`error while parsing Whirlpool: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<PositionData>>() export class ParsablePosition { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): PositionData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.Position, accountData); } catch (e) { console.error(`error while parsing Position: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<TickArrayData>>() export class ParsableTickArray { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): TickArrayData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.TickArray, accountData); } catch (e) { console.error(`error while parsing TickArray: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<FeeTierData>>() export class ParsableFeeTier { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): FeeTierData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.FeeTier, accountData); } catch (e) { console.error(`error while parsing FeeTier: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<PositionBundleData>>() export class ParsablePositionBundle { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): PositionBundleData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.PositionBundle, accountData); } catch (e) { console.error(`error while parsing PositionBundle: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<WhirlpoolsConfigExtensionData>>() export class ParsableWhirlpoolsConfigExtension { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): WhirlpoolsConfigExtensionData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount( AccountName.WhirlpoolsConfigExtension, accountData, ); } catch (e) { console.error(`error while parsing WhirlpoolsConfigExtension: ${e}`); return null; } } } /** * @category Network */ @staticImplements<ParsableEntity<TokenBadgeData>>() export class ParsableTokenBadge { public static parse( address: PublicKey, accountData: AccountInfo<Buffer> | undefined | null, ): TokenBadgeData | null { if (!accountData?.data) { return null; } try { return parseAnchorAccount(AccountName.TokenBadge, accountData); } catch (e) { console.error(`error while parsing TokenBadge: ${e}`); return null; } } } const WhirlpoolCoder = new BorshAccountsCoder(WhirlpoolIDL as Idl); function parseAnchorAccount( accountName: AccountName, accountData: AccountInfo<Buffer>, ) { const data = accountData.data; const discriminator = BorshAccountsCoder.accountDiscriminator(accountName); if (discriminator.compare(data.slice(0, 8))) { console.error("incorrect account name during parsing"); return null; } try { return WhirlpoolCoder.decode(accountName, data); } catch (_e) { console.error("unknown account name during parsing"); return null; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/fetcher/fetcher-types.ts
import type { Address } from "@coral-xyz/anchor"; import type { BasicSupportedTypes, ParsableEntity, SimpleAccountFetchOptions, MintWithTokenProgram, AccountWithTokenProgram as TokenAccountWithTokenProgram, } from "@orca-so/common-sdk"; import type { FeeTierData, PositionBundleData, PositionData, TickArrayData, TokenBadgeData, WhirlpoolData, WhirlpoolsConfigData, WhirlpoolsConfigExtensionData, } from "../../../types/public"; /** * Union type of all the {@link ParsableEntity} types that can be cached in the {@link WhirlpoolAccountFetcherInterface} * @category Network */ export type WhirlpoolSupportedTypes = | WhirlpoolsConfigData | WhirlpoolData | PositionData | TickArrayData | FeeTierData | PositionBundleData | WhirlpoolsConfigExtensionData | TokenBadgeData | BasicSupportedTypes; /** * The default retention periods for each {@link ParsableEntity} type in the {@link WhirlpoolAccountFetcherInterface} * @category Network */ export const DEFAULT_WHIRLPOOL_RETENTION_POLICY: ReadonlyMap< ParsableEntity<WhirlpoolSupportedTypes>, number > = new Map<ParsableEntity<WhirlpoolSupportedTypes>, number>([]); /** * Type to define fetch options for the {@link WhirlpoolAccountFetcherInterface} * @category Network */ export type WhirlpoolAccountFetchOptions = SimpleAccountFetchOptions; /** * Default fetch option for always fetching when making an account request to the {@link WhirlpoolAccountFetcherInterface} * @category Network */ export const IGNORE_CACHE: WhirlpoolAccountFetchOptions = { maxAge: 0 }; /** * Default fetch option for always using the cached value for an account request to the {@link WhirlpoolAccountFetcherInterface} * @category Network */ export const PREFER_CACHE: WhirlpoolAccountFetchOptions = { maxAge: Number.POSITIVE_INFINITY, }; /** * Fetcher interface for fetching {@link WhirlpoolSupportedTypes} from the network * @category Network */ export interface WhirlpoolAccountFetcherInterface { /** * Fetch and cache the rent exempt value * @param refresh If true, will always fetch from the network */ getAccountRentExempt(refresh?: boolean): Promise<number>; /** * Fetch and cache the current epoch info * @param refresh If true, will always fetch from the network */ getEpoch(refresh?: boolean): Promise<number>; /** * Fetch and cache the account for a given Whirlpool addresses * @param address The mint address * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPool( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolData | null>; /** * Fetch and cache the accounts for a given array of Whirlpool addresses * @param addresses The array of mint addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPools( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolData | null>>; /** * Fetch and cache the account for a given Position address * @param address The address of the position account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPosition( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<PositionData | null>; /** * Fetch and cache the accounts for a given array of Position addresses * @param addresses The array of position account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPositions( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, PositionData | null>>; /** * Fetch and cache the account for a given TickArray address. * @param address The address of the tick array account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTickArray( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TickArrayData | null>; /** * Fetch and cache the accounts for a given array of TickArray addresses * @param addresses The array of tick array account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTickArrays( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyArray<TickArrayData | null>>; /** * Fetch and cache the account for a given FeeTier address * @param address The address of the fee tier account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getFeeTier( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<FeeTierData | null>; /** * Fetch and cache the accounts for a given array of FeeTier addresses * @param addresses The array of fee tier account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getFeeTiers( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, FeeTierData | null>>; /** * Fetch and cache the account for a given TokenAccount address * @param address The address of the token account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTokenInfo( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenAccountWithTokenProgram | null>; /** * Fetch and cache the accounts for a given array of TokenAccount addresses * @param addresses The array of token account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTokenInfos( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, TokenAccountWithTokenProgram | null>>; /** * Fetch and cache the account for a given Mint address * @param address The address of the mint account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getMintInfo( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<MintWithTokenProgram | null>; /** * Fetch and cache the accounts for a given array of Mint addresses * @param addresses The array of mint account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getMintInfos( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, MintWithTokenProgram | null>>; /** * Fetch and cache the account for a given WhirlpoolConfig address * @param address The address of the WhirlpoolConfig account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getConfig( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolsConfigData | null>; /** * Fetch and cache the accounts for a given array of WhirlpoolConfig addresses * @param addresses The array of WhirlpoolConfig account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getConfigs( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolsConfigData | null>>; /** * Fetch and cache the account for a given PositionBundle address * @param address The address of the position bundle account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPositionBundle( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<PositionBundleData | null>; /** * Fetch and cache the accounts for a given array of PositionBundle addresses * @param addresses The array of position bundle account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getPositionBundles( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, PositionBundleData | null>>; /** * Fetch and cache the account for a given WhirlpoolConfigExtension address * @param address The address of the WhirlpoolConfigExtension account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getConfigExtension( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolsConfigExtensionData | null>; /** * Fetch and cache the accounts for a given array of WhirlpoolConfigExtension addresses * @param addresses The array of WhirlpoolConfigExtension account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getConfigExtensions( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolsConfigExtensionData | null>>; /** * Fetch and cache the account for a given TokenBadge address * @param address The address of the TokenBadge account * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTokenBadge( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenBadgeData | null>; /** * Fetch and cache the accounts for a given array of TokenBadge addresses * @param addresses The array of TokenBadge account addresses * @param opts {@link WhirlpoolAccountFetchOptions} instance to dictate fetch behavior */ getTokenBadges( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, TokenBadgeData | null>>; /** * Populate the fetcher's cache with the given {@link WhirlpoolsData} accounts * @param accounts The map of addresses to on-chain account data * @param parser The {@link ParsableEntity} instance to parse the accounts * @param now The current timestamp to use for the cache */ populateCache<T extends WhirlpoolSupportedTypes>( accounts: ReadonlyMap<string, T>, parser: ParsableEntity<T>, now: number, ): void; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/fetcher/fetcher-impl.ts
import type { Address } from "@coral-xyz/anchor"; import type { AccountFetcher, ParsableEntity, MintWithTokenProgram, AccountWithTokenProgram as TokenAccountWithTokenProgram, } from "@orca-so/common-sdk"; import { ParsableMintInfo, ParsableTokenAccountInfo, SimpleAccountFetcher, } from "@orca-so/common-sdk"; import { AccountLayout } from "@solana/spl-token"; import type { Connection, EpochInfo } from "@solana/web3.js"; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, WhirlpoolSupportedTypes, } from ".."; import { DEFAULT_WHIRLPOOL_RETENTION_POLICY } from ".."; import type { FeeTierData, PositionBundleData, PositionData, TickArrayData, TokenBadgeData, WhirlpoolData, WhirlpoolsConfigData, WhirlpoolsConfigExtensionData, } from "../../../types/public"; import { ParsableFeeTier, ParsablePosition, ParsablePositionBundle, ParsableTickArray, ParsableWhirlpool, ParsableWhirlpoolsConfig, ParsableWhirlpoolsConfigExtension, ParsableTokenBadge, } from "../parsing"; /** * Build a default instance of {@link WhirlpoolAccountFetcherInterface} with the default {@link AccountFetcher} implementation * @param connection An instance of {@link Connection} to use for fetching accounts * @returns An instance of {@link WhirlpoolAccountFetcherInterface} * @category Network */ export const buildDefaultAccountFetcher = (connection: Connection) => { return new WhirlpoolAccountFetcher( connection, new SimpleAccountFetcher(connection, DEFAULT_WHIRLPOOL_RETENTION_POLICY), ); }; /** * Fetcher and cache layer for fetching {@link WhirlpoolSupportedTypes} from the network * Default implementation for {@link WhirlpoolAccountFetcherInterface} * @category Network */ export class WhirlpoolAccountFetcher implements WhirlpoolAccountFetcherInterface { private _accountRentExempt: number | undefined; private _epochInfo: EpochInfo | undefined; private _epochInfoNextFetchTime: number = 0; constructor( readonly connection: Connection, readonly fetcher: AccountFetcher< WhirlpoolSupportedTypes, WhirlpoolAccountFetchOptions >, ) {} async getAccountRentExempt(refresh: boolean = false): Promise<number> { // This value should be relatively static or at least not break according to spec // https://solana.com/docs/terminology#rent-exempt if (!this._accountRentExempt || refresh) { this._accountRentExempt = await this.connection.getMinimumBalanceForRentExemption( AccountLayout.span, ); } return this._accountRentExempt; } async getEpoch(refresh: boolean = false): Promise<number> { if ( !this._epochInfo || Date.now() >= this._epochInfoNextFetchTime || refresh ) { const epochInfo = await this.connection.getEpochInfo(); // In theory, 1 slot per every 400ms. // 320ms is 80% of 400ms. const remainingSlotsInEpoch = Math.max( epochInfo.slotsInEpoch - epochInfo.slotIndex, 0, ); const nextFetchTime = Date.now() + remainingSlotsInEpoch * 320; this._epochInfo = epochInfo; this._epochInfoNextFetchTime = nextFetchTime; } return this._epochInfo.epoch; } getPool( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolData | null> { return this.fetcher.getAccount(address, ParsableWhirlpool, opts); } getPools( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolData | null>> { return this.fetcher.getAccounts(addresses, ParsableWhirlpool, opts); } getPosition( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<PositionData | null> { return this.fetcher.getAccount(address, ParsablePosition, opts); } getPositions( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, PositionData | null>> { return this.fetcher.getAccounts(addresses, ParsablePosition, opts); } getTickArray( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TickArrayData | null> { return this.fetcher.getAccount(address, ParsableTickArray, opts); } getTickArrays( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyArray<TickArrayData | null>> { return this.fetcher.getAccountsAsArray(addresses, ParsableTickArray, opts); } getFeeTier( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<FeeTierData | null> { return this.fetcher.getAccount(address, ParsableFeeTier, opts); } getFeeTiers( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, FeeTierData | null>> { return this.fetcher.getAccounts(addresses, ParsableFeeTier, opts); } getTokenInfo( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenAccountWithTokenProgram | null> { return this.fetcher.getAccount(address, ParsableTokenAccountInfo, opts); } getTokenInfos( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, TokenAccountWithTokenProgram | null>> { return this.fetcher.getAccounts(addresses, ParsableTokenAccountInfo, opts); } getMintInfo( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<MintWithTokenProgram | null> { return this.fetcher.getAccount(address, ParsableMintInfo, opts); } getMintInfos( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, MintWithTokenProgram | null>> { return this.fetcher.getAccounts(addresses, ParsableMintInfo, opts); } getConfig( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolsConfigData | null> { return this.fetcher.getAccount(address, ParsableWhirlpoolsConfig, opts); } getConfigs( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolsConfigData | null>> { return this.fetcher.getAccounts(addresses, ParsableWhirlpoolsConfig, opts); } getPositionBundle( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<PositionBundleData | null> { return this.fetcher.getAccount(address, ParsablePositionBundle, opts); } getPositionBundles( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, PositionBundleData | null>> { return this.fetcher.getAccounts(addresses, ParsablePositionBundle, opts); } getConfigExtension( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<WhirlpoolsConfigExtensionData | null> { return this.fetcher.getAccount( address, ParsableWhirlpoolsConfigExtension, opts, ); } getConfigExtensions( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, WhirlpoolsConfigExtensionData | null>> { return this.fetcher.getAccounts( addresses, ParsableWhirlpoolsConfigExtension, opts, ); } getTokenBadge( address: Address, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenBadgeData | null> { return this.fetcher.getAccount(address, ParsableTokenBadge, opts); } getTokenBadges( addresses: Address[], opts?: WhirlpoolAccountFetchOptions, ): Promise<ReadonlyMap<string, TokenBadgeData | null>> { return this.fetcher.getAccounts(addresses, ParsableTokenBadge, opts); } populateCache<T extends WhirlpoolSupportedTypes>( accounts: ReadonlyMap<string, T>, parser: ParsableEntity<T>, now = Date.now(), ): void { this.fetcher.populateAccounts(accounts, parser, now); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/fetcher/index.ts
export * from "./fetcher-impl"; export * from "./fetcher-types"; export * from "./fetcher-utils";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/network/public/fetcher/fetcher-utils.ts
import type { Address } from "@orca-so/common-sdk"; import { AddressUtil } from "@orca-so/common-sdk"; import type { Connection, PublicKey } from "@solana/web3.js"; import invariant from "tiny-invariant"; import type { PositionBundleData, PositionData, WhirlpoolData, } from "../../../types/public"; import { AccountName, WHIRLPOOL_CODER, getAccountSize, } from "../../../types/public"; import { ParsableWhirlpool } from "../parsing"; import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, unpackAccount, } from "@solana/spl-token"; import { PDAUtil, PositionBundleUtil } from "../../../utils/public"; import { IGNORE_CACHE } from "../../.."; import type { WhirlpoolContext } from "../../.."; /** * Retrieve a list of whirlpool addresses and accounts filtered by the given params using * getProgramAccounts. * @category Network * * @param connection The connection to use to fetch accounts * @param programId The Whirlpool program to search Whirlpool accounts for * @param configId The {@link WhirlpoolConfig} account program address to filter by * @returns tuple of whirlpool addresses and accounts */ export async function getAllWhirlpoolAccountsForConfig({ connection, programId, configId, }: { connection: Connection; programId: Address; configId: Address; }): Promise<ReadonlyMap<string, WhirlpoolData>> { const filters = [ { dataSize: getAccountSize(AccountName.Whirlpool) }, { memcmp: WHIRLPOOL_CODER.memcmp( AccountName.Whirlpool, AddressUtil.toPubKey(configId).toBuffer(), ), }, ]; const accounts = await connection.getProgramAccounts( AddressUtil.toPubKey(programId), { filters, }, ); const parsedAccounts: [string, WhirlpoolData][] = []; accounts.forEach(({ pubkey, account }) => { const parsedAccount = ParsableWhirlpool.parse(pubkey, account); invariant( !!parsedAccount, `could not parse whirlpool: ${pubkey.toBase58()}`, ); parsedAccounts.push([AddressUtil.toString(pubkey), parsedAccount]); }); return new Map( parsedAccounts.map(([address, pool]) => [ AddressUtil.toString(address), pool, ]), ); } export type PositionMap = { positions: ReadonlyMap<string, PositionData>; positionsWithTokenExtensions: ReadonlyMap<string, PositionData>; positionBundles: BundledPositionMap[]; }; export type BundledPositionMap = { positionBundleAddress: Address; positionBundleData: PositionBundleData; bundledPositions: ReadonlyMap<number, PositionData>; }; /** * Retrieve a list of position addresses and accounts filtered by the given params. * @category Network * * @param ctx The whirlpool context * @param owner The owner of the positions * @param includesPositions Whether to fetch positions * @param includesPositionsWithTokenExtensions Whether to fetch positions with token extensions * @param includesBundledPositions Whether to fetch bundled positions * @returns The map of position addresses to position accounts */ export async function getAllPositionAccountsByOwner({ ctx, owner, includesPositions = true, includesPositionsWithTokenExtensions = true, includesBundledPositions = false, }: { ctx: WhirlpoolContext; owner: Address; includesPositions?: boolean; includesPositionsWithTokenExtensions?: boolean; includesBundledPositions?: boolean; }): Promise<PositionMap> { const positions = !includesPositions ? new Map() : await findPositions(ctx, owner, TOKEN_PROGRAM_ID); const positionsWithTokenExtensions = !includesPositionsWithTokenExtensions ? new Map() : await findPositions(ctx, owner, TOKEN_2022_PROGRAM_ID); const positionBundles = !includesBundledPositions ? [] : await findBundledPositions(ctx, owner); return { positions, positionsWithTokenExtensions, positionBundles, }; } async function findPositions( ctx: WhirlpoolContext, owner: Address, tokenProgramId: Address, ): Promise<ReadonlyMap<string, PositionData>> { const programId = AddressUtil.toPubKey(tokenProgramId); const tokenAccounts = await ctx.connection.getTokenAccountsByOwner( AddressUtil.toPubKey(owner), { programId, }, ); // Get candidate addresses for the position const candidatePubkeys: PublicKey[] = []; tokenAccounts.value.forEach((ta) => { const parsed = unpackAccount(ta.pubkey, ta.account, programId); if (parsed.amount === 1n) { const pda = PDAUtil.getPosition(ctx.program.programId, parsed.mint); candidatePubkeys.push(pda.publicKey); } }); // Fetch candidate accounts const positionData = await ctx.fetcher.getPositions( candidatePubkeys, IGNORE_CACHE, ); // Drop null return new Map( Array.from(positionData.entries()).filter(([_, v]) => v !== null) as [ string, PositionData, ][], ); } async function findBundledPositions( ctx: WhirlpoolContext, owner: Address, ): Promise< { positionBundleAddress: Address; positionBundleData: PositionBundleData; bundledPositions: ReadonlyMap<number, PositionData>; }[] > { const tokenAccounts = await ctx.connection.getTokenAccountsByOwner( AddressUtil.toPubKey(owner), { programId: TOKEN_PROGRAM_ID, }, ); // Get candidate addresses for the position bundle const candidatePubkeys: PublicKey[] = []; tokenAccounts.value.forEach((ta) => { const parsed = unpackAccount(ta.pubkey, ta.account, TOKEN_PROGRAM_ID); if (parsed.amount === 1n) { const pda = PDAUtil.getPositionBundle(ctx.program.programId, parsed.mint); candidatePubkeys.push(pda.publicKey); } }); // Fetch candidate accounts const positionBundleData = await ctx.fetcher.getPositionBundles( candidatePubkeys, IGNORE_CACHE, ); // Drop null const positionBundles = Array.from(positionBundleData.entries()).filter( ([_, v]) => v !== null, ) as [string, PositionBundleData][]; const bundledPositionPubkeys: PublicKey[] = []; positionBundles.forEach(([_, positionBundle]) => { const bundleIndexes = PositionBundleUtil.getOccupiedBundleIndexes(positionBundle); bundleIndexes.forEach((bundleIndex) => { const pda = PDAUtil.getBundledPosition( ctx.program.programId, positionBundle.positionBundleMint, bundleIndex, ); bundledPositionPubkeys.push(pda.publicKey); }); }); // Fetch bundled positions const bundledPositionData = await ctx.fetcher.getPositions( bundledPositionPubkeys, IGNORE_CACHE, ); return positionBundles.map(([positionBundleAddress, positionBundleData]) => { const bundleIndexes = PositionBundleUtil.getOccupiedBundleIndexes(positionBundleData); const bundledPositions = new Map( bundleIndexes .map((bundleIndex) => { const pda = PDAUtil.getBundledPosition( ctx.program.programId, positionBundleData.positionBundleMint, bundleIndex, ); return [ bundleIndex, bundledPositionData.get(AddressUtil.toString(pda.publicKey)), ]; }) .filter(([_, v]) => v !== null) as [number, PositionData][], ); return { positionBundleAddress, positionBundleData, bundledPositions, }; }); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/instructions-util.ts
import * as anchor from "@coral-xyz/anchor"; import { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, } from "@solana/spl-token"; import { SystemProgram } from "@solana/web3.js"; import type { OpenPositionParams, OpenPositionWithTokenExtensionsParams, } from "../instructions"; export function openPositionAccounts(params: OpenPositionParams) { const { funder, owner, positionPda, positionMintAddress, positionTokenAccount: positionTokenAccountAddress, whirlpool: whirlpoolKey, } = params; return { funder: funder, owner, position: positionPda.publicKey, positionMint: positionMintAddress, positionTokenAccount: positionTokenAccountAddress, whirlpool: whirlpoolKey, tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, rent: anchor.web3.SYSVAR_RENT_PUBKEY, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, }; } export function openPositionWithTokenExtensionsAccounts( params: OpenPositionWithTokenExtensionsParams, ) { const { funder, owner, positionPda, positionMint, positionTokenAccount, whirlpool: whirlpoolKey, } = params; return { funder: funder, owner, position: positionPda.publicKey, positionMint, positionTokenAccount, whirlpool: whirlpoolKey, token2022Program: TOKEN_2022_PROGRAM_ID, systemProgram: SystemProgram.programId, associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/position-util.ts
import type { BN } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { MathUtil } from "@orca-so/common-sdk"; import { PriceMath } from "./public"; import { getLowerSqrtPriceFromTokenA, getLowerSqrtPriceFromTokenB, getUpperSqrtPriceFromTokenA, getUpperSqrtPriceFromTokenB, } from "./swap-utils"; export enum SwapDirection { AtoB = "Swap A to B", BtoA = "Swap B to A", } export enum AmountSpecified { Input = "Specified input amount", Output = "Specified output amount", } export enum PositionStatus { BelowRange, InRange, AboveRange, } export class PositionUtil { /** * Returns the position status of a given tickCurrentIndex in relation to the tickLowerIndex and tickUpperIndex. * If the tickCurrentIndex is below the range, it returns PositionStatus.BelowRange. * If the tickCurrentIndex is above the range, it returns PositionStatus.AboveRange. * If the tickCurrentIndex is equal to the lower, PositionStatus.InRange is returned. * On the other hand, if the tickCurrentIndex is equal to the upper, PositionStatus.AboveRange is returned. * The relation "PriceMath.tickIndexToSqrtPriceX64(tickCurrentIndex) <= pool's sqrtPrice" is the reason. * * @param tickCurrentIndex - Whirlpool's current tick index. * @param tickLowerIndex - The tick specifying the lower end of the position range. * @param tickUpperIndex - The tick specifying the upper end of the position range. * @returns Position status in the form of PositionStatus enum. */ public static getPositionStatus( tickCurrentIndex: number, tickLowerIndex: number, tickUpperIndex: number, ): PositionStatus { if (tickCurrentIndex < tickLowerIndex) { return PositionStatus.BelowRange; } else if (tickCurrentIndex < tickUpperIndex) { return PositionStatus.InRange; } else { return PositionStatus.AboveRange; } } /** * Returns the position status of a given sqrtPriceX64 in relation to the tickLowerIndex and tickUpperIndex. * If the sqrtPriceX64 is below the range, it returns PositionStatus.BelowRange. * If the sqrtPriceX64 is above the range, it returns PositionStatus.AboveRange. * If the sqrtPriceX64 is equal to the lower or upper, PositionStatus.BelowRange or PositionStatus.AboveRange is returned respectively. * * @param sqrtPriceX64 - X64 representation of the square root of the price. * @param tickLowerIndex - The tick specifying the lower end of the position range. * @param tickUpperIndex - The tick specifying the upper end of the position range. * @returns Position status in the form of PositionStatus enum. */ public static getStrictPositionStatus( sqrtPriceX64: BN, tickLowerIndex: number, tickUpperIndex: number, ): PositionStatus { const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); if (sqrtPriceX64.lte(sqrtPriceLowerX64)) { return PositionStatus.BelowRange; } else if (sqrtPriceX64.gte(sqrtPriceUpperX64)) { return PositionStatus.AboveRange; } else { return PositionStatus.InRange; } } } export function adjustForSlippage( n: BN, { numerator, denominator }: Percentage, adjustUp: boolean, ): BN { if (adjustUp) { return n.mul(denominator.add(numerator)).div(denominator); } else { return n.mul(denominator).div(denominator.add(numerator)); } } export function adjustAmountForSlippage( amountIn: BN, amountOut: BN, { numerator, denominator }: Percentage, amountSpecified: AmountSpecified, ): BN { if (amountSpecified === AmountSpecified.Input) { return amountOut.mul(denominator).div(denominator.add(numerator)); } else { return amountIn.mul(denominator.add(numerator)).div(denominator); } } export function getLiquidityFromTokenA( amount: BN, sqrtPriceLowerX64: BN, sqrtPriceUpperX64: BN, roundUp: boolean, ) { const result = amount .mul(sqrtPriceLowerX64) .mul(sqrtPriceUpperX64) .div(sqrtPriceUpperX64.sub(sqrtPriceLowerX64)); if (roundUp) { return MathUtil.shiftRightRoundUp(result); } else { return result.shrn(64); } } export function getLiquidityFromTokenB( amount: BN, sqrtPriceLowerX64: BN, sqrtPriceUpperX64: BN, roundUp: boolean, ) { const numerator = amount.shln(64); const denominator = sqrtPriceUpperX64.sub(sqrtPriceLowerX64); if (roundUp) { return MathUtil.divRoundUp(numerator, denominator); } else { return numerator.div(denominator); } } export function getAmountFixedDelta( currentSqrtPriceX64: BN, targetSqrtPriceX64: BN, liquidity: BN, amountSpecified: AmountSpecified, swapDirection: SwapDirection, ) { if ( (amountSpecified == AmountSpecified.Input) == (swapDirection == SwapDirection.AtoB) ) { return getTokenAFromLiquidity( liquidity, currentSqrtPriceX64, targetSqrtPriceX64, amountSpecified == AmountSpecified.Input, ); } else { return getTokenBFromLiquidity( liquidity, currentSqrtPriceX64, targetSqrtPriceX64, amountSpecified == AmountSpecified.Input, ); } } export function getAmountUnfixedDelta( currentSqrtPriceX64: BN, targetSqrtPriceX64: BN, liquidity: BN, amountSpecified: AmountSpecified, swapDirection: SwapDirection, ) { if ( (amountSpecified == AmountSpecified.Input) == (swapDirection == SwapDirection.AtoB) ) { return getTokenBFromLiquidity( liquidity, currentSqrtPriceX64, targetSqrtPriceX64, amountSpecified == AmountSpecified.Output, ); } else { return getTokenAFromLiquidity( liquidity, currentSqrtPriceX64, targetSqrtPriceX64, amountSpecified == AmountSpecified.Output, ); } } export function getNextSqrtPrice( sqrtPriceX64: BN, liquidity: BN, amount: BN, amountSpecified: AmountSpecified, swapDirection: SwapDirection, ) { if ( amountSpecified === AmountSpecified.Input && swapDirection === SwapDirection.AtoB ) { return getLowerSqrtPriceFromTokenA(amount, liquidity, sqrtPriceX64); } else if ( amountSpecified === AmountSpecified.Output && swapDirection === SwapDirection.BtoA ) { return getUpperSqrtPriceFromTokenA(amount, liquidity, sqrtPriceX64); } else if ( amountSpecified === AmountSpecified.Input && swapDirection === SwapDirection.BtoA ) { return getUpperSqrtPriceFromTokenB(amount, liquidity, sqrtPriceX64); } else { return getLowerSqrtPriceFromTokenB(amount, liquidity, sqrtPriceX64); } } export function getTokenAFromLiquidity( liquidity: BN, sqrtPrice0X64: BN, sqrtPrice1X64: BN, roundUp: boolean, ) { const [sqrtPriceLowerX64, sqrtPriceUpperX64] = orderSqrtPrice( sqrtPrice0X64, sqrtPrice1X64, ); const numerator = liquidity .mul(sqrtPriceUpperX64.sub(sqrtPriceLowerX64)) .shln(64); const denominator = sqrtPriceUpperX64.mul(sqrtPriceLowerX64); if (roundUp) { return MathUtil.divRoundUp(numerator, denominator); } else { return numerator.div(denominator); } } export function getTokenBFromLiquidity( liquidity: BN, sqrtPrice0X64: BN, sqrtPrice1X64: BN, roundUp: boolean, ) { const [sqrtPriceLowerX64, sqrtPriceUpperX64] = orderSqrtPrice( sqrtPrice0X64, sqrtPrice1X64, ); const result = liquidity.mul(sqrtPriceUpperX64.sub(sqrtPriceLowerX64)); if (roundUp) { return MathUtil.shiftRightRoundUp(result); } else { return result.shrn(64); } } /** Private */ function orderSqrtPrice(sqrtPrice0X64: BN, sqrtPrice1X64: BN): [BN, BN] { if (sqrtPrice0X64.lt(sqrtPrice1X64)) { return [sqrtPrice0X64, sqrtPrice1X64]; } else { return [sqrtPrice1X64, sqrtPrice0X64]; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/remaining-accounts-util.ts
import type { AccountMeta, PublicKey } from "@solana/web3.js"; import invariant from "tiny-invariant"; import { MAX_SUPPLEMENTAL_TICK_ARRAYS } from "../types/public"; export enum RemainingAccountsType { TransferHookA = "transferHookA", TransferHookB = "transferHookB", TransferHookReward = "transferHookReward", TransferHookInput = "transferHookInput", TransferHookIntermediate = "transferHookIntermediate", TransferHookOutput = "transferHookOutput", SupplementalTickArrays = "supplementalTickArrays", SupplementalTickArraysOne = "supplementalTickArraysOne", SupplementalTickArraysTwo = "supplementalTickArraysTwo", } type RemainingAccountsAnchorType = | { transferHookA: object } | { transferHookB: object } | { transferHookReward: object } | { transferHookInput: object } | { transferHookIntermediate: object } | { transferHookOutput: object } | { supplementalTickArrays: object } | { supplementalTickArraysOne: object } | { supplementalTickArraysTwo: object }; export type RemainingAccountsSliceData = { accountsType: RemainingAccountsAnchorType; length: number; }; export type RemainingAccountsInfoData = { slices: RemainingAccountsSliceData[]; }; // Option<RemainingAccountsInfoData> on Rust // null is treated as None in Rust. undefined doesn't work. export type OptionRemainingAccountsInfoData = RemainingAccountsInfoData | null; export class RemainingAccountsBuilder { private remainingAccounts: AccountMeta[] = []; private slices: RemainingAccountsSliceData[] = []; addSlice( accountsType: RemainingAccountsType, accounts?: AccountMeta[], ): this { if (!accounts || accounts.length === 0) return this; this.slices.push({ accountsType: { [accountsType]: {} } as RemainingAccountsAnchorType, length: accounts.length, }); this.remainingAccounts.push(...accounts); return this; } build(): [OptionRemainingAccountsInfoData, AccountMeta[] | undefined] { return this.slices.length === 0 ? [null, undefined] : [{ slices: this.slices }, this.remainingAccounts]; } } export function toSupplementalTickArrayAccountMetas( tickArrayPubkeys: PublicKey[] | undefined, ): AccountMeta[] | undefined { if (!tickArrayPubkeys) return undefined; invariant( tickArrayPubkeys.length <= MAX_SUPPLEMENTAL_TICK_ARRAYS, "Too many supplemental tick arrays provided", ); return tickArrayPubkeys.map((pubkey) => ({ pubkey, isWritable: true, isSigner: false, })); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/whirlpool-ata-utils.ts
import type { Instruction, TransactionBuilder, WrappedSolAccountCreateMethod, } from "@orca-so/common-sdk"; import { TokenUtil, ZERO, resolveOrCreateATAs } from "@orca-so/common-sdk"; import { NATIVE_MINT } from "@solana/spl-token"; import { PublicKey } from "@solana/web3.js"; import type { WhirlpoolContext } from ".."; import { PoolUtil } from ".."; import type { WhirlpoolData } from "../types/public"; import { convertListToMap } from "./txn-utils"; export enum TokenMintTypes { ALL = "ALL", POOL_ONLY = "POOL_ONLY", REWARD_ONLY = "REWARDS_ONLY", } export type WhirlpoolsTokenMints = { mintMap: PublicKey[]; hasNativeMint: boolean; }; /** * Fetch a list of affliated tokens from a list of whirlpools * * SOL tokens does not use the ATA program and therefore not handled. * @param whirlpoolDatas An array of whirlpoolData (from fetcher.listPools) * @param mintTypes The set of mints to collect from these whirlpools * @returns All the whirlpool, reward token mints in the given set of whirlpools */ export function getTokenMintsFromWhirlpools( whirlpoolDatas: (WhirlpoolData | null)[], mintTypes = TokenMintTypes.ALL, ): WhirlpoolsTokenMints { let hasNativeMint = false; const mints = Array.from( whirlpoolDatas.reduce<Set<string>>((accu, whirlpoolData) => { if (whirlpoolData) { if ( mintTypes === TokenMintTypes.ALL || mintTypes === TokenMintTypes.POOL_ONLY ) { const { tokenMintA, tokenMintB } = whirlpoolData; // TODO: Once we move to sync-native for wSOL wrapping, we can simplify and use wSOL ATA instead of a custom token account. if (!TokenUtil.isNativeMint(tokenMintA)) { accu.add(tokenMintA.toBase58()); } else { hasNativeMint = true; } if (!TokenUtil.isNativeMint(tokenMintB)) { accu.add(tokenMintB.toBase58()); } else { hasNativeMint = true; } } if ( mintTypes === TokenMintTypes.ALL || mintTypes === TokenMintTypes.REWARD_ONLY ) { const rewardInfos = whirlpoolData.rewardInfos; rewardInfos.forEach((reward) => { if (TokenUtil.isNativeMint(reward.mint)) { hasNativeMint = true; } if (PoolUtil.isRewardInitialized(reward)) { accu.add(reward.mint.toBase58()); } }); } } return accu; }, new Set<string>()), ).map((mint) => new PublicKey(mint)); return { mintMap: mints, hasNativeMint, }; } /** * Parameters to resolve ATAs for affliated tokens in a list of Whirlpools * * @category Instruction Types * @param mints - The list of mints to generate affliated tokens for. * @param accountExemption - The value from the most recent getMinimumBalanceForRentExemption(). * @param destinationWallet - the wallet to generate ATAs against * @param payer - The payer address that would pay for the creation of ATA addresses */ export type ResolveAtaInstructionParams = { mints: PublicKey[]; accountExemption: number; receiver?: PublicKey; payer?: PublicKey; }; /** * An interface of mapping between tokenMint & ATA & the instruction set to initialize them. * * @category Instruction Types * @param ataTokenAddresses - A record between the token mint & generated ATA addresses * @param resolveAtaIxs - An array of instructions to initialize all uninitialized ATA token accounts for the list above. */ export type ResolvedATAInstructionSet = { ataTokenAddresses: Record<string, PublicKey>; resolveAtaIxs: Instruction[]; }; /** * Build instructions to resolve ATAs (Associated Tokens Addresses) for affliated tokens in a list of Whirlpools. * Affliated tokens are tokens that are part of the trade pair or reward in a Whirlpool. * * @param ctx - WhirlpoolContext object for the current environment. * @param params - ResolveAtaInstructionParams * @returns a ResolvedTokenAddressesIxSet containing the derived ATA addresses & ix set to initialize the accounts. */ export async function resolveAtaForMints( ctx: WhirlpoolContext, params: ResolveAtaInstructionParams, ): Promise<ResolvedATAInstructionSet> { const { mints, receiver, payer, accountExemption } = params; const receiverKey = receiver ?? ctx.wallet.publicKey; const payerKey = payer ?? ctx.wallet.publicKey; const resolvedAtaResults = await resolveOrCreateATAs( ctx.connection, receiverKey, mints.map((tokenMint) => { return { tokenMint }; }), async () => accountExemption, payerKey, undefined, // use default ctx.accountResolverOpts.allowPDAOwnerAddress, ctx.accountResolverOpts.createWrappedSolAccountMethod, ); // Convert the results back into the specified format const { resolveAtaIxs, resolvedAtas } = resolvedAtaResults.reduce<{ resolvedAtas: PublicKey[]; resolveAtaIxs: Instruction[]; }>( (accu, curr) => { const { address, ...ix } = curr; accu.resolvedAtas.push(address); // TODO: common-sdk needs to have an easier way to check for empty instruction if (ix.instructions.length) { accu.resolveAtaIxs.push(ix); } return accu; }, { resolvedAtas: [], resolveAtaIxs: [] }, ); const affliatedTokenAtaMap = convertListToMap( resolvedAtas, mints.map((mint) => mint.toBase58()), ); return { ataTokenAddresses: affliatedTokenAtaMap, resolveAtaIxs, }; } /** * Add native WSOL mint handling to a transaction builder. */ export function addNativeMintHandlingIx( txBuilder: TransactionBuilder, affliatedTokenAtaMap: Record<string, PublicKey>, destinationWallet: PublicKey, accountExemption: number, createAccountMethod: WrappedSolAccountCreateMethod, ) { let { address: wSOLAta, ...resolveWSolIx } = TokenUtil.createWrappedNativeAccountInstruction( destinationWallet, ZERO, accountExemption, undefined, // use default undefined, // use default createAccountMethod, ); affliatedTokenAtaMap[NATIVE_MINT.toBase58()] = wSOLAta; txBuilder.prependInstruction(resolveWSolIx); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/wallet-utils.ts
import type { Wallet } from "@orca-so/common-sdk"; import { PublicKey } from "@solana/web3.js"; /** * Checks if a wallet is connected. * @category Whirlpool Utils * @param wallet The wallet to check. * @returns True if the wallet is connected, false otherwise. */ export function isWalletConnected(wallet: Wallet | null): boolean { return wallet !== null && !wallet.publicKey.equals(PublicKey.default); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/swap-utils.ts
import { MathUtil, ZERO } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import type BN from "bn.js"; import type { TickArrayData, TickData } from "../types/public"; import { MAX_SWAP_TICK_ARRAYS, TICK_ARRAY_SIZE } from "../types/public"; import { PDAUtil, TickUtil } from "./public"; export function getLowerSqrtPriceFromTokenA( amount: BN, liquidity: BN, sqrtPriceX64: BN, ): BN { const numerator = liquidity.mul(sqrtPriceX64).shln(64); const denominator = liquidity.shln(64).add(amount.mul(sqrtPriceX64)); // always round up return MathUtil.divRoundUp(numerator, denominator); } export function getUpperSqrtPriceFromTokenA( amount: BN, liquidity: BN, sqrtPriceX64: BN, ): BN { const numerator = liquidity.mul(sqrtPriceX64).shln(64); const denominator = liquidity.shln(64).sub(amount.mul(sqrtPriceX64)); // always round up return MathUtil.divRoundUp(numerator, denominator); } export function getLowerSqrtPriceFromTokenB( amount: BN, liquidity: BN, sqrtPriceX64: BN, ): BN { // always round down return sqrtPriceX64.sub(MathUtil.divRoundUp(amount.shln(64), liquidity)); } export function getUpperSqrtPriceFromTokenB( amount: BN, liquidity: BN, sqrtPriceX64: BN, ): BN { // always round down (rounding up a negative number) return sqrtPriceX64.add(amount.shln(64).div(liquidity)); } export type TickArrayAddress = { pubkey: PublicKey; startTickIndex: number }; export function getTickArrayPublicKeysWithStartTickIndex( tickCurrentIndex: number, tickSpacing: number, aToB: boolean, programId: PublicKey, whirlpoolAddress: PublicKey, ): TickArrayAddress[] { const shift = aToB ? 0 : tickSpacing; let offset = 0; let tickArrayAddresses: TickArrayAddress[] = []; for (let i = 0; i < MAX_SWAP_TICK_ARRAYS; i++) { let startIndex: number; try { startIndex = TickUtil.getStartTickIndex( tickCurrentIndex + shift, tickSpacing, offset, ); } catch { return tickArrayAddresses; } const pda = PDAUtil.getTickArray(programId, whirlpoolAddress, startIndex); tickArrayAddresses.push({ pubkey: pda.publicKey, startTickIndex: startIndex, }); offset = aToB ? offset - 1 : offset + 1; } return tickArrayAddresses; } export const ZEROED_TICK_DATA: TickData = Object.freeze({ initialized: false, liquidityNet: ZERO, liquidityGross: ZERO, feeGrowthOutsideA: ZERO, feeGrowthOutsideB: ZERO, rewardGrowthsOutside: [ZERO, ZERO, ZERO], }); export const ZEROED_TICKS: TickData[] = Array.from( { length: TICK_ARRAY_SIZE }, () => ZEROED_TICK_DATA, ); export function buildZeroedTickArray( whirlpool: PublicKey, startTickIndex: number, ): TickArrayData { return { startTickIndex, ticks: ZEROED_TICKS, whirlpool, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/constants.ts
export const TOKEN_MINTS = { USDC: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", SOL: "So11111111111111111111111111111111111111112", USDT: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", USDH: "USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX", mSOL: "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So", stSOL: "7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj", };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/spl-token-utils.ts
import { NATIVE_MINT } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; export function isNativeMint(mint: PublicKey) { return mint.equals(NATIVE_MINT); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/txn-utils.ts
import type { Instruction, ResolvedTokenAddressInstruction, TransactionBuilderOptions, } from "@orca-so/common-sdk"; import { MEASUREMENT_BLOCKHASH, TokenUtil, TransactionBuilder, ZERO, defaultTransactionBuilderOptions, } from "@orca-so/common-sdk"; import type { WhirlpoolContext, WhirlpoolContextOpts as WhirlpoolContextOptions, } from ".."; import { NATIVE_MINT } from "@solana/spl-token"; import type { PublicKey } from "@solana/web3.js"; export function convertListToMap<T>( fetchedData: T[], addresses: string[], ): Record<string, T> { const result: Record<string, T> = {}; fetchedData.forEach((data, index) => { if (data) { const addr = addresses[index]; result[addr] = data; } }); return result; } // Filter out null objects in the first array and remove the corresponding objects in the second array export function filterNullObjects<T, K>( firstArray: ReadonlyArray<T | null>, secondArray: ReadonlyArray<K>, ): [Array<T>, Array<K>] { const filteredFirstArray: Array<T> = []; const filteredSecondArray: Array<K> = []; firstArray.forEach((item, idx) => { if (item !== null) { filteredFirstArray.push(item); filteredSecondArray.push(secondArray[idx]); } }); return [filteredFirstArray, filteredSecondArray]; } export async function checkMergedTransactionSizeIsValid( ctx: WhirlpoolContext, builders: TransactionBuilder[], latestBlockhash: Readonly<{ blockhash: string; lastValidBlockHeight: number; }>, ): Promise<boolean> { const merged = new TransactionBuilder( ctx.connection, ctx.wallet, ctx.txBuilderOpts, ); builders.forEach((builder) => merged.addInstruction(builder.compressIx(true)), ); try { await merged.txnSize({ latestBlockhash, }); return true; } catch { return false; } } export function contextOptionsToBuilderOptions( opts: WhirlpoolContextOptions, ): TransactionBuilderOptions | undefined { return { defaultBuildOption: { ...defaultTransactionBuilderOptions.defaultBuildOption, ...opts.userDefaultBuildOptions, }, defaultSendOption: { ...defaultTransactionBuilderOptions.defaultSendOption, ...opts.userDefaultSendOptions, }, defaultConfirmationCommitment: opts.userDefaultConfirmCommitment ?? defaultTransactionBuilderOptions.defaultConfirmationCommitment, }; } export class MultipleTransactionBuilderFactoryWithAccountResolver { private txBuilders: TransactionBuilder[] = []; private pendingTxBuilder: TransactionBuilder | null = null; private touchedMints: Set<string> | null = null; private accountExemption: number | null = null; constructor( private ctx: WhirlpoolContext, private resolvedAtas: Record<string, ResolvedTokenAddressInstruction>, private tokenOwner: PublicKey = ctx.wallet.publicKey, private payer: PublicKey = tokenOwner, ) {} public async addInstructions( generator: (resolve: (mint: string) => PublicKey) => Promise<Instruction[]>, ) { if (this.accountExemption === null) { this.accountExemption = await this.ctx.fetcher.getAccountRentExempt(); } for (let iter = 0; iter < 2; iter++) { if (!this.pendingTxBuilder || !this.touchedMints) { this.pendingTxBuilder = new TransactionBuilder( this.ctx.connection, this.ctx.wallet, this.ctx.txBuilderOpts, ); this.touchedMints = new Set<string>(); this.resolvedAtas[NATIVE_MINT.toBase58()] = TokenUtil.createWrappedNativeAccountInstruction( this.tokenOwner, ZERO, this.accountExemption, this.payer, this.tokenOwner, this.ctx.accountResolverOpts.createWrappedSolAccountMethod, ); } const newTxBuilder = new TransactionBuilder( this.ctx.connection, this.ctx.wallet, this.ctx.txBuilderOpts, ); const resolve = (mint: string): PublicKey => { if (!this.touchedMints!.has(mint)) { newTxBuilder.addInstruction(this.resolvedAtas[mint]); this.touchedMints!.add(mint); } return this.resolvedAtas[mint].address; }; const ixs = await generator(resolve.bind(this)); newTxBuilder.addInstructions(ixs); // Attempt to push the new instructions into the pending builder const mergeable = await checkMergedTransactionSizeIsValid( this.ctx, [this.pendingTxBuilder, newTxBuilder], MEASUREMENT_BLOCKHASH, ); if (mergeable) { this.pendingTxBuilder.addInstruction(newTxBuilder.compressIx(false)); break; } else { if (iter !== 0) { throw new Error(`instruction is too large.`); } this.txBuilders.push(this.pendingTxBuilder); this.pendingTxBuilder = null; this.touchedMints = null; } } } public build(): TransactionBuilder[] { return this.pendingTxBuilder ? [...this.txBuilders, this.pendingTxBuilder] : [...this.txBuilders]; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/math/bit-math.ts
import { BN } from "@coral-xyz/anchor"; import { MathUtil, ONE, TWO, U64_MAX, ZERO } from "@orca-so/common-sdk"; import { MathErrorCode, WhirlpoolsError } from "../../errors/errors"; export class BitMath { static mul(n0: BN, n1: BN, limit: number): BN { const result = n0.mul(n1); if (this.isOverLimit(result, limit)) { throw new WhirlpoolsError( `Mul result higher than u${limit}`, MathErrorCode.MultiplicationOverflow, ); } return result; } static mulDiv(n0: BN, n1: BN, d: BN, limit: number): BN { return this.mulDivRoundUpIf(n0, n1, d, false, limit); } static mulDivRoundUp(n0: BN, n1: BN, d: BN, limit: number): BN { return this.mulDivRoundUpIf(n0, n1, d, true, limit); } static mulDivRoundUpIf( n0: BN, n1: BN, d: BN, roundUp: boolean, limit: number, ): BN { if (d.eq(ZERO)) { throw new WhirlpoolsError( "mulDiv denominator is zero", MathErrorCode.DivideByZero, ); } const p = this.mul(n0, n1, limit); const n = p.div(d); return roundUp && p.mod(d).gt(ZERO) ? n.add(ONE) : n; } static checked_mul_shift_right(n0: BN, n1: BN, limit: number) { return this.checked_mul_shift_right_round_up_if(n0, n1, false, limit); } static checked_mul_shift_right_round_up_if( n0: BN, n1: BN, roundUp: boolean, limit: number, ) { // customized this function is used in tryGetAmountDeltaB (token-math.ts) if (n0.eq(ZERO) || n1.eq(ZERO)) { return ZERO; } const p = this.mul(n0, n1, limit); if (this.isOverLimit(p, limit)) { throw new WhirlpoolsError( `MulShiftRight overflowed u${limit}.`, MathErrorCode.MultiplicationShiftRightOverflow, ); } const result = MathUtil.fromX64_BN(p); const shouldRound = roundUp && p.and(U64_MAX).gt(ZERO); if (shouldRound && result.eq(U64_MAX)) { throw new WhirlpoolsError( `MulShiftRight overflowed u${limit}.`, MathErrorCode.MultiplicationOverflow, ); } return shouldRound ? result.add(ONE) : result; } static isOverLimit(n0: BN, limit: number) { const limitBN = TWO.pow(new BN(limit)).sub(ONE); return n0.gt(limitBN); } static divRoundUp(n: BN, d: BN) { return this.divRoundUpIf(n, d, true); } static divRoundUpIf(n: BN, d: BN, roundUp: boolean) { if (d.eq(ZERO)) { throw new WhirlpoolsError( "divRoundUpIf - divide by zero", MathErrorCode.DivideByZero, ); } let q = n.div(d); return roundUp && n.mod(d).gt(ZERO) ? q.add(ONE) : q; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/math/token-math.ts
import type { Percentage } from "@orca-so/common-sdk"; import { MathUtil, ONE, U64_MAX, ZERO } from "@orca-so/common-sdk"; import BN from "bn.js"; import { MathErrorCode, TokenErrorCode, WhirlpoolsError, } from "../../errors/errors"; import { MAX_SQRT_PRICE, MIN_SQRT_PRICE } from "../../types/public"; import { BitMath } from "./bit-math"; import invariant from "tiny-invariant"; type AmountDeltaU64Valid = { type: "Valid"; value: BN; }; type AmountDeltaU64ExceedsMax = { type: "ExceedsMax"; error: Error; }; export class AmountDeltaU64 { constructor(private inner: AmountDeltaU64Valid | AmountDeltaU64ExceedsMax) {} public static fromValid(value: BN): AmountDeltaU64 { return new AmountDeltaU64({ type: "Valid", value, }); } public static fromExceedsMax(error: Error): AmountDeltaU64 { return new AmountDeltaU64({ type: "ExceedsMax", error, }); } public lte(other: BN): boolean { if (this.inner.type === "ExceedsMax") { return false; } return this.inner.value.lte(other); } public exceedsMax(): boolean { return this.inner.type === "ExceedsMax"; } public value(): BN { invariant(this.inner.type === "Valid", "Expected valid AmountDeltaU64"); return this.inner.value; } public unwrap(): BN { if (this.inner.type === "Valid") { return this.inner.value; } else { throw this.inner.error; } } } export function getAmountDeltaA( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, roundUp: boolean, ): BN { return tryGetAmountDeltaA( currSqrtPrice, targetSqrtPrice, currLiquidity, roundUp, ).unwrap(); } export function tryGetAmountDeltaA( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, roundUp: boolean, ): AmountDeltaU64 { let [sqrtPriceLower, sqrtPriceUpper] = toIncreasingPriceOrder( currSqrtPrice, targetSqrtPrice, ); let sqrtPriceDiff = sqrtPriceUpper.sub(sqrtPriceLower); let numerator = currLiquidity.mul(sqrtPriceDiff).shln(64); let denominator = sqrtPriceLower.mul(sqrtPriceUpper); let quotient = numerator.div(denominator); let remainder = numerator.mod(denominator); let result = roundUp && !remainder.eq(ZERO) ? quotient.add(new BN(1)) : quotient; if (result.gt(U64_MAX)) { return AmountDeltaU64.fromExceedsMax( new WhirlpoolsError( "Results larger than U64", TokenErrorCode.TokenMaxExceeded, ), ); } return AmountDeltaU64.fromValid(result); } export function getAmountDeltaB( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, roundUp: boolean, ): BN { return tryGetAmountDeltaB( currSqrtPrice, targetSqrtPrice, currLiquidity, roundUp, ).unwrap(); } export function tryGetAmountDeltaB( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, roundUp: boolean, ): AmountDeltaU64 { let [sqrtPriceLower, sqrtPriceUpper] = toIncreasingPriceOrder( currSqrtPrice, targetSqrtPrice, ); // customized BitMath.checked_mul_shift_right_round_up_if const n0 = currLiquidity; const n1 = sqrtPriceUpper.sub(sqrtPriceLower); const limit = 128; if (n0.eq(ZERO) || n1.eq(ZERO)) { return AmountDeltaU64.fromValid(ZERO); } // we need to use limit * 2 (u256) here to prevent overflow error IN BitMath.mul. // we check the overflow in the next step and return wrapped error if it happens. const p = BitMath.mul(n0, n1, limit * 2); if (BitMath.isOverLimit(p, limit)) { return AmountDeltaU64.fromExceedsMax( new WhirlpoolsError( `MulShiftRight overflowed u${limit}.`, MathErrorCode.MultiplicationShiftRightOverflow, ), ); } const result = MathUtil.fromX64_BN(p); const shouldRound = roundUp && p.and(U64_MAX).gt(ZERO); if (shouldRound && result.eq(U64_MAX)) { return AmountDeltaU64.fromExceedsMax( new WhirlpoolsError( `MulShiftRight overflowed u${limit}.`, MathErrorCode.MultiplicationOverflow, ), ); } return AmountDeltaU64.fromValid(shouldRound ? result.add(ONE) : result); } export function getNextSqrtPrice( sqrtPrice: BN, currLiquidity: BN, amount: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ) { if (amountSpecifiedIsInput === aToB) { return getNextSqrtPriceFromARoundUp( sqrtPrice, currLiquidity, amount, amountSpecifiedIsInput, ); } else { return getNextSqrtPriceFromBRoundDown( sqrtPrice, currLiquidity, amount, amountSpecifiedIsInput, ); } } export function adjustForSlippage( n: BN, { numerator, denominator }: Percentage, adjustUp: boolean, ): BN { if (adjustUp) { return n.mul(denominator.add(numerator)).div(denominator); } else { return n.mul(denominator).div(denominator.add(numerator)); } } function toIncreasingPriceOrder(sqrtPrice0: BN, sqrtPrice1: BN) { if (sqrtPrice0.gt(sqrtPrice1)) { return [sqrtPrice1, sqrtPrice0]; } else { return [sqrtPrice0, sqrtPrice1]; } } function getNextSqrtPriceFromARoundUp( sqrtPrice: BN, currLiquidity: BN, amount: BN, amountSpecifiedIsInput: boolean, ) { if (amount.eq(ZERO)) { return sqrtPrice; } let p = BitMath.mul(sqrtPrice, amount, 256); let numerator = BitMath.mul(currLiquidity, sqrtPrice, 256).shln(64); if (BitMath.isOverLimit(numerator, 256)) { throw new WhirlpoolsError( "getNextSqrtPriceFromARoundUp - numerator overflow u256", MathErrorCode.MultiplicationOverflow, ); } let currLiquidityShiftLeft = currLiquidity.shln(64); if (!amountSpecifiedIsInput && currLiquidityShiftLeft.lte(p)) { throw new WhirlpoolsError( "getNextSqrtPriceFromARoundUp - Unable to divide currLiquidityX64 by product", MathErrorCode.DivideByZero, ); } let denominator = amountSpecifiedIsInput ? currLiquidityShiftLeft.add(p) : currLiquidityShiftLeft.sub(p); let price = BitMath.divRoundUp(numerator, denominator); if (price.lt(new BN(MIN_SQRT_PRICE))) { throw new WhirlpoolsError( "getNextSqrtPriceFromARoundUp - price less than min sqrt price", TokenErrorCode.TokenMinSubceeded, ); } else if (price.gt(new BN(MAX_SQRT_PRICE))) { throw new WhirlpoolsError( "getNextSqrtPriceFromARoundUp - price less than max sqrt price", TokenErrorCode.TokenMaxExceeded, ); } return price; } function getNextSqrtPriceFromBRoundDown( sqrtPrice: BN, currLiquidity: BN, amount: BN, amountSpecifiedIsInput: boolean, ) { let amountX64 = amount.shln(64); let delta = BitMath.divRoundUpIf( amountX64, currLiquidity, !amountSpecifiedIsInput, ); if (amountSpecifiedIsInput) { sqrtPrice = sqrtPrice.add(delta); } else { sqrtPrice = sqrtPrice.sub(delta); } return sqrtPrice; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/math/constants.ts
import { ONE, U64_MAX } from "@orca-so/common-sdk"; export const U64 = U64_MAX.add(ONE);
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/math/k-smallest-partition.ts
const RECURSION_BREAKPOINT = 600; /** * Implementation of Floyd-Rivest selection * https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm * * Performs an in place partition of an array of items, such that * indices [0, k) contain the k smallest elements and all indices * [k, array.length) are larger than all elements in [0, k) * * @param array * @param k * @param left * @param right * @param compare */ export function kSmallestPartition<T>( array: T[], k: number, left: number = 0, right: number = array.length - 1, compare: (a: T, b: T) => number = defaultCompare, ) { while (right > left) { // Recursive sampling and partition of the set if (right - left > RECURSION_BREAKPOINT) { const n = right - left + 1; const i = k - left + 1; const z = Math.log(n); const s = 0.5 * Math.exp((2 * z) / 3); const sd = 0.5 * Math.sqrt((z * s * (n - s)) / n) * (i - n / 2 < 0 ? -1 : 1); const newLeft = Math.max(left, Math.floor(k - (i * s) / n + sd)); const newRight = Math.min(right, Math.floor(k + ((n - i) * s) / n + sd)); kSmallestPartition(array, k, newLeft, newRight, compare); } // Partition elements around t const t = array[k]; let i = left; let j = right; swap(array, left, k); if (compare(array[right], t) > 0) { swap(array, left, right); } while (i < j) { swap(array, i, j); i++; j--; while (compare(array[i], t) < 0) { i++; } while (compare(array[j], t) > 0) { j--; } } if (compare(array[left], t) === 0) { swap(array, left, j); } else { j++; swap(array, j, right); } // Adjust boundaries of partitions if (j <= k) { left = j + 1; } if (k <= j) { right = j - 1; } } } function swap<T>(arr: T[], i: number, j: number) { const tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } function defaultCompare<T>(a: T, b: T) { return a < b ? -1 : a > b ? 1 : 0; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/math/swap-math.ts
import BN from "bn.js"; import { FEE_RATE_MUL_VALUE } from "../../types/public"; import { BitMath } from "./bit-math"; import { getAmountDeltaA, getAmountDeltaB, getNextSqrtPrice, tryGetAmountDeltaA, tryGetAmountDeltaB, } from "./token-math"; export type SwapStep = { amountIn: BN; amountOut: BN; nextPrice: BN; feeAmount: BN; }; export function computeSwapStep( amountRemaining: BN, feeRate: number, currLiquidity: BN, currSqrtPrice: BN, targetSqrtPrice: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ): SwapStep { let initialAmountFixedDelta = tryGetAmountFixedDelta( currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput, aToB, ); let amountCalc = amountRemaining; if (amountSpecifiedIsInput) { const result = BitMath.mulDiv( amountRemaining, FEE_RATE_MUL_VALUE.sub(new BN(feeRate)), FEE_RATE_MUL_VALUE, 128, ); amountCalc = result; } let nextSqrtPrice = initialAmountFixedDelta.lte(amountCalc) ? targetSqrtPrice : getNextSqrtPrice( currSqrtPrice, currLiquidity, amountCalc, amountSpecifiedIsInput, aToB, ); let isMaxSwap = nextSqrtPrice.eq(targetSqrtPrice); let amountUnfixedDelta = getAmountUnfixedDelta( currSqrtPrice, nextSqrtPrice, currLiquidity, amountSpecifiedIsInput, aToB, ); let amountFixedDelta = !isMaxSwap || initialAmountFixedDelta.exceedsMax() ? getAmountFixedDelta( currSqrtPrice, nextSqrtPrice, currLiquidity, amountSpecifiedIsInput, aToB, ) : initialAmountFixedDelta.value(); let amountIn = amountSpecifiedIsInput ? amountFixedDelta : amountUnfixedDelta; let amountOut = amountSpecifiedIsInput ? amountUnfixedDelta : amountFixedDelta; if (!amountSpecifiedIsInput && amountOut.gt(amountRemaining)) { amountOut = amountRemaining; } let feeAmount: BN; if (amountSpecifiedIsInput && !isMaxSwap) { feeAmount = amountRemaining.sub(amountIn); } else { const feeRateBN = new BN(feeRate); feeAmount = BitMath.mulDivRoundUp( amountIn, feeRateBN, FEE_RATE_MUL_VALUE.sub(feeRateBN), 128, ); } return { amountIn, amountOut, nextPrice: nextSqrtPrice, feeAmount, }; } function getAmountFixedDelta( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ) { if (aToB === amountSpecifiedIsInput) { return getAmountDeltaA( currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput, ); } else { return getAmountDeltaB( currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput, ); } } function tryGetAmountFixedDelta( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ) { if (aToB === amountSpecifiedIsInput) { return tryGetAmountDeltaA( currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput, ); } else { return tryGetAmountDeltaB( currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput, ); } } function getAmountUnfixedDelta( currSqrtPrice: BN, targetSqrtPrice: BN, currLiquidity: BN, amountSpecifiedIsInput: boolean, aToB: boolean, ) { if (aToB === amountSpecifiedIsInput) { return getAmountDeltaB( currSqrtPrice, targetSqrtPrice, currLiquidity, !amountSpecifiedIsInput, ); } else { return getAmountDeltaA( currSqrtPrice, targetSqrtPrice, currLiquidity, !amountSpecifiedIsInput, ); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/tick-utils.ts
import type { Address } from "@coral-xyz/anchor"; import type { PDA } from "@orca-so/common-sdk"; import { AddressUtil } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import invariant from "tiny-invariant"; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, } from "../../network/public/fetcher"; import type { TickArrayData, TickData } from "../../types/public"; import { FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD, MAX_TICK_INDEX, MIN_TICK_INDEX, TICK_ARRAY_SIZE, } from "../../types/public"; import { PDAUtil } from "./pda-utils"; enum TickSearchDirection { Left, Right, } /** * A collection of utility functions when interacting with Ticks. * @category Whirlpool Utils */ export class TickUtil { /** * Get the offset index to access a tick at a given tick-index in a tick-array * * @param tickIndex The tick index for the tick that this offset would access * @param arrayStartIndex The starting tick for the array that this tick-index resides in * @param tickSpacing The tickSpacing for the Whirlpool that this tickArray belongs to * @returns The offset index that can access the desired tick at the given tick-array */ public static getOffsetIndex( tickIndex: number, arrayStartIndex: number, tickSpacing: number, ) { return Math.floor((tickIndex - arrayStartIndex) / tickSpacing); } /** * Get the startIndex of the tick array containing tickIndex. * * @param tickIndex * @param tickSpacing * @param offset can be used to get neighboring tick array startIndex. * @returns */ public static getStartTickIndex( tickIndex: number, tickSpacing: number, offset = 0, ): number { const realIndex = Math.floor(tickIndex / tickSpacing / TICK_ARRAY_SIZE); const startTickIndex = (realIndex + offset) * tickSpacing * TICK_ARRAY_SIZE; const ticksInArray = TICK_ARRAY_SIZE * tickSpacing; const minTickIndex = MIN_TICK_INDEX - ((MIN_TICK_INDEX % ticksInArray) + ticksInArray); invariant( startTickIndex >= minTickIndex, `startTickIndex is too small - - ${startTickIndex}`, ); invariant( startTickIndex <= MAX_TICK_INDEX, `startTickIndex is too large - ${startTickIndex}`, ); return startTickIndex; } /** * Get the nearest (rounding down) valid tick index from the tickIndex. * A valid tick index is a point on the tick spacing grid line. */ public static getInitializableTickIndex( tickIndex: number, tickSpacing: number, ): number { return tickIndex - (tickIndex % tickSpacing); } public static getNextInitializableTickIndex( tickIndex: number, tickSpacing: number, ) { return ( TickUtil.getInitializableTickIndex(tickIndex, tickSpacing) + tickSpacing ); } public static getPrevInitializableTickIndex( tickIndex: number, tickSpacing: number, ) { return ( TickUtil.getInitializableTickIndex(tickIndex, tickSpacing) - tickSpacing ); } /** * Get the previous initialized tick index within the same tick array. * * @param account * @param currentTickIndex * @param tickSpacing * @returns */ public static findPreviousInitializedTickIndex( account: TickArrayData, currentTickIndex: number, tickSpacing: number, ): number | null { return TickUtil.findInitializedTick( account, currentTickIndex, tickSpacing, TickSearchDirection.Left, ); } /** * Get the next initialized tick index within the same tick array. * @param account * @param currentTickIndex * @param tickSpacing * @returns */ public static findNextInitializedTickIndex( account: TickArrayData, currentTickIndex: number, tickSpacing: number, ): number | null { return TickUtil.findInitializedTick( account, currentTickIndex, tickSpacing, TickSearchDirection.Right, ); } private static findInitializedTick( account: TickArrayData, currentTickIndex: number, tickSpacing: number, searchDirection: TickSearchDirection, ): number | null { const currentTickArrayIndex = tickIndexToInnerIndex( account.startTickIndex, currentTickIndex, tickSpacing, ); const increment = searchDirection === TickSearchDirection.Right ? 1 : -1; let stepInitializedTickArrayIndex = searchDirection === TickSearchDirection.Right ? currentTickArrayIndex + increment : currentTickArrayIndex; while ( stepInitializedTickArrayIndex >= 0 && stepInitializedTickArrayIndex < account.ticks.length ) { if (account.ticks[stepInitializedTickArrayIndex]?.initialized) { return innerIndexToTickIndex( account.startTickIndex, stepInitializedTickArrayIndex, tickSpacing, ); } stepInitializedTickArrayIndex += increment; } return null; } public static checkTickInBounds(tick: number) { return tick <= MAX_TICK_INDEX && tick >= MIN_TICK_INDEX; } public static isTickInitializable(tick: number, tickSpacing: number) { return tick % tickSpacing === 0; } /** * * Returns the tick for the inverse of the price that this tick represents. * Eg: Consider tick i where Pb/Pa = 1.0001 ^ i * inverse of this, i.e. Pa/Pb = 1 / (1.0001 ^ i) = 1.0001^-i * @param tick The tick to invert * @returns */ public static invertTick(tick: number) { return -tick; } /** * Get the minimum and maximum tick index that can be initialized. * * @param tickSpacing The tickSpacing for the Whirlpool * @returns An array of numbers where the first element is the minimum tick index and the second element is the maximum tick index. */ public static getFullRangeTickIndex(tickSpacing: number): [number, number] { return [ Math.ceil(MIN_TICK_INDEX / tickSpacing) * tickSpacing, Math.floor(MAX_TICK_INDEX / tickSpacing) * tickSpacing, ]; } /** * Check if the tick range is the full range of the Whirlpool. * @param tickSpacing The tickSpacing for the Whirlpool * @param tickLowerIndex The lower tick index of the range * @param tickUpperIndex The upper tick index of the range * @returns true if the range is the full range of the Whirlpool, false otherwise. */ public static isFullRange( tickSpacing: number, tickLowerIndex: number, tickUpperIndex: number, ): boolean { const [min, max] = TickUtil.getFullRangeTickIndex(tickSpacing); return tickLowerIndex === min && tickUpperIndex === max; } /** * Check if a whirlpool is a full-range only pool. * @param tickSpacing The tickSpacing for the Whirlpool * @returns true if the whirlpool is a full-range only pool, false otherwise. */ public static isFullRangeOnly(tickSpacing: number): boolean { return tickSpacing >= FULL_RANGE_ONLY_TICK_SPACING_THRESHOLD; } } /** * A collection of utility functions when interacting with a TickArray. * @category Whirlpool Utils */ export class TickArrayUtil { /** * Get the tick from tickArray with a global tickIndex. */ public static getTickFromArray( tickArray: TickArrayData, tickIndex: number, tickSpacing: number, ): TickData { const realIndex = tickIndexToInnerIndex( tickArray.startTickIndex, tickIndex, tickSpacing, ); const tick = tickArray.ticks[realIndex]; invariant( !!tick, `tick realIndex out of range - start - ${tickArray.startTickIndex} index - ${tickIndex}, realIndex - ${realIndex}`, ); return tick; } /** * Return a sequence of tick array pdas based on the sequence start index. * @param tick - A tick in the first tick-array of your sequence * @param tickSpacing - Tick spacing for the whirlpool * @param numOfTickArrays - The number of TickArray PDAs to generate * @param programId - Program Id of the whirlpool for these tick-arrays * @param whirlpoolAddress - Address for the Whirlpool for these tick-arrays * @returns TickArray PDAs for the sequence` */ public static getTickArrayPDAs( tick: number, tickSpacing: number, numOfTickArrays: number, programId: PublicKey, whirlpoolAddress: PublicKey, aToB: boolean, ): PDA[] { let arrayIndexList = [...Array(numOfTickArrays).keys()]; if (aToB) { arrayIndexList = arrayIndexList.map((value) => -value); } return arrayIndexList.map((value) => { const startTick = TickUtil.getStartTickIndex(tick, tickSpacing, value); return PDAUtil.getTickArray(programId, whirlpoolAddress, startTick); }); } /** * Return a string containing all of the uninitialized arrays in the provided addresses. * Useful for creating error messages. * * @param tickArrayAddrs - A list of tick-array addresses to verify. * @param cache - {@link WhirlpoolAccountFetcherInterface} * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A string of all uninitialized tick array addresses, delimited by ",". Falsy value if all arrays are initialized. */ public static async getUninitializedArraysString( tickArrayAddrs: Address[], fetcher: WhirlpoolAccountFetcherInterface, opts?: WhirlpoolAccountFetchOptions, ) { const taAddrs = AddressUtil.toPubKeys(tickArrayAddrs); const tickArrayData = await fetcher.getTickArrays(taAddrs, opts); // Verify tick arrays are initialized if the user provided them. if (tickArrayData) { const uninitializedIndices = TickArrayUtil.getUninitializedArrays(tickArrayData); if (uninitializedIndices.length > 0) { const uninitializedArrays = uninitializedIndices .map((index) => taAddrs[index].toBase58()) .join(", "); return uninitializedArrays; } } return null; } public static async getUninitializedArraysPDAs( ticks: number[], programId: PublicKey, whirlpoolAddress: PublicKey, tickSpacing: number, fetcher: WhirlpoolAccountFetcherInterface, opts: WhirlpoolAccountFetchOptions, ) { const startTicks = ticks.map((tick) => TickUtil.getStartTickIndex(tick, tickSpacing), ); const removeDupeTicks = [...new Set(startTicks)]; const tickArrayPDAs = removeDupeTicks.map((tick) => PDAUtil.getTickArray(programId, whirlpoolAddress, tick), ); const fetchedArrays = await fetcher.getTickArrays( tickArrayPDAs.map((pda) => pda.publicKey), opts, ); const uninitializedIndices = TickArrayUtil.getUninitializedArrays(fetchedArrays); return uninitializedIndices.map((index) => { return { startIndex: removeDupeTicks[index], pda: tickArrayPDAs[index], }; }); } /** * Evaluate a list of tick-array data and return the array of indices which the tick-arrays are not initialized. * @param tickArrays - a list of TickArrayData or null objects from WhirlpoolAccountCacheInterface.getTickArrays * @returns an array of array-index for the input tickArrays that requires initialization. */ public static getUninitializedArrays( tickArrays: readonly (TickArrayData | null)[], ): number[] { return tickArrays .map((value, index) => { if (!value) { return index; } return -1; }) .filter((index) => index >= 0); } } function tickIndexToInnerIndex( startTickIndex: number, tickIndex: number, tickSpacing: number, ): number { return Math.floor((tickIndex - startTickIndex) / tickSpacing); } function innerIndexToTickIndex( startTickIndex: number, tickArrayIndex: number, tickSpacing: number, ): number { return startTickIndex + tickArrayIndex * tickSpacing; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/pda-utils.ts
import { BN } from "@coral-xyz/anchor"; import { AddressUtil } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import { METADATA_PROGRAM_ADDRESS } from "../../types/public"; import { PriceMath } from "./price-math"; import { TickUtil } from "./tick-utils"; const PDA_WHIRLPOOL_SEED = "whirlpool"; const PDA_POSITION_SEED = "position"; const PDA_METADATA_SEED = "metadata"; const PDA_TICK_ARRAY_SEED = "tick_array"; const PDA_FEE_TIER_SEED = "fee_tier"; const PDA_ORACLE_SEED = "oracle"; const PDA_POSITION_BUNDLE_SEED = "position_bundle"; const PDA_BUNDLED_POSITION_SEED = "bundled_position"; const PDA_CONFIG_EXTENSION_SEED = "config_extension"; const PDA_TOKEN_BADGE_SEED = "token_badge"; /** * @category Whirlpool Utils */ export class PDAUtil { /** * * @param programId * @param whirlpoolsConfigKey * @param tokenMintAKey * @param tokenMintBKey * @param tickSpacing * @returns */ public static getWhirlpool( programId: PublicKey, whirlpoolsConfigKey: PublicKey, tokenMintAKey: PublicKey, tokenMintBKey: PublicKey, tickSpacing: number, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_WHIRLPOOL_SEED), whirlpoolsConfigKey.toBuffer(), tokenMintAKey.toBuffer(), tokenMintBKey.toBuffer(), new BN(tickSpacing).toArrayLike(Buffer, "le", 2), ], programId, ); } /** * @category Program Derived Addresses * @param programId * @param positionMintKey * @returns */ public static getPosition(programId: PublicKey, positionMintKey: PublicKey) { return AddressUtil.findProgramAddress( [Buffer.from(PDA_POSITION_SEED), positionMintKey.toBuffer()], programId, ); } /** * @category Program Derived Addresses * @param positionMintKey * @returns */ public static getPositionMetadata(positionMintKey: PublicKey) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_METADATA_SEED), METADATA_PROGRAM_ADDRESS.toBuffer(), positionMintKey.toBuffer(), ], METADATA_PROGRAM_ADDRESS, ); } /** * @category Program Derived Addresses * @param programId * @param whirlpoolAddress * @param startTick * @returns */ public static getTickArray( programId: PublicKey, whirlpoolAddress: PublicKey, startTick: number, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_TICK_ARRAY_SEED), whirlpoolAddress.toBuffer(), Buffer.from(startTick.toString()), ], programId, ); } /** * Get the PDA of the tick array containing tickIndex. * tickArrayOffset can be used to get neighboring tick arrays. * * @param tickIndex * @param tickSpacing * @param whirlpool * @param programId * @param tickArrayOffset * @returns */ public static getTickArrayFromTickIndex( tickIndex: number, tickSpacing: number, whirlpool: PublicKey, programId: PublicKey, tickArrayOffset = 0, ) { const startIndex = TickUtil.getStartTickIndex( tickIndex, tickSpacing, tickArrayOffset, ); return PDAUtil.getTickArray( AddressUtil.toPubKey(programId), AddressUtil.toPubKey(whirlpool), startIndex, ); } public static getTickArrayFromSqrtPrice( sqrtPriceX64: BN, tickSpacing: number, whirlpool: PublicKey, programId: PublicKey, tickArrayOffset = 0, ) { const tickIndex = PriceMath.sqrtPriceX64ToTickIndex(sqrtPriceX64); return PDAUtil.getTickArrayFromTickIndex( tickIndex, tickSpacing, whirlpool, programId, tickArrayOffset, ); } /** * @category Program Derived Addresses * @param programId * @param whirlpoolsConfigAddress * @param tickSpacing * @returns */ public static getFeeTier( programId: PublicKey, whirlpoolsConfigAddress: PublicKey, tickSpacing: number, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_FEE_TIER_SEED), whirlpoolsConfigAddress.toBuffer(), new BN(tickSpacing).toArrayLike(Buffer, "le", 2), ], programId, ); } /** * @category Program Derived Addresses * @param programId * @param whirlpoolAddress * @returns */ public static getOracle(programId: PublicKey, whirlpoolAddress: PublicKey) { return AddressUtil.findProgramAddress( [Buffer.from(PDA_ORACLE_SEED), whirlpoolAddress.toBuffer()], programId, ); } /** * @category Program Derived Addresses * @param programId * @param positionBundleMintKey * @param bundleIndex * @returns */ public static getBundledPosition( programId: PublicKey, positionBundleMintKey: PublicKey, bundleIndex: number, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_BUNDLED_POSITION_SEED), positionBundleMintKey.toBuffer(), Buffer.from(bundleIndex.toString()), ], programId, ); } /** * @category Program Derived Addresses * @param programId * @param positionBundleMintKey * @returns */ public static getPositionBundle( programId: PublicKey, positionBundleMintKey: PublicKey, ) { return AddressUtil.findProgramAddress( [Buffer.from(PDA_POSITION_BUNDLE_SEED), positionBundleMintKey.toBuffer()], programId, ); } /** * @category Program Derived Addresses * @param positionBundleMintKey * @returns */ public static getPositionBundleMetadata(positionBundleMintKey: PublicKey) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_METADATA_SEED), METADATA_PROGRAM_ADDRESS.toBuffer(), positionBundleMintKey.toBuffer(), ], METADATA_PROGRAM_ADDRESS, ); } /** * @category Program Derived Addresses * @param programId * @param whirlpoolsConfigAddress * @returns */ public static getConfigExtension( programId: PublicKey, whirlpoolsConfigAddress: PublicKey, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_CONFIG_EXTENSION_SEED), whirlpoolsConfigAddress.toBuffer(), ], programId, ); } /** * @category Program Derived Addresses * @param programId * @param whirlpoolsConfigAddress * @param tokenMintKey * @returns */ public static getTokenBadge( programId: PublicKey, whirlpoolsConfigAddress: PublicKey, tokenMintKey: PublicKey, ) { return AddressUtil.findProgramAddress( [ Buffer.from(PDA_TOKEN_BADGE_SEED), whirlpoolsConfigAddress.toBuffer(), tokenMintKey.toBuffer(), ], programId, ); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/ix-utils.ts
import type { Instruction } from "@orca-so/common-sdk"; import { TransactionBuilder } from "@orca-so/common-sdk"; import type { WhirlpoolContext } from "../../context"; export function toTx( ctx: WhirlpoolContext, ix: Instruction, ): TransactionBuilder { return new TransactionBuilder( ctx.provider.connection, ctx.provider.wallet, ctx.txBuilderOpts, ).addInstruction(ix); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/pool-utils.ts
import type { Address } from "@coral-xyz/anchor"; import { AddressUtil, MathUtil, Percentage } from "@orca-so/common-sdk"; import { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; import Decimal from "decimal.js"; import type { WhirlpoolData, WhirlpoolRewardInfoData, } from "../../types/public"; import { TOKEN_MINTS } from "../constants"; import { PriceMath } from "./price-math"; import { TokenType } from "./types"; import type { WhirlpoolContext } from "../.."; import { PDAUtil } from "../.."; import invariant from "tiny-invariant"; import { AccountState, ExtensionType, NATIVE_MINT_2022, TOKEN_PROGRAM_ID, getDefaultAccountState, getExtensionTypes, } from "@solana/spl-token"; /** * @category Whirlpool Utils */ export class PoolUtil { public static isRewardInitialized( rewardInfo: WhirlpoolRewardInfoData, ): boolean { return ( !PublicKey.default.equals(rewardInfo.mint) && !PublicKey.default.equals(rewardInfo.vault) ); } /** * Return the corresponding token type (TokenA/B) for this mint key for a Whirlpool. * * @param pool The Whirlpool to evaluate the mint against * @param mint The token mint PublicKey * @returns The match result in the form of TokenType enum. undefined if the token mint is not part of the trade pair of the pool. */ public static getTokenType( pool: WhirlpoolData, mint: PublicKey, ): TokenType | undefined { if (pool.tokenMintA.equals(mint)) { return TokenType.TokenA; } else if (pool.tokenMintB.equals(mint)) { return TokenType.TokenB; } return undefined; } public static getFeeRate(feeRate: number): Percentage { /** * Smart Contract comment: https://github.com/orca-so/whirlpool/blob/main/programs/whirlpool/src/state/whirlpool.rs#L9-L11 * // Stored as hundredths of a basis point * // u16::MAX corresponds to ~6.5% * pub fee_rate: u16, */ return Percentage.fromFraction(feeRate, 1e6); // TODO } public static getProtocolFeeRate(protocolFeeRate: number): Percentage { /** * Smart Contract comment: https://github.com/orca-so/whirlpool/blob/main/programs/whirlpool/src/state/whirlpool.rs#L13-L14 * // Stored as a basis point * pub protocol_fee_rate: u16, */ return Percentage.fromFraction(protocolFeeRate, 1e4); // TODO } public static orderMints(mintX: Address, mintY: Address): [Address, Address] { return this.compareMints(mintX, mintY) < 0 ? [mintX, mintY] : [mintY, mintX]; } public static compareMints(mintX: Address, mintY: Address): number { return Buffer.compare( AddressUtil.toPubKey(mintX).toBuffer(), AddressUtil.toPubKey(mintY).toBuffer(), ); } /** * @category Whirlpool Utils * @param liquidity * @param currentSqrtPrice * @param lowerSqrtPrice * @param upperSqrtPrice * @param round_up * @returns */ public static getTokenAmountsFromLiquidity( liquidity: BN, currentSqrtPrice: BN, lowerSqrtPrice: BN, upperSqrtPrice: BN, round_up: boolean, ): TokenAmounts { const _liquidity = new Decimal(liquidity.toString()); const _currentPrice = new Decimal(currentSqrtPrice.toString()); const _lowerPrice = new Decimal(lowerSqrtPrice.toString()); const _upperPrice = new Decimal(upperSqrtPrice.toString()); let tokenA, tokenB; if (currentSqrtPrice.lt(lowerSqrtPrice)) { // x = L * (pb - pa) / (pa * pb) tokenA = MathUtil.toX64_Decimal(_liquidity) .mul(_upperPrice.sub(_lowerPrice)) .div(_lowerPrice.mul(_upperPrice)); tokenB = new Decimal(0); } else if (currentSqrtPrice.lt(upperSqrtPrice)) { // x = L * (pb - p) / (p * pb) // y = L * (p - pa) tokenA = MathUtil.toX64_Decimal(_liquidity) .mul(_upperPrice.sub(_currentPrice)) .div(_currentPrice.mul(_upperPrice)); tokenB = MathUtil.fromX64_Decimal( _liquidity.mul(_currentPrice.sub(_lowerPrice)), ); } else { // y = L * (pb - pa) tokenA = new Decimal(0); tokenB = MathUtil.fromX64_Decimal( _liquidity.mul(_upperPrice.sub(_lowerPrice)), ); } // TODO: round up if (round_up) { return { tokenA: new BN(tokenA.ceil().toString()), tokenB: new BN(tokenB.ceil().toString()), }; } else { return { tokenA: new BN(tokenA.floor().toString()), tokenB: new BN(tokenB.floor().toString()), }; } } /** * Estimate the liquidity amount required to increase/decrease liquidity. * * // TODO: At the top end of the price range, tick calcuation is off therefore the results can be off * * @category Whirlpool Utils * @param currTick - Whirlpool's current tick index (aka price) * @param lowerTick - Position lower tick index * @param upperTick - Position upper tick index * @param tokenAmount - The desired amount of tokens to deposit/withdraw * @returns An estimated amount of liquidity needed to deposit/withdraw the desired amount of tokens. * @deprecated Please use {@link estimateMaxLiquidityFromTokenAmounts} instead. */ public static estimateLiquidityFromTokenAmounts( currTick: number, lowerTick: number, upperTick: number, tokenAmount: TokenAmounts, ): BN { return this.estimateMaxLiquidityFromTokenAmounts( PriceMath.tickIndexToSqrtPriceX64(currTick), lowerTick, upperTick, tokenAmount, ); } /** * Estimate the liquidity amount required to increase/decrease liquidity. * * @category Whirlpool Utils * @param sqrtPriceX64 - Whirlpool's current sqrt price * @param tickLowerIndex - Position lower tick index * @param tickUpperIndex - Position upper tick index * @param tokenAmount - The desired amount of tokens to deposit/withdraw * @returns An estimated amount of liquidity needed to deposit/withdraw the desired amount of tokens. */ public static estimateMaxLiquidityFromTokenAmounts( sqrtPriceX64: BN, tickLowerIndex: number, tickUpperIndex: number, tokenAmount: TokenAmounts, ): BN { if (tickUpperIndex < tickLowerIndex) { throw new Error("upper tick cannot be lower than the lower tick"); } const currSqrtPrice = sqrtPriceX64; const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex); const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex); if (currSqrtPrice.gte(upperSqrtPrice)) { return estLiquidityForTokenB( upperSqrtPrice, lowerSqrtPrice, tokenAmount.tokenB, ); } else if (currSqrtPrice.lt(lowerSqrtPrice)) { return estLiquidityForTokenA( lowerSqrtPrice, upperSqrtPrice, tokenAmount.tokenA, ); } else { const estLiquidityAmountA = estLiquidityForTokenA( currSqrtPrice, upperSqrtPrice, tokenAmount.tokenA, ); const estLiquidityAmountB = estLiquidityForTokenB( currSqrtPrice, lowerSqrtPrice, tokenAmount.tokenB, ); return BN.min(estLiquidityAmountA, estLiquidityAmountB); } } /** * Given an arbitrary pair of token mints, this function returns an ordering of the token mints * in the format [base, quote]. USD based stable coins are prioritized as the quote currency * followed by variants of SOL. * * @category Whirlpool Utils * @param tokenMintAKey - The mint of token A in the token pair. * @param tokenMintBKey - The mint of token B in the token pair. * @returns A two-element array with the tokens sorted in the order of [baseToken, quoteToken]. */ public static toBaseQuoteOrder( tokenMintAKey: PublicKey, tokenMintBKey: PublicKey, ): [PublicKey, PublicKey] { const pair: [PublicKey, PublicKey] = [tokenMintAKey, tokenMintBKey]; return pair.sort(sortByQuotePriority); } public static async isSupportedToken( ctx: WhirlpoolContext, whirlpoolsConfig: PublicKey, tokenMintKey: PublicKey, ) { // sync with is_supported_token (programs/whirlpool/src/util/v2/token.rs) const mintWithTokenProgram = await ctx.fetcher.getMintInfo(tokenMintKey); invariant(mintWithTokenProgram, "Mint not found"); if (mintWithTokenProgram.tokenProgram.equals(TOKEN_PROGRAM_ID)) { return true; } if (mintWithTokenProgram.address.equals(NATIVE_MINT_2022)) { return false; } const tokenBadgePda = PDAUtil.getTokenBadge( ctx.program.programId, whirlpoolsConfig, tokenMintKey, ); const tokenBadge = await ctx.fetcher.getTokenBadge(tokenBadgePda.publicKey); const isTokenBadgeInitialized = tokenBadge !== null; if ( mintWithTokenProgram.freezeAuthority !== null && !isTokenBadgeInitialized ) { return false; } // HACK: spl-token doesn't support ExtensionType.ConfidentialTransferFeeConfig yet const EXTENSION_TYPE_CONFIDENTIAL_TRANSFER_FEE_CONFIG = 16 as ExtensionType; const extensions = getExtensionTypes(mintWithTokenProgram.tlvData); for (const extension of extensions) { switch (extension) { // supported case ExtensionType.TransferFeeConfig: case ExtensionType.InterestBearingConfig: case ExtensionType.TokenMetadata: case ExtensionType.MetadataPointer: case ExtensionType.ConfidentialTransferMint: case EXTENSION_TYPE_CONFIDENTIAL_TRANSFER_FEE_CONFIG: continue; // supported if TokenBadge is initialized case ExtensionType.PermanentDelegate: case ExtensionType.TransferHook: case ExtensionType.MintCloseAuthority: if (!isTokenBadgeInitialized) { return false; } continue; case ExtensionType.DefaultAccountState: if (!isTokenBadgeInitialized) { return false; } const defaultAccountState = getDefaultAccountState(mintWithTokenProgram)!; if (defaultAccountState.state !== AccountState.Initialized) { return false; } continue; // not supported case ExtensionType.NonTransferable: return false; // not supported yet or unknown extension default: return false; } } return true; } } /** * @category Whirlpool Utils */ export type TokenAmounts = { tokenA: BN; tokenB: BN; }; /** * @category Whirlpool Utils */ export function toTokenAmount(a: number, b: number): TokenAmounts { return { tokenA: new BN(a.toString()), tokenB: new BN(b.toString()), }; } // These are the token mints that will be prioritized as the second token in the pair (quote). // The number that the mint maps to determines the priority that it will be used as the quote // currency. const QUOTE_TOKENS: { [mint: string]: number } = { [TOKEN_MINTS["USDT"]]: 100, [TOKEN_MINTS["USDC"]]: 90, // USDC [TOKEN_MINTS["USDH"]]: 80, // USDH [TOKEN_MINTS["SOL"]]: 70, // SOL [TOKEN_MINTS["mSOL"]]: 60, // mSOL [TOKEN_MINTS["stSOL"]]: 50, // stSOL }; const DEFAULT_QUOTE_PRIORITY = 0; function getQuoteTokenPriority(mint: string): number { const value = QUOTE_TOKENS[mint]; if (value) { return value; } return DEFAULT_QUOTE_PRIORITY; } function sortByQuotePriority( mintLeft: PublicKey, mintRight: PublicKey, ): number { return ( getQuoteTokenPriority(mintLeft.toString()) - getQuoteTokenPriority(mintRight.toString()) ); } // Convert this function based on Delta A = Delta L * (1/sqrt(lower) - 1/sqrt(upper)) function estLiquidityForTokenA( sqrtPrice1: BN, sqrtPrice2: BN, tokenAmount: BN, ) { const lowerSqrtPriceX64 = BN.min(sqrtPrice1, sqrtPrice2); const upperSqrtPriceX64 = BN.max(sqrtPrice1, sqrtPrice2); const num = MathUtil.fromX64_BN( tokenAmount.mul(upperSqrtPriceX64).mul(lowerSqrtPriceX64), ); const dem = upperSqrtPriceX64.sub(lowerSqrtPriceX64); return num.div(dem); } // Convert this function based on Delta B = Delta L * (sqrt_price(upper) - sqrt_price(lower)) function estLiquidityForTokenB( sqrtPrice1: BN, sqrtPrice2: BN, tokenAmount: BN, ) { const lowerSqrtPriceX64 = BN.min(sqrtPrice1, sqrtPrice2); const upperSqrtPriceX64 = BN.max(sqrtPrice1, sqrtPrice2); const delta = upperSqrtPriceX64.sub(lowerSqrtPriceX64); return tokenAmount.shln(64).div(delta); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/price-math.ts
import { BN } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { DecimalUtil, MathUtil } from "@orca-so/common-sdk"; import Decimal from "decimal.js"; import { MAX_SQRT_PRICE, MAX_SQRT_PRICE_BN, MIN_SQRT_PRICE, MIN_SQRT_PRICE_BN, } from "../../types/public"; import { TickUtil } from "./tick-utils"; const BIT_PRECISION = 14; const LOG_B_2_X32 = "59543866431248"; const LOG_B_P_ERR_MARGIN_LOWER_X64 = "184467440737095516"; const LOG_B_P_ERR_MARGIN_UPPER_X64 = "15793534762490258745"; /** * A collection of utility functions to convert between price, tickIndex and sqrtPrice. * * @category Whirlpool Utils */ export class PriceMath { public static priceToSqrtPriceX64( price: Decimal, decimalsA: number, decimalsB: number, ): BN { return MathUtil.toX64( price.mul(Decimal.pow(10, decimalsB - decimalsA)).sqrt(), ); } public static sqrtPriceX64ToPrice( sqrtPriceX64: BN, decimalsA: number, decimalsB: number, ): Decimal { return MathUtil.fromX64(sqrtPriceX64) .pow(2) .mul(Decimal.pow(10, decimalsA - decimalsB)); } /** * @param tickIndex * @returns */ public static tickIndexToSqrtPriceX64(tickIndex: number): BN { if (tickIndex > 0) { return new BN(tickIndexToSqrtPricePositive(tickIndex)); } else { return new BN(tickIndexToSqrtPriceNegative(tickIndex)); } } /** * * @param sqrtPriceX64 * @returns */ public static sqrtPriceX64ToTickIndex(sqrtPriceX64: BN): number { if ( sqrtPriceX64.gt(new BN(MAX_SQRT_PRICE)) || sqrtPriceX64.lt(new BN(MIN_SQRT_PRICE)) ) { throw new Error( "Provided sqrtPrice is not within the supported sqrtPrice range.", ); } const msb = sqrtPriceX64.bitLength() - 1; const adjustedMsb = new BN(msb - 64); const log2pIntegerX32 = signedShiftLeft(adjustedMsb, 32, 128); let bit = new BN("8000000000000000", "hex"); let precision = 0; let log2pFractionX64 = new BN(0); let r = msb >= 64 ? sqrtPriceX64.shrn(msb - 63) : sqrtPriceX64.shln(63 - msb); while (bit.gt(new BN(0)) && precision < BIT_PRECISION) { r = r.mul(r); let rMoreThanTwo = r.shrn(127); r = r.shrn(63 + rMoreThanTwo.toNumber()); log2pFractionX64 = log2pFractionX64.add(bit.mul(rMoreThanTwo)); bit = bit.shrn(1); precision += 1; } const log2pFractionX32 = log2pFractionX64.shrn(32); const log2pX32 = log2pIntegerX32.add(log2pFractionX32); const logbpX64 = log2pX32.mul(new BN(LOG_B_2_X32)); const tickLow = signedShiftRight( logbpX64.sub(new BN(LOG_B_P_ERR_MARGIN_LOWER_X64)), 64, 128, ).toNumber(); const tickHigh = signedShiftRight( logbpX64.add(new BN(LOG_B_P_ERR_MARGIN_UPPER_X64)), 64, 128, ).toNumber(); if (tickLow == tickHigh) { return tickLow; } else { const derivedTickHighSqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(tickHigh); if (derivedTickHighSqrtPriceX64.lte(sqrtPriceX64)) { return tickHigh; } else { return tickLow; } } } public static tickIndexToPrice( tickIndex: number, decimalsA: number, decimalsB: number, ): Decimal { return PriceMath.sqrtPriceX64ToPrice( PriceMath.tickIndexToSqrtPriceX64(tickIndex), decimalsA, decimalsB, ); } public static priceToTickIndex( price: Decimal, decimalsA: number, decimalsB: number, ): number { return PriceMath.sqrtPriceX64ToTickIndex( PriceMath.priceToSqrtPriceX64(price, decimalsA, decimalsB), ); } public static priceToInitializableTickIndex( price: Decimal, decimalsA: number, decimalsB: number, tickSpacing: number, ): number { return TickUtil.getInitializableTickIndex( PriceMath.priceToTickIndex(price, decimalsA, decimalsB), tickSpacing, ); } /** * Utility to invert the price Pb/Pa to Pa/Pb * NOTE: precision is lost in this conversion * * @param price Pb / Pa * @param decimalsA Decimals of original token A (i.e. token A in the given Pb / Pa price) * @param decimalsB Decimals of original token B (i.e. token B in the given Pb / Pa price) * @returns inverted price, i.e. Pa / Pb */ public static invertPrice( price: Decimal, decimalsA: number, decimalsB: number, ): Decimal { const tick = PriceMath.priceToTickIndex(price, decimalsA, decimalsB); const invTick = TickUtil.invertTick(tick); return PriceMath.tickIndexToPrice(invTick, decimalsB, decimalsA); } /** * Utility to invert the sqrtPriceX64 from X64 repr. of sqrt(Pb/Pa) to X64 repr. of sqrt(Pa/Pb) * NOTE: precision is lost in this conversion * * @param sqrtPriceX64 X64 representation of sqrt(Pb / Pa) * @returns inverted sqrtPriceX64, i.e. X64 representation of sqrt(Pa / Pb) */ public static invertSqrtPriceX64(sqrtPriceX64: BN): BN { const tick = PriceMath.sqrtPriceX64ToTickIndex(sqrtPriceX64); const invTick = TickUtil.invertTick(tick); return PriceMath.tickIndexToSqrtPriceX64(invTick); } /** * Calculate the sqrtPriceX64 & tick index slippage price boundary for a given price and slippage. * Note: This function loses precision * * @param sqrtPriceX64 the sqrtPriceX64 to apply the slippage on * @param slippage the slippage to apply onto the sqrtPriceX64 * @returns the sqrtPriceX64 & tick index slippage price boundary */ public static getSlippageBoundForSqrtPrice( sqrtPriceX64: BN, slippage: Percentage, ): { lowerBound: [BN, number]; upperBound: [BN, number] } { const sqrtPriceX64Decimal = DecimalUtil.fromBN(sqrtPriceX64); const slippageNumerator = new Decimal(slippage.numerator.toString()); const slippageDenominator = new Decimal(slippage.denominator.toString()); const lowerBoundSqrtPriceDecimal = sqrtPriceX64Decimal .mul(slippageDenominator.sub(slippageNumerator).sqrt()) .div(slippageDenominator.sqrt()) .toDecimalPlaces(0); const upperBoundSqrtPriceDecimal = sqrtPriceX64Decimal .mul(slippageDenominator.add(slippageNumerator).sqrt()) .div(slippageDenominator.sqrt()) .toDecimalPlaces(0); const lowerBoundSqrtPrice = BN.min( BN.max(new BN(lowerBoundSqrtPriceDecimal.toFixed(0)), MIN_SQRT_PRICE_BN), MAX_SQRT_PRICE_BN, ); const upperBoundSqrtPrice = BN.min( BN.max(new BN(upperBoundSqrtPriceDecimal.toFixed(0)), MIN_SQRT_PRICE_BN), MAX_SQRT_PRICE_BN, ); const lowerTickCurrentIndex = PriceMath.sqrtPriceX64ToTickIndex(lowerBoundSqrtPrice); const upperTickCurrentIndex = PriceMath.sqrtPriceX64ToTickIndex(upperBoundSqrtPrice); return { lowerBound: [lowerBoundSqrtPrice, lowerTickCurrentIndex], upperBound: [upperBoundSqrtPrice, upperTickCurrentIndex], }; } } // Private Functions function tickIndexToSqrtPricePositive(tick: number) { let ratio: BN; if ((tick & 1) != 0) { ratio = new BN("79232123823359799118286999567"); } else { ratio = new BN("79228162514264337593543950336"); } if ((tick & 2) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79236085330515764027303304731")), 96, 256, ); } if ((tick & 4) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79244008939048815603706035061")), 96, 256, ); } if ((tick & 8) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79259858533276714757314932305")), 96, 256, ); } if ((tick & 16) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79291567232598584799939703904")), 96, 256, ); } if ((tick & 32) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79355022692464371645785046466")), 96, 256, ); } if ((tick & 64) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79482085999252804386437311141")), 96, 256, ); } if ((tick & 128) != 0) { ratio = signedShiftRight( ratio.mul(new BN("79736823300114093921829183326")), 96, 256, ); } if ((tick & 256) != 0) { ratio = signedShiftRight( ratio.mul(new BN("80248749790819932309965073892")), 96, 256, ); } if ((tick & 512) != 0) { ratio = signedShiftRight( ratio.mul(new BN("81282483887344747381513967011")), 96, 256, ); } if ((tick & 1024) != 0) { ratio = signedShiftRight( ratio.mul(new BN("83390072131320151908154831281")), 96, 256, ); } if ((tick & 2048) != 0) { ratio = signedShiftRight( ratio.mul(new BN("87770609709833776024991924138")), 96, 256, ); } if ((tick & 4096) != 0) { ratio = signedShiftRight( ratio.mul(new BN("97234110755111693312479820773")), 96, 256, ); } if ((tick & 8192) != 0) { ratio = signedShiftRight( ratio.mul(new BN("119332217159966728226237229890")), 96, 256, ); } if ((tick & 16384) != 0) { ratio = signedShiftRight( ratio.mul(new BN("179736315981702064433883588727")), 96, 256, ); } if ((tick & 32768) != 0) { ratio = signedShiftRight( ratio.mul(new BN("407748233172238350107850275304")), 96, 256, ); } if ((tick & 65536) != 0) { ratio = signedShiftRight( ratio.mul(new BN("2098478828474011932436660412517")), 96, 256, ); } if ((tick & 131072) != 0) { ratio = signedShiftRight( ratio.mul(new BN("55581415166113811149459800483533")), 96, 256, ); } if ((tick & 262144) != 0) { ratio = signedShiftRight( ratio.mul(new BN("38992368544603139932233054999993551")), 96, 256, ); } return signedShiftRight(ratio, 32, 256); } function tickIndexToSqrtPriceNegative(tickIndex: number) { let tick = Math.abs(tickIndex); let ratio: BN; if ((tick & 1) != 0) { ratio = new BN("18445821805675392311"); } else { ratio = new BN("18446744073709551616"); } if ((tick & 2) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18444899583751176498")), 64, 256, ); } if ((tick & 4) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18443055278223354162")), 64, 256, ); } if ((tick & 8) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18439367220385604838")), 64, 256, ); } if ((tick & 16) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18431993317065449817")), 64, 256, ); } if ((tick & 32) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18417254355718160513")), 64, 256, ); } if ((tick & 64) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18387811781193591352")), 64, 256, ); } if ((tick & 128) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18329067761203520168")), 64, 256, ); } if ((tick & 256) != 0) { ratio = signedShiftRight( ratio.mul(new BN("18212142134806087854")), 64, 256, ); } if ((tick & 512) != 0) { ratio = signedShiftRight( ratio.mul(new BN("17980523815641551639")), 64, 256, ); } if ((tick & 1024) != 0) { ratio = signedShiftRight( ratio.mul(new BN("17526086738831147013")), 64, 256, ); } if ((tick & 2048) != 0) { ratio = signedShiftRight( ratio.mul(new BN("16651378430235024244")), 64, 256, ); } if ((tick & 4096) != 0) { ratio = signedShiftRight( ratio.mul(new BN("15030750278693429944")), 64, 256, ); } if ((tick & 8192) != 0) { ratio = signedShiftRight( ratio.mul(new BN("12247334978882834399")), 64, 256, ); } if ((tick & 16384) != 0) { ratio = signedShiftRight(ratio.mul(new BN("8131365268884726200")), 64, 256); } if ((tick & 32768) != 0) { ratio = signedShiftRight(ratio.mul(new BN("3584323654723342297")), 64, 256); } if ((tick & 65536) != 0) { ratio = signedShiftRight(ratio.mul(new BN("696457651847595233")), 64, 256); } if ((tick & 131072) != 0) { ratio = signedShiftRight(ratio.mul(new BN("26294789957452057")), 64, 256); } if ((tick & 262144) != 0) { ratio = signedShiftRight(ratio.mul(new BN("37481735321082")), 64, 256); } return ratio; } function signedShiftLeft(n0: BN, shiftBy: number, bitWidth: number) { let twosN0 = n0.toTwos(bitWidth).shln(shiftBy); twosN0.imaskn(bitWidth + 1); return twosN0.fromTwos(bitWidth); } function signedShiftRight(n0: BN, shiftBy: number, bitWidth: number) { let twoN0 = n0.toTwos(bitWidth).shrn(shiftBy); twoN0.imaskn(bitWidth - shiftBy + 1); return twoN0.fromTwos(bitWidth - shiftBy); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/swap-utils.ts
import type { Address } from "@coral-xyz/anchor"; import type { Percentage } from "@orca-so/common-sdk"; import { AddressUtil, U64_MAX, ZERO } from "@orca-so/common-sdk"; import type { PublicKey } from "@solana/web3.js"; import BN from "bn.js"; import type { WhirlpoolContext } from "../.."; import { TickUtil } from "../.."; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, } from "../../network/public/fetcher"; import type { SwapInput, SwapParams, TickArray, WhirlpoolData, } from "../../types/public"; import { MAX_SQRT_PRICE, MIN_SQRT_PRICE } from "../../types/public"; import type { Whirlpool } from "../../whirlpool-client"; import { adjustForSlippage } from "../math/token-math"; import { PDAUtil } from "./pda-utils"; import { PoolUtil } from "./pool-utils"; import { SwapDirection, TokenType } from "./types"; import type { TickArrayAddress } from "../swap-utils"; import { buildZeroedTickArray, getTickArrayPublicKeysWithStartTickIndex, } from "../swap-utils"; /** * A request to fetch the tick-arrays that a swap may traverse across. * @category Whirlpool Utils */ export interface TickArrayRequest { whirlpoolAddress: PublicKey; aToB: boolean; tickCurrentIndex: number; tickSpacing: number; } /** * @category Whirlpool Utils */ export class SwapUtils { /** * Get the default values for the sqrtPriceLimit parameter in a swap. * @param aToB - The direction of a swap * @returns The default values for the sqrtPriceLimit parameter in a swap. */ public static getDefaultSqrtPriceLimit(aToB: boolean) { return new BN(aToB ? MIN_SQRT_PRICE : MAX_SQRT_PRICE); } /** * Get the default values for the otherAmountThreshold parameter in a swap. * @param amountSpecifiedIsInput - The direction of a swap * @returns The default values for the otherAmountThreshold parameter in a swap. */ public static getDefaultOtherAmountThreshold( amountSpecifiedIsInput: boolean, ) { return amountSpecifiedIsInput ? ZERO : U64_MAX; } /** * Given the intended token mint to swap, return the swap direction of a swap for a Whirlpool * @param pool The Whirlpool to evaluate the mint against * @param swapTokenMint The token mint PublicKey the user bases their swap against * @param swapTokenIsInput Whether the swap token is the input token. (similar to amountSpecifiedIsInput from swap Ix) * @returns The direction of the swap given the swapTokenMint. undefined if the token mint is not part of the trade pair of the pool. */ public static getSwapDirection( pool: WhirlpoolData, swapTokenMint: PublicKey, swapTokenIsInput: boolean, ): SwapDirection | undefined { const tokenType = PoolUtil.getTokenType(pool, swapTokenMint); if (!tokenType) { return undefined; } return (tokenType === TokenType.TokenA) === swapTokenIsInput ? SwapDirection.AtoB : SwapDirection.BtoA; } /** * Given the current tick-index, returns the dervied PDA and fetched data * for the tick-arrays that this swap may traverse across. * * @category Whirlpool Utils * @param tickCurrentIndex - The current tickIndex for the Whirlpool to swap on. * @param tickSpacing - The tickSpacing for the Whirlpool. * @param aToB - The direction of the trade. * @param programId - The Whirlpool programId which the Whirlpool lives on. * @param whirlpoolAddress - PublicKey of the whirlpool to swap on. * @returns An array of PublicKey[] for the tickArray accounts that this swap may traverse across. */ public static getTickArrayPublicKeys( tickCurrentIndex: number, tickSpacing: number, aToB: boolean, programId: PublicKey, whirlpoolAddress: PublicKey, ): PublicKey[] { return getTickArrayPublicKeysWithStartTickIndex( tickCurrentIndex, tickSpacing, aToB, programId, whirlpoolAddress, ).map((p) => p.pubkey); } /** * Given the tickArrays, return the fallback tickArray account that this swap may traverse across. * * @category Whirlpool Utils * @param tickArrays - An array of tickArrays to be used in the swap. * @param tickSpacing - The tickSpacing for the Whirlpool. * @param aToB - The direction of the trade. * @param programId - The Whirlpool programId which the Whirlpool lives on. * @param whirlpoolAddress - PublicKey of the whirlpool to swap on. * @returns A PublicKey for the fallback tickArray account that this swap may traverse across. If the fallback tickArray does not exist, return undefined. */ public static getFallbackTickArrayPublicKey( tickArrays: TickArray[], tickSpacing: number, aToB: boolean, programId: PublicKey, whirlpoolAddress: PublicKey, ): PublicKey | undefined { try { const fallbackStartTickIndex = TickUtil.getStartTickIndex( tickArrays[0].startTickIndex, tickSpacing, aToB ? 1 : -1, ); const pda = PDAUtil.getTickArray( programId, whirlpoolAddress, fallbackStartTickIndex, ); return pda.publicKey; } catch { return undefined; } } /** * Given the current tick-index, returns TickArray objects that this swap may traverse across. * * @category Whirlpool Utils * @param tickCurrentIndex - The current tickIndex for the Whirlpool to swap on. * @param tickSpacing - The tickSpacing for the Whirlpool. * @param aToB - The direction of the trade. * @param programId - The Whirlpool programId which the Whirlpool lives on. * @param whirlpoolAddress - PublicKey of the whirlpool to swap on. * @param cache - WhirlpoolAccountCacheInterface object to fetch solana accounts * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns An array of PublicKey[] for the tickArray accounts that this swap may traverse across. */ public static async getTickArrays( tickCurrentIndex: number, tickSpacing: number, aToB: boolean, programId: PublicKey, whirlpoolAddress: PublicKey, fetcher: WhirlpoolAccountFetcherInterface, opts?: WhirlpoolAccountFetchOptions, ): Promise<TickArray[]> { const data = await this.getBatchTickArrays( programId, fetcher, [{ tickCurrentIndex, tickSpacing, aToB, whirlpoolAddress }], opts, ); return data[0]; } /** * Fetch a batch of tick-arrays for a set of TA requests. * @param programId - The Whirlpool programId which the Whirlpool lives on. * @param cache - WhirlpoolAccountCacheInterface instance to fetch solana accounts * @param tickArrayRequests - An array of {@link TickArrayRequest} of tick-arrays to request for. * @param opts an {@link WhirlpoolAccountFetchOptions} object to define fetch and cache options when accessing on-chain accounts * @returns A array of request indicies mapped to an array of resulting PublicKeys. */ public static async getBatchTickArrays( programId: PublicKey, fetcher: WhirlpoolAccountFetcherInterface, tickArrayRequests: TickArrayRequest[], opts?: WhirlpoolAccountFetchOptions, ): Promise<TickArray[][]> { let addresses: TickArrayAddress[] = []; let requestToIndices = []; // Each individual tick array request may correspond to more than one tick array // so we map each request to a slice of the batch request for (let i = 0; i < tickArrayRequests.length; i++) { const { tickCurrentIndex, tickSpacing, aToB, whirlpoolAddress } = tickArrayRequests[i]; const requestAddresses = getTickArrayPublicKeysWithStartTickIndex( tickCurrentIndex, tickSpacing, aToB, programId, whirlpoolAddress, ); requestToIndices.push([ addresses.length, addresses.length + requestAddresses.length, ]); addresses.push(...requestAddresses); } const data = await fetcher.getTickArrays( addresses.map((a) => a.pubkey), opts, ); // Re-map from flattened batch data to TickArray[] for request return requestToIndices.map((indices) => { const [start, end] = indices; const addressSlice = addresses.slice(start, end); const dataSlice = data.slice(start, end); return addressSlice.map((addr, index) => ({ address: addr.pubkey, startTickIndex: addr.startTickIndex, data: dataSlice[index], })); }); } /** * Given a set of tickArrays, interpolate the tickArrays with zeroed tick data if they are not initialized. * * @param whirlpoolAddress - PublicKey of the whirlpool to swap on. * @param tickArrays - Fetched tickArrays to interpolate. * @returns An array of TickArray objects with zeroed tick data if they are not initialized. */ public static interpolateUninitializedTickArrays( whirlpoolAddress: PublicKey, tickArrays: TickArray[], ): TickArray[] { return tickArrays.map((tickArray) => ({ address: tickArray.address, startTickIndex: tickArray.startTickIndex, data: tickArray.data ?? buildZeroedTickArray(whirlpoolAddress, tickArray.startTickIndex), })); } /** * Calculate the SwapInput parameters `amount` & `otherAmountThreshold` based on the amountIn & amountOut estimates from a quote. * @param amount - The amount of tokens the user wanted to swap from. * @param estAmountIn - The estimated amount of input tokens expected in a `SwapQuote` * @param estAmountOut - The estimated amount of output tokens expected from a `SwapQuote` * @param slippageTolerance - The amount of slippage to adjust for. * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents in the swap quote. If true, the amount represents * the input token of the swap. * @returns A Partial `SwapInput` object containing the slippage adjusted 'amount' & 'otherAmountThreshold' parameters. */ public static calculateSwapAmountsFromQuote( amount: BN, estAmountIn: BN, estAmountOut: BN, slippageTolerance: Percentage, amountSpecifiedIsInput: boolean, ): Pick<SwapInput, "amount" | "otherAmountThreshold"> { if (amountSpecifiedIsInput) { return { amount, otherAmountThreshold: adjustForSlippage( estAmountOut, slippageTolerance, false, ), }; } else { return { amount, otherAmountThreshold: adjustForSlippage( estAmountIn, slippageTolerance, true, ), }; } } /** * Convert a quote object and WhirlpoolClient's {@link Whirlpool} object into a {@link SwapParams} type * to be plugged into {@link WhirlpoolIx.swapIx}. * * @param quote - A {@link SwapQuote} type generated from {@link swapQuoteWithParams} * @param ctx - {@link WhirlpoolContext} * @param whirlpool - A {@link Whirlpool} object from WhirlpoolClient * @param inputTokenAssociatedAddress - The public key for the ATA of the input token in the swap * @param outputTokenAssociatedAddress - The public key for the ATA of the input token in the swap * @param wallet - The token authority for this swap * @returns A converted {@link SwapParams} generated from the input */ public static getSwapParamsFromQuote( quote: SwapInput, ctx: WhirlpoolContext, whirlpool: Whirlpool, inputTokenAssociatedAddress: Address, outputTokenAssociatedAddress: Address, wallet: PublicKey, ) { const data = whirlpool.getData(); return this.getSwapParamsFromQuoteKeys( quote, ctx, whirlpool.getAddress(), data.tokenVaultA, data.tokenVaultB, inputTokenAssociatedAddress, outputTokenAssociatedAddress, wallet, ); } public static getSwapParamsFromQuoteKeys( quote: SwapInput, ctx: WhirlpoolContext, whirlpool: PublicKey, tokenVaultA: PublicKey, tokenVaultB: PublicKey, inputTokenAssociatedAddress: Address, outputTokenAssociatedAddress: Address, wallet: PublicKey, ) { const aToB = quote.aToB; const [inputTokenATA, outputTokenATA] = AddressUtil.toPubKeys([ inputTokenAssociatedAddress, outputTokenAssociatedAddress, ]); const oraclePda = PDAUtil.getOracle(ctx.program.programId, whirlpool); const params: SwapParams = { whirlpool, tokenOwnerAccountA: aToB ? inputTokenATA : outputTokenATA, tokenOwnerAccountB: aToB ? outputTokenATA : inputTokenATA, tokenVaultA, tokenVaultB, oracle: oraclePda.publicKey, tokenAuthority: wallet, ...quote, }; return params; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/types.ts
/** * An enum for the direction of a swap. * @category Whirlpool Utils */ export enum SwapDirection { AtoB = "aToB", BtoA = "bToA", } /** * An enum for the token type in a Whirlpool. * @category Whirlpool Utils */ export enum TokenType { TokenA = 1, TokenB, }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/position-bundle-util.ts
import invariant from "tiny-invariant"; import type { PositionBundleData } from "../../types/public"; import { POSITION_BUNDLE_SIZE } from "../../types/public"; /** * A collection of utility functions when interacting with a PositionBundle. * @category Whirlpool Utils */ export class PositionBundleUtil { /** * Check if the bundle index is in the correct range. * * @param bundleIndex The bundle index to be checked * @returns true if bundle index is in the correct range */ public static checkBundleIndexInBounds(bundleIndex: number): boolean { return bundleIndex >= 0 && bundleIndex < POSITION_BUNDLE_SIZE; } /** * Check if the Bundled Position corresponding to the bundle index has been opened. * * @param positionBundle The position bundle to be checked * @param bundleIndex The bundle index to be checked * @returns true if Bundled Position has been opened */ public static isOccupied( positionBundle: PositionBundleData, bundleIndex: number, ): boolean { invariant( PositionBundleUtil.checkBundleIndexInBounds(bundleIndex), "bundleIndex out of range", ); const array = PositionBundleUtil.convertBitmapToArray(positionBundle); return array[bundleIndex]; } /** * Check if the Bundled Position corresponding to the bundle index has not been opened. * * @param positionBundle The position bundle to be checked * @param bundleIndex The bundle index to be checked * @returns true if Bundled Position has not been opened */ public static isUnoccupied( positionBundle: PositionBundleData, bundleIndex: number, ): boolean { return !PositionBundleUtil.isOccupied(positionBundle, bundleIndex); } /** * Check if all bundle index is occupied. * * @param positionBundle The position bundle to be checked * @returns true if all bundle index is occupied */ public static isFull(positionBundle: PositionBundleData): boolean { const unoccupied = PositionBundleUtil.getUnoccupiedBundleIndexes(positionBundle); return unoccupied.length === 0; } /** * Check if all bundle index is unoccupied. * * @param positionBundle The position bundle to be checked * @returns true if all bundle index is unoccupied */ public static isEmpty(positionBundle: PositionBundleData): boolean { const occupied = PositionBundleUtil.getOccupiedBundleIndexes(positionBundle); return occupied.length === 0; } /** * Get all bundle indexes where the corresponding Bundled Position is open. * * @param positionBundle The position bundle to be checked * @returns The array of bundle index where the corresponding Bundled Position is open */ public static getOccupiedBundleIndexes( positionBundle: PositionBundleData, ): number[] { const result: number[] = []; PositionBundleUtil.convertBitmapToArray(positionBundle).forEach( (occupied, index) => { if (occupied) { result.push(index); } }, ); return result; } /** * Get all bundle indexes where the corresponding Bundled Position is not open. * * @param positionBundle The position bundle to be checked * @returns The array of bundle index where the corresponding Bundled Position is not open */ public static getUnoccupiedBundleIndexes( positionBundle: PositionBundleData, ): number[] { const result: number[] = []; PositionBundleUtil.convertBitmapToArray(positionBundle).forEach( (occupied, index) => { if (!occupied) { result.push(index); } }, ); return result; } /** * Get the first unoccupied bundle index in the position bundle. * * @param positionBundle The position bundle to be checked * @returns The first unoccupied bundle index, null if the position bundle is full */ public static findUnoccupiedBundleIndex( positionBundle: PositionBundleData, ): number | null { const unoccupied = PositionBundleUtil.getUnoccupiedBundleIndexes(positionBundle); return unoccupied.length === 0 ? null : unoccupied[0]; } /** * Convert position bitmap to the array of boolean which represent if Bundled Position is open. * * @param positionBundle The position bundle whose bitmap will be converted * @returns The array of boolean representing if Bundled Position is open */ public static convertBitmapToArray( positionBundle: PositionBundleData, ): boolean[] { const result: boolean[] = []; positionBundle.positionBitmap.map((bitmap) => { for (let offset = 0; offset < 8; offset++) { result.push((bitmap & (1 << offset)) !== 0); } }); return result; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/index.ts
export * from "../graphs/public"; export * from "./ix-utils"; export * from "./pda-utils"; export * from "./pool-utils"; export * from "./position-bundle-util"; export * from "./price-math"; export * from "./swap-utils"; export * from "./tick-utils"; export * from "./token-extension-util"; export * from "./types";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/public/token-extension-util.ts
import type { TransferFee } from "@solana/spl-token"; import { calculateFee, getEpochFee, getTransferFeeConfig, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, getTransferHook, addExtraAccountMetasForExecute, } from "@solana/spl-token"; import BN from "bn.js"; import type { MintWithTokenProgram } from "@orca-so/common-sdk"; import { U64_MAX, ZERO } from "@orca-so/common-sdk"; import type { WhirlpoolAccountFetchOptions, WhirlpoolAccountFetcherInterface, WhirlpoolData, } from "../.."; import { PoolUtil } from "../.."; import type { AccountMeta, Connection } from "@solana/web3.js"; import { PublicKey, TransactionInstruction } from "@solana/web3.js"; export type TransferFeeIncludedAmount = { amount: BN; fee: BN; }; export type TransferFeeExcludedAmount = { amount: BN; fee: BN; }; export type TokenExtensionContext = { currentEpoch: number; tokenMintWithProgramA: MintWithTokenProgram; tokenMintWithProgramB: MintWithTokenProgram; rewardTokenMintsWithProgram: [ MintWithTokenProgram | null, MintWithTokenProgram | null, MintWithTokenProgram | null, ]; }; export type TokenExtensionContextForPool = Omit< TokenExtensionContext, "rewardTokenMintsWithProgram" >; export type TokenExtensionContextForReward = Omit< TokenExtensionContext, "tokenMintWithProgramA" | "tokenMintWithProgramB" >; const defaultTokenMintWithProgram: MintWithTokenProgram = { address: PublicKey.default, decimals: 0, freezeAuthority: null, mintAuthority: null, isInitialized: true, supply: 0n, tlvData: Buffer.from([]), tokenProgram: TOKEN_PROGRAM_ID, }; export const NO_TOKEN_EXTENSION_CONTEXT: TokenExtensionContext = { currentEpoch: 0, tokenMintWithProgramA: defaultTokenMintWithProgram, tokenMintWithProgramB: defaultTokenMintWithProgram, rewardTokenMintsWithProgram: [ defaultTokenMintWithProgram, defaultTokenMintWithProgram, defaultTokenMintWithProgram, ], }; export class TokenExtensionUtil { public static calculateTransferFeeIncludedAmount( transferFeeExcludedAmount: BN, tokenInfo: MintWithTokenProgram, currentEpoch: number, ): TransferFeeIncludedAmount { const config = getTransferFeeConfig(tokenInfo); if (config === null) { return { amount: transferFeeExcludedAmount, fee: ZERO }; } const transferFee = getEpochFee(config, BigInt(currentEpoch)); return calculateTransferFeeIncludedAmount( transferFee, transferFeeExcludedAmount, ); } public static calculateTransferFeeExcludedAmount( transferFeeIncludedAmount: BN, tokenInfo: MintWithTokenProgram, currentEpoch: number, ): TransferFeeExcludedAmount { const config = getTransferFeeConfig(tokenInfo); if (config === null) { return { amount: transferFeeIncludedAmount, fee: ZERO }; } const transferFee = getEpochFee(config, BigInt(currentEpoch)); return calculateTransferFeeExcludedAmount( transferFee, transferFeeIncludedAmount, ); } public static async buildTokenExtensionContext( fetcher: WhirlpoolAccountFetcherInterface, whirlpoolData: WhirlpoolData, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenExtensionContext> { const mintA = whirlpoolData.tokenMintA; const mintB = whirlpoolData.tokenMintB; const rewards = whirlpoolData.rewardInfos; const [tokenMintWithProgram, currentEpoch] = await Promise.all([ fetcher.getMintInfos( [ mintA, mintB, ...rewards .filter((r) => PoolUtil.isRewardInitialized(r)) .map((r) => r.mint), ], opts, ), fetcher.getEpoch(), ]); const get = (mint: PublicKey) => tokenMintWithProgram.get(mint.toBase58())!; return { tokenMintWithProgramA: get(whirlpoolData.tokenMintA), tokenMintWithProgramB: get(whirlpoolData.tokenMintB), rewardTokenMintsWithProgram: [ PoolUtil.isRewardInitialized(rewards[0]) ? get(rewards[0].mint) : null, PoolUtil.isRewardInitialized(rewards[1]) ? get(rewards[1].mint) : null, PoolUtil.isRewardInitialized(rewards[2]) ? get(rewards[2].mint) : null, ], currentEpoch, }; } public static async buildTokenExtensionContextForPool( fetcher: WhirlpoolAccountFetcherInterface, tokenMintA: PublicKey, tokenMintB: PublicKey, opts?: WhirlpoolAccountFetchOptions, ): Promise<TokenExtensionContextForPool> { const [tokenMintWithProgram, currentEpoch] = await Promise.all([ fetcher.getMintInfos([tokenMintA, tokenMintB], opts), fetcher.getEpoch(), ]); const get = (mint: PublicKey) => tokenMintWithProgram.get(mint.toBase58())!; return { tokenMintWithProgramA: get(tokenMintA), tokenMintWithProgramB: get(tokenMintB), currentEpoch, }; } public static async getExtraAccountMetasForTransferHook( connection: Connection, tokenMintWithProgram: MintWithTokenProgram, source: PublicKey, destination: PublicKey, owner: PublicKey, ): Promise<AccountMeta[] | undefined> { const transferHook = getTransferHook(tokenMintWithProgram); if (!transferHook) return undefined; const instruction = new TransactionInstruction({ programId: TOKEN_2022_PROGRAM_ID, keys: [ { pubkey: source, isSigner: false, isWritable: false }, { pubkey: tokenMintWithProgram.address, isSigner: false, isWritable: false, }, { pubkey: destination, isSigner: false, isWritable: false }, { pubkey: owner, isSigner: false, isWritable: false }, { pubkey: owner, isSigner: false, isWritable: false }, ], }); await addExtraAccountMetasForExecute( connection, instruction, transferHook.programId, source, tokenMintWithProgram.address, destination, owner, 0n, // extra account must not depend on the amount (the amount will be changed due to slippage) "confirmed", ); const extraAccountMetas = instruction.keys.slice(5); return extraAccountMetas.length > 0 ? extraAccountMetas : undefined; } public static async getExtraAccountMetasForTransferHookForPool( connection: Connection, tokenExtensionCtx: TokenExtensionContextForPool, sourceA: PublicKey, destinationA: PublicKey, ownerA: PublicKey, sourceB: PublicKey, destinationB: PublicKey, ownerB: PublicKey, ): Promise<{ tokenTransferHookAccountsA: AccountMeta[] | undefined; tokenTransferHookAccountsB: AccountMeta[] | undefined; }> { const [tokenTransferHookAccountsA, tokenTransferHookAccountsB] = await Promise.all([ TokenExtensionUtil.getExtraAccountMetasForTransferHook( connection, tokenExtensionCtx.tokenMintWithProgramA, sourceA, destinationA, ownerA, ), TokenExtensionUtil.getExtraAccountMetasForTransferHook( connection, tokenExtensionCtx.tokenMintWithProgramB, sourceB, destinationB, ownerB, ), ]); return { tokenTransferHookAccountsA, tokenTransferHookAccountsB, }; } public static isV2IxRequiredPool( tokenExtensionCtx: TokenExtensionContextForPool, ): boolean { return ( tokenExtensionCtx.tokenMintWithProgramA.tokenProgram.equals( TOKEN_2022_PROGRAM_ID, ) || tokenExtensionCtx.tokenMintWithProgramB.tokenProgram.equals( TOKEN_2022_PROGRAM_ID, ) ); } public static isV2IxRequiredReward( tokenExtensionCtx: TokenExtensionContextForReward, rewardIndex: number, ): boolean { return ( tokenExtensionCtx.rewardTokenMintsWithProgram[ rewardIndex ]?.tokenProgram.equals(TOKEN_2022_PROGRAM_ID) ?? false ); } } function ceilDivBN(num: BN, denom: BN): BN { return num.add(denom.subn(1)).div(denom); } function calculateTransferFeeIncludedAmount( transferFee: TransferFee, amount: BN, ): TransferFeeIncludedAmount { // https://github.com/solana-labs/solana-program-library/blob/master/token/program-2022/src/extension/transfer_fee/mod.rs#L90 const ONE_IN_BASIS_POINTS = 10_000; const maxFeeBN = new BN(transferFee.maximumFee.toString()); // edge cases if (transferFee.transferFeeBasisPoints === 0) { return { amount, fee: ZERO, }; } if (amount.isZero()) { return { amount, fee: ZERO, }; } if (transferFee.transferFeeBasisPoints === ONE_IN_BASIS_POINTS) { if (amount.add(maxFeeBN).gt(U64_MAX)) { throw new Error("The total amount and fees overflow"); } return { amount: amount.add(maxFeeBN), fee: maxFeeBN, }; } // normal case const num = amount.muln(ONE_IN_BASIS_POINTS); const denom = new BN( ONE_IN_BASIS_POINTS - transferFee.transferFeeBasisPoints, ); const rawFeeIncludedAmount = ceilDivBN(num, denom); const result = rawFeeIncludedAmount.sub(amount).gte(maxFeeBN) ? { amount: amount.add(maxFeeBN), fee: maxFeeBN } : { amount: rawFeeIncludedAmount, fee: rawFeeIncludedAmount.sub(amount) }; if (result.amount.gt(U64_MAX)) { throw new Error("The total amount and fees overflow"); } return { ...result }; } function calculateTransferFeeExcludedAmount( transferFee: TransferFee, amount: BN, ): TransferFeeExcludedAmount { const fee = calculateFee(transferFee, BigInt(amount.toString())); const feeBN = new BN(fee.toString()); return { amount: amount.sub(feeBN), fee: feeBN, }; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs/adjacency-list-pool-graph.ts
import type { Address } from "@coral-xyz/anchor"; import { AddressUtil } from "@orca-so/common-sdk"; import type { Edge, Path, PathSearchEntries, PathSearchOptions, PoolGraph, PoolTokenPair, } from "./public/pool-graph"; import { PoolGraphUtils } from "./public/pool-graph-utils"; /** * A pool graph implementation using an adjacency list. * * Whirlpools (Pools (edges) & Tokens (nodes)) are sparse graphs concentrated on popular pairs such as SOL, USDC etc. * Therefore this implementation is more efficient in memory consumption & building than a matrix. * * TODO: This implementation does not support 2-edge paths between identical tokens. */ export class AdjacencyListPoolGraph implements PoolGraph { readonly graph: Readonly<AdjacencyPoolGraphMap>; readonly tokens: Readonly<Address[]>; constructor(pools: PoolTokenPair[]) { const [adjacencyListGraphMap, insertedTokens] = buildPoolGraph(pools); this.graph = adjacencyListGraphMap; this.tokens = Array.from(insertedTokens); } getPath( startMint: Address, endMint: Address, options?: PathSearchOptions, ): Path[] { const results = this.getPathsForPairs([[startMint, endMint]], options); return results[0][1]; } getPathsForPairs( searchTokenPairs: [Address, Address][], options?: PathSearchOptions, ): PathSearchEntries { const searchTokenPairsInString = searchTokenPairs.map( ([startMint, endMint]) => { return [ AddressUtil.toString(startMint), AddressUtil.toString(endMint), ] as const; }, ); const searchTokenPairsToFind = searchTokenPairsInString.filter( ([startMint, endMint]) => { return startMint !== endMint; }, ); const walkMap = findWalks( searchTokenPairsToFind, this.graph, options?.intermediateTokens.map((token) => AddressUtil.toString(token)), ); const results = searchTokenPairsInString.map(([startMint, endMint]) => { const searchRouteId = PoolGraphUtils.getSearchPathId(startMint, endMint); const [internalStartMint, internalEndMint] = [startMint, endMint].sort(); const internalRouteId = getInternalRouteId( internalStartMint, internalEndMint, false, ); const reversed = internalStartMint !== startMint; const pathsForSearchPair = walkMap[internalRouteId]; const paths = pathsForSearchPair ? pathsForSearchPair.map<Path>((path) => { return { startTokenMint: startMint, endTokenMint: endMint, edges: getHopsFromRoute(path, reversed), }; }) : []; return [searchRouteId, paths] as const; }); return results; } getAllPaths(options?: PathSearchOptions | undefined): PathSearchEntries { const tokenPairCombinations = combinations2(this.tokens) as [ string, string, ][]; const searchTokenPairsInString = tokenPairCombinations.map( ([startMint, endMint]) => { return [startMint, endMint] as const; }, ); const searchTokenPairsToFind = searchTokenPairsInString.filter( ([startMint, endMint]) => { return startMint !== endMint; }, ); const walkMap = findWalks( searchTokenPairsToFind, this.graph, options?.intermediateTokens.map((token) => AddressUtil.toString(token)), ); // TODO: The token pairs are is in 1 direction only, we have to reverse them to get the other direction. // this is actually pretty slow.consider removing reversal optimization in findWalks const results = searchTokenPairsInString.reduce<PathSearchEntries>( (acc, [startMint, endMint]) => { const searchRouteId = PoolGraphUtils.getSearchPathId( startMint, endMint, ); // We do not support routes that routes between identical tokens if (startMint === endMint) { acc.push([searchRouteId, []]); return acc; } const [internalStartMint, internalEndMint] = [ startMint, endMint, ].sort(); const internalRouteId = getInternalRouteId( internalStartMint, internalEndMint, false, ); const reversed = internalStartMint !== startMint; const pathsForSearchPair = walkMap[internalRouteId]; const paths = pathsForSearchPair ? pathsForSearchPair.map<Path>((path) => { return { startTokenMint: startMint, endTokenMint: endMint, edges: getHopsFromRoute(path, reversed), }; }) : []; acc.push([searchRouteId, paths]); const reversedSearchRouteId = PoolGraphUtils.getSearchPathId( endMint, startMint, ); const reversedPaths = pathsForSearchPair ? pathsForSearchPair.map<Path>((path) => { return { startTokenMint: endMint, endTokenMint: startMint, edges: getHopsFromRoute(path, !reversed), }; }) : []; acc.push([reversedSearchRouteId, reversedPaths]); return acc; }, [], ); return results; } } function getHopsFromRoute(path: string[], reversed: boolean): Edge[] { const finalRoutes = reversed ? path.slice().reverse() : path; return finalRoutes.map((hopStr) => { return { poolAddress: hopStr }; }); } type AdjacencyPoolGraphMap = Record<string, readonly PoolGraphEdge[]>; type PoolGraphEdge = { address: string; otherToken: string; }; // A record of path-id (tokenA-tokenB) to a list of edges type PoolWalks = Record<string, string[][]>; function buildPoolGraph( pools: PoolTokenPair[], ): readonly [Readonly<AdjacencyPoolGraphMap>, Set<string>] { const insertedPoolCache: Record<string, Set<string>> = {}; const insertedTokens = new Set<string>(); const poolGraphSet = pools.reduce( (poolGraph: Record<string, PoolGraphEdge[]>, pool) => { const { address, tokenMintA, tokenMintB } = pool; const [addr, mintA, mintB] = AddressUtil.toStrings([ address, tokenMintA, tokenMintB, ]); insertedTokens.add(mintA); insertedTokens.add(mintB); if (poolGraph[mintA] === undefined) { poolGraph[mintA] = []; insertedPoolCache[mintA] = new Set<string>(); } if (poolGraph[mintB] === undefined) { poolGraph[mintB] = []; insertedPoolCache[mintB] = new Set<string>(); } const [insertedPoolsForA, insertedPoolsForB] = [ insertedPoolCache[mintA], insertedPoolCache[mintB], ]; if (!insertedPoolsForA.has(addr)) { poolGraph[mintA].push({ address: addr, otherToken: mintB }); insertedPoolsForA.add(addr); } if (!insertedPoolsForB.has(addr)) { poolGraph[mintB].push({ address: addr, otherToken: mintA }); insertedPoolsForB.add(addr); } return poolGraph; }, {}, ); return [poolGraphSet, insertedTokens] as const; } // This is currently hardcoded to find walks of max length 2, generalizing to longer walks // may mean that a adjacency matrix might have better performance // NOTE: that this function does not support routing between the same token on hop length 2. function findWalks( tokenPairs: (readonly [string, string])[], poolGraph: AdjacencyPoolGraphMap, intermediateTokens?: string[], ) { const walks: PoolWalks = {}; tokenPairs.forEach(([tokenMintFrom, tokenMintTo]) => { let paths = []; // Adjust walk's from & to token based of internal path id. const [internalTokenMintFrom, internalTokenMintTo] = [ tokenMintFrom, tokenMintTo, ].sort(); const internalPathId = getInternalRouteId( internalTokenMintFrom, internalTokenMintTo, false, ); const poolsForTokenFrom = poolGraph[internalTokenMintFrom] || []; const poolsForTokenTo = poolGraph[internalTokenMintTo] || []; // If the internal path id has already been created, then there is no need to re-search the path. // Possible that the path was searched in reverse. if (!!walks[internalPathId]) { return; } // Find all direct pool paths, i.e. all edges shared between tokenA and tokenB const singleHop = poolsForTokenFrom .filter(({ address }) => poolsForTokenTo.some((p) => p.address === address), ) .map((op) => [op.address]); paths.push(...singleHop); // Remove all direct edges from poolA to poolB const firstHop = poolsForTokenFrom.filter( ({ address }) => !poolsForTokenTo.some((p) => p.address === address), ); // Find all edges/nodes from neighbors of A that connect to B to create paths of length 2 // tokenA --> tokenX --> tokenB firstHop.forEach((firstPool) => { const intermediateToken = firstPool.otherToken; if ( !intermediateTokens || intermediateTokens.indexOf(intermediateToken) > -1 ) { const secondHops = poolsForTokenTo .filter((secondPool) => secondPool.otherToken === intermediateToken) .map((secondPool) => [firstPool.address, secondPool.address]); paths.push(...secondHops); } }); if (paths.length > 0) { walks[internalPathId] = paths; } }); return walks; } function getInternalRouteId( tokenA: Address, tokenB: Address, sort = true, ): string { const mints = [AddressUtil.toString(tokenA), AddressUtil.toString(tokenB)]; const sortedMints = sort ? mints.sort() : mints; return `${sortedMints[0]}${PoolGraphUtils.PATH_ID_DELIMITER}${sortedMints[1]}`; } // equivalent to lodash.combinations(array, 2) function combinations2<T>(array: Readonly<T[]>): [T, T][] { const result: [T, T][] = []; for (let i = 0; i < array.length - 1; i++) { for (let j = i + 1; j < array.length; j++) { result.push([array[i], array[j]]); } } return result; }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs/public/pool-graph-builder.ts
import type { Address } from "@coral-xyz/anchor"; import type { WhirlpoolAccountFetcherInterface } from "../../../network/public/fetcher"; import { PREFER_CACHE } from "../../../network/public/fetcher"; import { AdjacencyListPoolGraph } from "../adjacency-list-pool-graph"; import type { PoolGraph, PoolTokenPair } from "./pool-graph"; /** * A builder class for creating a {@link PoolGraph} * * Note: we use an adjacency list as a representation of our pool graph, * since we assume that most token pairings don't exist as pools * @category PoolGraph */ export class PoolGraphBuilder { /** * Fetch data and build a {@link PoolGraph} from a list of pools addresses * @param pools - a list of pool addresses to generate this pool graph * @param cache - {@link WhirlpoolAccountFetcherInterface} to use for fetching pool data * @returns A {@link PoolGraph} with the provided pools */ static async buildPoolGraphWithFetch( pools: Address[], fetcher: WhirlpoolAccountFetcherInterface, ): Promise<PoolGraph> { const poolAccounts = await fetcher.getPools(pools, PREFER_CACHE); const poolTokenPairs = Array.from(poolAccounts.entries()) .map(([addr, pool]) => { if (pool) { return { address: addr, tokenMintA: pool.tokenMintA, tokenMintB: pool.tokenMintB, }; } return null; }) .flatMap((pool) => (pool ? pool : [])); return new AdjacencyListPoolGraph(poolTokenPairs); } /** * Build a {@link PoolGraph} from a list of pools in the format of {@link PoolTokenPair} * @param poolTokenPairs - a list of {@link PoolTokenPair} to generate this pool graph * @returns A {@link PoolGraph} with the provided pools */ static buildPoolGraph(poolTokenPairs: PoolTokenPair[]): PoolGraph { return new AdjacencyListPoolGraph(poolTokenPairs); } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs/public/pool-graph-utils.ts
import type { Address } from "@coral-xyz/anchor"; import { AddressUtil } from "@orca-so/common-sdk"; /** * A utility class for working with pool graphs * @category PoolGraph */ export class PoolGraphUtils { static readonly PATH_ID_DELIMITER = "-"; /** * Get a search path id from two tokens. The id can be used to identify a path between the two tokens in {@link PathSearchEntries}. * @param tokenA The first token in the path * @param tokenB The second token in the path * @returns A path id that can be used to identify a path between the two tokens in {@link PathSearchEntries}. */ static getSearchPathId(tokenA: Address, tokenB: Address): string { return `${AddressUtil.toString(tokenA)}${ PoolGraphUtils.PATH_ID_DELIMITER }${AddressUtil.toString(tokenB)}`; } /** * Deconstruct a path id into the two tokens it represents * @param pathId - The path id to deconstruct * @returns A tuple of the two tokens in the path id. Returns undefined if the provided pathId is invalid. */ static deconstructPathId(pathId: string): readonly [string, string] { const split = pathId.split(PoolGraphUtils.PATH_ID_DELIMITER); if (split.length !== 2) { throw new Error(`Invalid path id: ${pathId}`); } const [tokenA, tokenB] = split; return [tokenA, tokenB] as const; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs/public/pool-graph.ts
import type { Address } from "@coral-xyz/anchor"; /** * An object containing the token pairs of a Whirlpool. * @category PoolGraph */ export interface PoolTokenPair { address: Address; tokenMintA: Address; tokenMintB: Address; } /** * Results for a series of graph search queries between two tokens. * The search id for each entry can be obtained from {@link PoolGraphUtils.getSearchRouteId} * If a path exist between tokens for that search id, it will be an array of paths. * If paths do not exist, it will be an empty array. * * @category PoolGraph */ export type PathSearchEntries = (readonly [string, Path[]])[]; /** * A path to trade from start token mint to end token mint. * * @category PoolGraph * @param startMint - The token the path starts with * @param endMint - The token the path ends with * @param edges - An ordered list of edges (pool addresses) that make up the path */ export type Path = { startTokenMint: string; endTokenMint: string; edges: Edge[]; }; /** * A type representing a pool graph edge. * * @category PoolGraph */ export type Edge = { poolAddress: Address; }; /** * Options for finding a path between two tokens * * @category PoolGraph * @param intermediateTokens - A list of tokens that can be used as intermediate hops */ export type PathSearchOptions = { intermediateTokens: Address[]; }; /** * A type representing an undirected graph of pools that can be used to find paths between two tokens. * In this graph, nodes are token mints, and edges are pools * * @category PoolGraph */ export type PoolGraph = { /** * Get a list of paths between two tokens for this pool graph. * * Notes: * - Only support paths with up to 2 edges * - Paths searching between two identical token mints are not supported. * * @param startMint The token the path starts from * @param endMint The token the path ends in * @param options Options for finding a path * @returns A list of path between the two tokens. If no path are found, it will be an empty array. */ getPath: ( startMint: Address, endMint: Address, options?: PathSearchOptions, ) => Path[]; /** * Get a map of paths from a list of token pairs for this pool graph. * * Notes: * - Only support paths with up to 2 edges * - Paths searching between two identical token mints are not supported. * * @param searchTokenPairs A list of token pairs to find paths for. The first token in the pair is the start token, and the second token is the end token. * @param options Options for finding a path * @return An array of search result entires in the same order as the searchTokenPairs. */ getPathsForPairs( searchTokenPairs: [Address, Address][], options?: PathSearchOptions, ): PathSearchEntries; /** * Get a list of all paths for this pool graph. * @param options Options for finding a path * @return An array of all permutations of token-pairs to the paths for each pair. */ getAllPaths(options?: PathSearchOptions): PathSearchEntries; };
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/graphs/public/index.ts
export type * from "./pool-graph"; export * from "./pool-graph-builder"; export * from "./pool-graph-utils";
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/utils/builder/position-builder-util.ts
import type { WhirlpoolContext } from "../.."; import type { WhirlpoolAccountFetchOptions } from "../../network/public/fetcher"; import type { PositionData, WhirlpoolData } from "../../types/public"; import { PDAUtil } from "../public"; export async function getTickArrayDataForPosition( ctx: WhirlpoolContext, position: PositionData, whirlpool: WhirlpoolData, opts?: WhirlpoolAccountFetchOptions, ) { const lowerTickArrayKey = PDAUtil.getTickArrayFromTickIndex( position.tickLowerIndex, whirlpool.tickSpacing, position.whirlpool, ctx.program.programId, ).publicKey; const upperTickArrayKey = PDAUtil.getTickArrayFromTickIndex( position.tickUpperIndex, whirlpool.tickSpacing, position.whirlpool, ctx.program.programId, ).publicKey; return await ctx.fetcher.getTickArrays( [lowerTickArrayKey, upperTickArrayKey], opts, ); }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/errors/errors.ts
export enum MathErrorCode { MultiplicationOverflow = `MultiplicationOverflow`, MulDivOverflow = `MulDivOverflow`, MultiplicationShiftRightOverflow = `MultiplicationShiftRightOverflow`, DivideByZero = `DivideByZero`, } export enum TokenErrorCode { TokenMaxExceeded = `TokenMaxExceeded`, TokenMinSubceeded = `TokenMinSubceeded`, } export enum SwapErrorCode { InvalidDevFeePercentage = `InvalidDevFeePercentage`, InvalidSqrtPriceLimitDirection = `InvalidSqrtPriceLimitDirection`, SqrtPriceOutOfBounds = `SqrtPriceOutOfBounds`, ZeroTradableAmount = `ZeroTradableAmount`, AmountOutBelowMinimum = `AmountOutBelowMinimum`, AmountInAboveMaximum = `AmountInAboveMaximum`, TickArrayCrossingAboveMax = `TickArrayCrossingAboveMax`, TickArrayIndexNotInitialized = `TickArrayIndexNotInitialized`, TickArraySequenceInvalid = `TickArraySequenceInvalid`, AmountRemainingOverflow = `AmountRemainingOverflow`, AmountCalcOverflow = `AmountCalcOverflow`, } export enum RouteQueryErrorCode { RouteDoesNotExist = "RouteDoesNotExist", TradeAmountTooHigh = "TradeAmountTooHigh", ZeroInputAmount = "ZeroInputAmount", General = "General", } export type WhirlpoolsErrorCode = | TokenErrorCode | SwapErrorCode | MathErrorCode | RouteQueryErrorCode; export class WhirlpoolsError extends Error { message: string; errorCode?: WhirlpoolsErrorCode; constructor( message: string, errorCode?: WhirlpoolsErrorCode, stack?: string, ) { super(message); this.message = message; this.errorCode = errorCode; this.stack = stack; } public static isWhirlpoolsErrorCode( e: unknown, code: WhirlpoolsErrorCode, ): boolean { return e instanceof WhirlpoolsError && e.errorCode === code; } }
0
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src
solana_public_repos/orca-so/whirlpools/legacy-sdk/whirlpool/src/router/convert-quote-map.ts
import BN from "bn.js"; import { kSmallestPartition } from "../utils/math/k-smallest-partition"; import type { RoutingOptions, SubTradeRoute, TradeRoute } from "./public"; import type { PathQuote, SanitizedQuoteMap } from "./quote-map"; export function getBestRoutesFromQuoteMap( quoteMap: SanitizedQuoteMap, amountSpecifiedIsInput: boolean, opts: RoutingOptions, ): TradeRoute[] { const { numTopRoutes, maxSplits } = opts; const sortedRoutes = [ ...getRankedRoutes( quoteMap, amountSpecifiedIsInput, numTopRoutes, maxSplits, ), ...getSingleHopSplit(quoteMap), ].sort(getRouteCompareFn(amountSpecifiedIsInput)); return convertInternalRoutesToTradeRoutes(sortedRoutes); } function convertInternalRoutesToTradeRoutes( internalRoutes: InternalRoute[], ): TradeRoute[] { const tradeRoutes: TradeRoute[] = internalRoutes.map((internalRoute) => { const { quotes, totalIn, totalOut } = internalRoute; return { subRoutes: quotes.map((quote) => convertPathQuoteToSubTradeRoute(quote)), totalAmountIn: totalIn, totalAmountOut: totalOut, }; }); return tradeRoutes; } function convertPathQuoteToSubTradeRoute(pathQuote: PathQuote): SubTradeRoute { const { calculatedEdgeQuotes, path, splitPercent, amountIn, amountOut } = pathQuote; return { path, splitPercent, amountIn, amountOut, hopQuotes: calculatedEdgeQuotes, }; } type InternalRoute = { quotes: PathQuote[]; splitPercent: number; totalIn: BN; totalOut: BN; }; function getSingleHopSplit(quoteMap: SanitizedQuoteMap): InternalRoute[] { const fullFlow = quoteMap[100]; if (fullFlow) { return fullFlow .filter((f) => f.calculatedEdgeQuotes.length == 1) .map((f) => { const oneHop = f.calculatedEdgeQuotes[0]; return { quotes: [f], splitPercent: 100, totalIn: oneHop.amountIn, totalOut: oneHop.amountOut, }; }) .flatMap((g) => (!!g ? g : [])); } return []; } function getRankedRoutes( percentMap: SanitizedQuoteMap, amountSpecifiedIsInput: boolean, topN: number, maxSplits: number, ): InternalRoute[] { let routes = generateRoutes(percentMap, maxSplits); // Run quick select algorithm to partition the topN results, mutating inplace const routeCompare = getRouteCompareFn(amountSpecifiedIsInput); if (routes.length <= topN) { return routes.sort(routeCompare); } kSmallestPartition(routes, topN, 0, routes.length - 1, routeCompare); return routes.slice(0, topN).sort(routeCompare); } function generateRoutes( percentMap: SanitizedQuoteMap, maxSplits: number, ): InternalRoute[] { let routes: InternalRoute[] = []; buildRoutes( percentMap, maxSplits, { quotes: [], splitPercent: 0, totalIn: new BN(0), totalOut: new BN(0), }, routes, ); return routes; } function buildRoutes( quotePercentMap: SanitizedQuoteMap, maxSplits: number, currentRoute: InternalRoute, routes: InternalRoute[], ) { const { splitPercent: percent, quotes } = currentRoute; const percents = Object.keys(quotePercentMap).map((percent) => Number(percent), ); for (let i = percents.length - 1; i >= 0; i--) { const nextPercent = percents[i]; const newPercentTotal = percent + nextPercent; // Optimization to prevent exceeding 100% flow and excess combinations of flow by only using decreasing // amounts of flow percentages const nextPercentIsSmaller = quotes.length > 0 && nextPercent > quotes[quotes.length - 1].splitPercent; if (newPercentTotal > 100 || nextPercentIsSmaller) { continue; } const nextPercentQuotes = quotePercentMap[nextPercent]; for (let j = 0; j < nextPercentQuotes.length; j++) { const nextQuote = nextPercentQuotes[j]; // Don't use a quote that shares a pool with an existing quote const hasReusedPools = nextQuote.edgesPoolAddrs.some((r1) => quotes.some((r2) => r2.edgesPoolAddrs.some((r3) => r3.indexOf(r1) !== -1), ), ); if (hasReusedPools) { continue; } // todo: Doesn't take into transaction fees // double-hops, multi-route penalties, benefits for pairs that can share lookup tables const nextRoute: InternalRoute = { quotes: [...quotes, nextQuote], splitPercent: newPercentTotal, totalIn: currentRoute.totalIn.add(nextQuote.amountIn), totalOut: currentRoute.totalOut.add(nextQuote.amountOut), }; // Remove the current and prior routes from consideration const nextCandidateQuotes = nextPercentQuotes.slice(j + 1); if (newPercentTotal === 100) { // If we have reached 100% flow routed, we add it to the set of valid route sets routes.push(nextRoute); } else if (quotes.length + 1 != maxSplits) { // Otherwise, recursively build route sets buildRoutes( { ...quotePercentMap, [nextPercent]: nextCandidateQuotes, }, maxSplits, nextRoute, routes, ); } } } } function getRouteCompareFn(amountSpecifiedIsInput: boolean) { return amountSpecifiedIsInput ? routesCompareForInputAmount : routesCompareForOutputAmount; } function routesCompareForInputAmount(a: InternalRoute, b: InternalRoute) { return b.totalOut.cmp(a.totalOut); } function routesCompareForOutputAmount(a: InternalRoute, b: InternalRoute) { return a.totalIn.cmp(b.totalIn); }
0