{"version":3,"sources":["../src/index.ts","../src/context.ts","../src/network/public/fetcher.ts","../src/network/public/parsing.ts","../src/types/public/constants.ts","../src/types/public/anchor-types.ts","../src/instructions/close-position-ix.ts","../src/instructions/collect-fees-ix.ts","../src/instructions/collect-protocol-fees-ix.ts","../src/instructions/collect-reward-ix.ts","../src/instructions/composites/collect-all-txn.ts","../src/ix.ts","../src/utils/public/ix-utils.ts","../src/utils/public/pda-utils.ts","../src/utils/public/price-math.ts","../src/utils/public/tick-utils.ts","../src/utils/public/pool-utils.ts","../src/utils/public/types.ts","../src/utils/public/swap-utils.ts","../src/utils/spl-token-utils.ts","../src/utils/txn-utils.ts","../src/utils/whirlpool-ata-utils.ts","../src/instructions/update-fees-and-rewards-ix.ts","../src/instructions/decrease-liquidity-ix.ts","../src/instructions/increase-liquidity-ix.ts","../src/instructions/initialize-config-ix.ts","../src/instructions/initialize-fee-tier-ix.ts","../src/instructions/initialize-pool-ix.ts","../src/instructions/initialize-reward-ix.ts","../src/instructions/initialize-tick-array-ix.ts","../src/instructions/open-position-ix.ts","../src/utils/instructions-util.ts","../src/instructions/set-collect-protocol-fees-authority-ix.ts","../src/instructions/set-default-fee-rate-ix.ts","../src/instructions/set-default-protocol-fee-rate-ix.ts","../src/instructions/set-fee-authority-ix.ts","../src/instructions/set-fee-rate-ix.ts","../src/instructions/set-protocol-fee-rate-ix.ts","../src/instructions/set-reward-authority-by-super-authority-ix.ts","../src/instructions/set-reward-authority-ix.ts","../src/instructions/set-reward-emissions-ix.ts","../src/instructions/set-reward-emissions-super-authority-ix.ts","../src/instructions/swap-ix.ts","../src/impl/position-impl.ts","../src/utils/builder/position-builder-util.ts","../src/quotes/public/increase-liquidity-quote.ts","../src/utils/position-util.ts","../src/utils/swap-utils.ts","../src/quotes/public/decrease-liquidity-quote.ts","../src/quotes/public/collect-fees-quote.ts","../src/quotes/public/collect-rewards-quote.ts","../src/quotes/public/swap-quote.ts","../src/quotes/swap/swap-quote-impl.ts","../src/errors/errors.ts","../src/quotes/swap/tick-array-index.ts","../src/quotes/swap/tick-array-sequence.ts","../src/quotes/swap/swap-manager.ts","../src/utils/math/swap-math.ts","../src/utils/math/token-math.ts","../src/utils/math/bit-math.ts","../src/quotes/public/dev-fee-swap-quote.ts","../src/impl/whirlpool-client-impl.ts","../src/impl/util.ts","../src/impl/whirlpool-impl.ts","../src/whirlpool-client.ts"],"sourcesContent":["import Decimal from \"decimal.js\";\n\nexport * from \"./context\";\nexport * from \"./impl/position-impl\";\nexport * from \"./ix\";\nexport * from \"./network/public\";\nexport * from \"./quotes/public\";\nexport * from \"./types/public\";\nexport * from \"./types/public/anchor-types\";\nexport * from \"./utils/public\";\nexport * from \"./whirlpool-client\";\nexport { Percentage } from \"@orca-so/common-sdk\";\n\n// Global rules for Decimals\n//  - 40 digits of precision for the largest number\n//  - 20 digits of precision for the smallest number\n//  - Always round towards 0 to mirror smart contract rules\nDecimal.set({ precision: 40, toExpPos: 40, toExpNeg: -20, rounding: 1 });\n","import { AnchorProvider, Idl, Program } from \"@project-serum/anchor\";\nimport { Wallet } from \"@project-serum/anchor/dist/cjs/provider\";\nimport { ConfirmOptions, Connection, PublicKey } from \"@solana/web3.js\";\nimport { Whirlpool } from \"./artifacts/whirlpool\";\nimport WhirlpoolIDL from \"./artifacts/whirlpool.json\";\nimport { AccountFetcher } from \"./network/public\";\n/**\n * @category Core\n */\nexport class WhirlpoolContext {\n  readonly connection: Connection;\n  readonly wallet: Wallet;\n  readonly opts: ConfirmOptions;\n  readonly program: Program<Whirlpool>;\n  readonly provider: AnchorProvider;\n  readonly fetcher: AccountFetcher;\n\n  public static from(\n    connection: Connection,\n    wallet: Wallet,\n    programId: PublicKey,\n    fetcher = new AccountFetcher(connection),\n    opts: ConfirmOptions = AnchorProvider.defaultOptions()\n  ): WhirlpoolContext {\n    const anchorProvider = new AnchorProvider(connection, wallet, opts);\n    const program = new Program(WhirlpoolIDL as Idl, programId, anchorProvider);\n    return new WhirlpoolContext(anchorProvider, anchorProvider.wallet, program, fetcher, opts);\n  }\n\n  public static fromWorkspace(\n    provider: AnchorProvider,\n    program: Program,\n    fetcher = new AccountFetcher(provider.connection),\n    opts: ConfirmOptions = AnchorProvider.defaultOptions()\n  ) {\n    return new WhirlpoolContext(provider, provider.wallet, program, fetcher, opts);\n  }\n\n  public static withProvider(\n    provider: AnchorProvider,\n    programId: PublicKey,\n    fetcher = new AccountFetcher(provider.connection),\n    opts: ConfirmOptions = AnchorProvider.defaultOptions()\n  ): WhirlpoolContext {\n    const program = new Program(WhirlpoolIDL as Idl, programId, provider);\n    return new WhirlpoolContext(provider, provider.wallet, program, fetcher, opts);\n  }\n\n  public constructor(\n    provider: AnchorProvider,\n    wallet: Wallet,\n    program: Program,\n    fetcher: AccountFetcher,\n    opts: ConfirmOptions\n  ) {\n    this.connection = provider.connection;\n    this.wallet = wallet;\n    this.opts = opts;\n    // It's a hack but it works on Anchor workspace *shrug*\n    this.program = program as unknown as Program<Whirlpool>;\n    this.provider = provider;\n    this.fetcher = fetcher;\n  }\n\n  // TODO: Add another factory method to build from on-chain IDL\n}\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport invariant from \"tiny-invariant\";\nimport { AccountInfo, AccountLayout, MintInfo } from \"@solana/spl-token\";\nimport {\n  ParsableEntity,\n  ParsableFeeTier,\n  ParsableMintInfo,\n  ParsablePosition,\n  ParsableTickArray,\n  ParsableTokenInfo,\n  ParsableWhirlpool,\n  ParsableWhirlpoolsConfig,\n} from \"./parsing\";\nimport { Address } from \"@project-serum/anchor\";\nimport {\n  PositionData,\n  TickArrayData,\n  WhirlpoolsConfigData,\n  WhirlpoolData,\n  WHIRLPOOL_ACCOUNT_SIZE,\n  WHIRLPOOL_CODER,\n  AccountName,\n} from \"../..\";\nimport { FeeTierData } from \"../../types/public\";\nimport { AddressUtil } from \"@orca-so/common-sdk\";\n\n/**\n * Supported accounts\n */\ntype CachedValue =\n  | WhirlpoolsConfigData\n  | WhirlpoolData\n  | PositionData\n  | TickArrayData\n  | FeeTierData\n  | AccountInfo\n  | MintInfo;\n\n/**\n * Include both the entity (i.e. type) of the stored value, and the value itself\n */\ninterface CachedContent<T extends CachedValue> {\n  entity: ParsableEntity<T>;\n  value: CachedValue | null;\n}\n\n/**\n * Type for rpc batch request response\n */\ntype GetMultipleAccountsResponse = {\n  error?: string;\n  result?: {\n    value?: ({ data: [string, string] } | null)[];\n  };\n};\n\n/**\n * Filter params for Whirlpools when invoking getProgramAccounts.\n */\ntype ListWhirlpoolParams = {\n  programId: Address;\n  configId: Address;\n};\n\n/**\n * Tuple containing Whirlpool address and parsed account data.\n */\ntype WhirlpoolAccount = [Address, WhirlpoolData];\n\n/**\n * Data access layer to access Whirlpool related accounts\n * Includes internal cache that can be refreshed by the client.\n *\n * @category Core\n */\nexport class AccountFetcher {\n  private readonly connection: Connection;\n  private readonly _cache: Record<string, CachedContent<CachedValue>> = {};\n  private _accountRentExempt: number | undefined;\n\n  constructor(connection: Connection, cache?: Record<string, CachedContent<CachedValue>>) {\n    this.connection = connection;\n    this._cache = cache ?? {};\n  }\n\n  /*** Public Methods ***/\n\n  /**\n   * Retrieve minimum balance for rent exemption of a Token Account;\n   *\n   * @param refresh force refresh of account rent exemption\n   * @returns minimum balance for rent exemption\n   */\n  public async getAccountRentExempt(refresh: boolean = false) {\n    // This value should be relatively static or at least not break according to spec\n    // https://docs.solana.com/developing/programming-model/accounts#rent-exemption\n    if (!this._accountRentExempt || refresh) {\n      this._accountRentExempt = await this.connection.getMinimumBalanceForRentExemption(\n        AccountLayout.span\n      );\n    }\n    return this._accountRentExempt;\n  }\n\n  /**\n   * Retrieve a cached whirlpool account. Fetch from rpc on cache miss.\n   *\n   * @param address whirlpool address\n   * @param refresh force cache refresh\n   * @returns whirlpool account\n   */\n  public async getPool(address: Address, refresh = false): Promise<WhirlpoolData | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableWhirlpool, refresh);\n  }\n\n  /**\n   * Retrieve a cached position account. Fetch from rpc on cache miss.\n   *\n   * @param address position address\n   * @param refresh force cache refresh\n   * @returns position account\n   */\n  public async getPosition(address: Address, refresh = false): Promise<PositionData | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsablePosition, refresh);\n  }\n\n  /**\n   * Retrieve a cached tick array account. Fetch from rpc on cache miss.\n   *\n   * @param address tick array address\n   * @param refresh force cache refresh\n   * @returns tick array account\n   */\n  public async getTickArray(address: Address, refresh = false): Promise<TickArrayData | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableTickArray, refresh);\n  }\n\n  /**\n   * Retrieve a cached fee tier account. Fetch from rpc on cache miss.\n   *\n   * @param address fee tier address\n   * @param refresh force cache refresh\n   * @returns fee tier account\n   */\n  public async getFeeTier(address: Address, refresh = false): Promise<FeeTierData | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableFeeTier, refresh);\n  }\n\n  /**\n   * Retrieve a cached token info account. Fetch from rpc on cache miss.\n   *\n   * @param address token info address\n   * @param refresh force cache refresh\n   * @returns token info account\n   */\n  public async getTokenInfo(address: Address, refresh = false): Promise<AccountInfo | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableTokenInfo, refresh);\n  }\n\n  /**\n   * Retrieve a cached mint info account. Fetch from rpc on cache miss.\n   *\n   * @param address mint info address\n   * @param refresh force cache refresh\n   * @returns mint info account\n   */\n  public async getMintInfo(address: Address, refresh = false): Promise<MintInfo | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableMintInfo, refresh);\n  }\n\n  /**\n   * Retrieve a cached whirlpool config account. Fetch from rpc on cache miss.\n   *\n   * @param address whirlpool config address\n   * @param refresh force cache refresh\n   * @returns whirlpool config account\n   */\n  public async getConfig(address: Address, refresh = false): Promise<WhirlpoolsConfigData | null> {\n    return this.get(AddressUtil.toPubKey(address), ParsableWhirlpoolsConfig, refresh);\n  }\n\n  /**\n   * Retrieve a list of cached whirlpool accounts. Fetch from rpc for cache misses.\n   *\n   * @param addresses whirlpool addresses\n   * @param refresh force cache refresh\n   * @returns whirlpool accounts\n   */\n  public async listPools(\n    addresses: Address[],\n    refresh: boolean\n  ): Promise<(WhirlpoolData | null)[]> {\n    return this.list(AddressUtil.toPubKeys(addresses), ParsableWhirlpool, refresh);\n  }\n\n  /**\n   * Retrieve a list of cached whirlpool addresses and accounts filtered by the given params using\n   * getProgramAccounts.\n   *\n   * @param params whirlpool filter params\n   * @returns tuple of whirlpool addresses and accounts\n   */\n  public async listPoolsWithParams({\n    programId,\n    configId,\n  }: ListWhirlpoolParams): Promise<WhirlpoolAccount[]> {\n    const filters = [\n      { dataSize: WHIRLPOOL_ACCOUNT_SIZE },\n      {\n        memcmp: WHIRLPOOL_CODER.memcmp(\n          AccountName.Whirlpool,\n          AddressUtil.toPubKey(configId).toBuffer()\n        ),\n      },\n    ];\n\n    const accounts = await this.connection.getProgramAccounts(AddressUtil.toPubKey(programId), {\n      filters,\n    });\n\n    const parsedAccounts: WhirlpoolAccount[] = [];\n    accounts.forEach(({ pubkey, account }) => {\n      const parsedAccount = ParsableWhirlpool.parse(account.data);\n      invariant(!!parsedAccount, `could not parse whirlpool: ${pubkey.toBase58()}`);\n      parsedAccounts.push([pubkey, parsedAccount]);\n      this._cache[pubkey.toBase58()] = { entity: ParsableWhirlpool, value: parsedAccount };\n    });\n\n    return parsedAccounts;\n  }\n\n  /**\n   * Retrieve a list of cached position accounts. Fetch from rpc for cache misses.\n   *\n   * @param addresses position addresses\n   * @param refresh force cache refresh\n   * @returns position accounts\n   */\n  public async listPositions(\n    addresses: Address[],\n    refresh: boolean\n  ): Promise<(PositionData | null)[]> {\n    return this.list(AddressUtil.toPubKeys(addresses), ParsablePosition, refresh);\n  }\n\n  /**\n   * Retrieve a list of cached tick array accounts. Fetch from rpc for cache misses.\n   *\n   * @param addresses tick array addresses\n   * @param refresh force cache refresh\n   * @returns tick array accounts\n   */\n  public async listTickArrays(\n    addresses: Address[],\n    refresh: boolean\n  ): Promise<(TickArrayData | null)[]> {\n    return this.list(AddressUtil.toPubKeys(addresses), ParsableTickArray, refresh);\n  }\n\n  /**\n   * Retrieve a list of cached token info accounts. Fetch from rpc for cache misses.\n   *\n   * @param addresses token info addresses\n   * @param refresh force cache refresh\n   * @returns token info accounts\n   */\n  public async listTokenInfos(\n    addresses: Address[],\n    refresh: boolean\n  ): Promise<(AccountInfo | null)[]> {\n    return this.list(AddressUtil.toPubKeys(addresses), ParsableTokenInfo, refresh);\n  }\n\n  /**\n   * Retrieve a list of cached mint info accounts. Fetch from rpc for cache misses.\n   *\n   * @param addresses mint info addresses\n   * @param refresh force cache refresh\n   * @returns mint info accounts\n   */\n  public async listMintInfos(addresses: Address[], refresh: boolean): Promise<(MintInfo | null)[]> {\n    return this.list(AddressUtil.toPubKeys(addresses), ParsableMintInfo, refresh);\n  }\n\n  /**\n   * Update the cached value of all entities currently in the cache.\n   * Uses batched rpc request for network efficient fetch.\n   */\n  public async refreshAll(): Promise<void> {\n    const addresses: string[] = Object.keys(this._cache);\n    const data = await this.bulkRequest(addresses);\n\n    for (const [idx, [key, cachedContent]] of Object.entries(this._cache).entries()) {\n      const entity = cachedContent.entity;\n      const value = entity.parse(data[idx]);\n\n      this._cache[key] = { entity, value };\n    }\n  }\n\n  /*** Private Methods ***/\n\n  /**\n   * Retrieve from cache or fetch from rpc, an account\n   */\n  private async get<T extends CachedValue>(\n    address: PublicKey,\n    entity: ParsableEntity<T>,\n    refresh: boolean\n  ): Promise<T | null> {\n    const key = address.toBase58();\n    const cachedValue: CachedValue | null | undefined = this._cache[key]?.value;\n\n    if (cachedValue !== undefined && !refresh) {\n      return cachedValue as T | null;\n    }\n\n    const accountInfo = await this.connection.getAccountInfo(address);\n    const accountData = accountInfo?.data;\n    const value = entity.parse(accountData);\n    this._cache[key] = { entity, value };\n\n    return value;\n  }\n\n  /**\n   * Retrieve from cache or fetch from rpc, a list of accounts\n   */\n  private async list<T extends CachedValue>(\n    addresses: PublicKey[],\n    entity: ParsableEntity<T>,\n    refresh: boolean\n  ): Promise<(T | null)[]> {\n    const keys = addresses.map((address) => address.toBase58());\n    const cachedValues: [string, CachedValue | null | undefined][] = keys.map((key) => [\n      key,\n      refresh ? undefined : this._cache[key]?.value,\n    ]);\n\n    /* Look for accounts not found in cache */\n    const undefinedAccounts: { cacheIndex: number; key: string }[] = [];\n    cachedValues.forEach(([key, value], cacheIndex) => {\n      if (value === undefined) {\n        undefinedAccounts.push({ cacheIndex, key });\n      }\n    });\n\n    /* Fetch accounts not found in cache */\n    if (undefinedAccounts.length > 0) {\n      const data = await this.bulkRequest(undefinedAccounts.map((account) => account.key));\n      undefinedAccounts.forEach(({ cacheIndex, key }, dataIndex) => {\n        const value = entity.parse(data[dataIndex]);\n        invariant(cachedValues[cacheIndex]?.[1] === undefined, \"unexpected non-undefined value\");\n        cachedValues[cacheIndex] = [key, value];\n        this._cache[key] = { entity, value };\n      });\n    }\n\n    const result = cachedValues\n      .map(([_, value]) => value)\n      .filter((value): value is T | null => value !== undefined);\n    invariant(result.length === addresses.length, \"not enough results fetched\");\n    return result;\n  }\n\n  /**\n   * Make batch rpc request\n   */\n  private async bulkRequest(addresses: string[]): Promise<(Buffer | null)[]> {\n    const responses: Promise<GetMultipleAccountsResponse>[] = [];\n    const chunk = 100; // getMultipleAccounts has limitation of 100 accounts per request\n\n    for (let i = 0; i < addresses.length; i += chunk) {\n      const addressesSubset = addresses.slice(i, i + chunk);\n      const res = (this.connection as any)._rpcRequest(\"getMultipleAccounts\", [\n        addressesSubset,\n        { commitment: this.connection.commitment },\n      ]);\n      responses.push(res);\n    }\n\n    const combinedResult: (Buffer | null)[] = [];\n\n    (await Promise.all(responses)).forEach((res) => {\n      invariant(!res.error, `bulkRequest result error: ${res.error}`);\n      invariant(!!res.result?.value, \"bulkRequest no value\");\n\n      res.result.value.forEach((account) => {\n        if (!account || account.data[1] !== \"base64\") {\n          combinedResult.push(null);\n        } else {\n          combinedResult.push(Buffer.from(account.data[0], account.data[1]));\n        }\n      });\n    });\n\n    invariant(combinedResult.length === addresses.length, \"bulkRequest not enough results\");\n    return combinedResult;\n  }\n}\n","import { AccountInfo, MintInfo, MintLayout, u64 } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport {\n  WhirlpoolsConfigData,\n  WhirlpoolData,\n  PositionData,\n  TickArrayData,\n  AccountName,\n  FeeTierData,\n} from \"../../types/public\";\nimport { BorshAccountsCoder, Idl } from \"@project-serum/anchor\";\nimport * as WhirlpoolIDL from \"../../artifacts/whirlpool.json\";\nimport { TokenUtil } from \"@orca-so/common-sdk\";\n\n/**\n * Static abstract class definition to parse entities.\n * @category Parsables\n */\nexport interface ParsableEntity<T> {\n  /**\n   * Parse account data\n   *\n   * @param accountData Buffer data for the entity\n   * @returns Parsed entity\n   */\n  parse: (accountData: Buffer | undefined | null) => T | null;\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<WhirlpoolsConfigData>>()\nexport class ParsableWhirlpoolsConfig {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): WhirlpoolsConfigData | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return parseAnchorAccount(AccountName.WhirlpoolsConfig, data);\n    } catch (e) {\n      console.error(`error while parsing WhirlpoolsConfig: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<WhirlpoolData>>()\nexport class ParsableWhirlpool {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): WhirlpoolData | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return parseAnchorAccount(AccountName.Whirlpool, data);\n    } catch (e) {\n      console.error(`error while parsing Whirlpool: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<PositionData>>()\nexport class ParsablePosition {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): PositionData | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return parseAnchorAccount(AccountName.Position, data);\n    } catch (e) {\n      console.error(`error while parsing Position: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<TickArrayData>>()\nexport class ParsableTickArray {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): TickArrayData | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return parseAnchorAccount(AccountName.TickArray, data);\n    } catch (e) {\n      console.error(`error while parsing TickArray: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<FeeTierData>>()\nexport class ParsableFeeTier {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): FeeTierData | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return parseAnchorAccount(AccountName.FeeTier, data);\n    } catch (e) {\n      console.error(`error while parsing FeeTier: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<AccountInfo>>()\nexport class ParsableTokenInfo {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): AccountInfo | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      return TokenUtil.deserializeTokenAccount(data);\n    } catch (e) {\n      console.error(`error while parsing TokenAccount: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * @category Parsables\n */\n@staticImplements<ParsableEntity<MintInfo>>()\nexport class ParsableMintInfo {\n  private constructor() {}\n\n  public static parse(data: Buffer | undefined | null): MintInfo | null {\n    if (!data) {\n      return null;\n    }\n\n    try {\n      const buffer = MintLayout.decode(data);\n      const mintInfo: MintInfo = {\n        mintAuthority:\n          buffer.mintAuthorityOption === 0 ? null : new PublicKey(buffer.mintAuthority),\n        supply: u64.fromBuffer(buffer.supply),\n        decimals: buffer.decimals,\n        isInitialized: buffer.isInitialized !== 0,\n        freezeAuthority:\n          buffer.freezeAuthority === 0 ? null : new PublicKey(buffer.freezeAuthority),\n      };\n\n      return mintInfo;\n    } catch (e) {\n      console.error(`error while parsing MintInfo: ${e}`);\n      return null;\n    }\n  }\n}\n\n/**\n * Class decorator to define an interface with static methods\n * Reference: https://github.com/Microsoft/TypeScript/issues/13462#issuecomment-295685298\n */\nfunction staticImplements<T>() {\n  return <U extends T>(constructor: U) => {\n    constructor;\n  };\n}\n\nconst WhirlpoolCoder = new BorshAccountsCoder(WhirlpoolIDL as Idl);\n\nfunction parseAnchorAccount(accountName: AccountName, data: Buffer) {\n  const discriminator = BorshAccountsCoder.accountDiscriminator(accountName);\n  if (discriminator.compare(data.slice(0, 8))) {\n    console.error(\"incorrect account name during parsing\");\n    return null;\n  }\n\n  try {\n    return WhirlpoolCoder.decode(accountName, data);\n  } catch (_e) {\n    console.error(\"unknown account name during parsing\");\n    return null;\n  }\n}\n","import { BN } from \"@project-serum/anchor\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Program ID hosting Orca's Whirlpool program.\n * @category Constants\n */\nexport const ORCA_WHIRLPOOL_PROGRAM_ID = new PublicKey(\n  \"whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc\"\n);\n\n/**\n * Orca's WhirlpoolsConfig PublicKey.\n * @category Constants\n */\nexport const ORCA_WHIRLPOOLS_CONFIG = new PublicKey(\"2LecshUwdy9xi7meFgHtFJQNSKk4KdTrcpvaB56dP2NQ\");\n\n/**\n * The number of rewards supported by this whirlpool.\n * @category Constants\n */\nexport const NUM_REWARDS = 3;\n\n/**\n * The maximum tick index supported by the Whirlpool program.\n * @category Constants\n */\nexport const MAX_TICK_INDEX = 443636;\n\n/**\n * The minimum tick index supported by the Whirlpool program.\n * @category Constants\n */\nexport const MIN_TICK_INDEX = -443636;\n\n/**\n * The maximum sqrt-price supported by the Whirlpool program.\n * @category Constants\n */\nexport const MAX_SQRT_PRICE = \"79226673515401279992447579055\";\n\n/**\n * The minimum sqrt-price supported by the Whirlpool program.\n * @category Constants\n */\nexport const MIN_SQRT_PRICE = \"4295048016\";\n\n/**\n * The number of initialized ticks that a tick-array account can hold.\n * @category Constants\n */\nexport const TICK_ARRAY_SIZE = 88;\n\n/**\n * @category Constants\n */\nexport const METADATA_PROGRAM_ADDRESS = new PublicKey(\n  \"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s\"\n);\n\n/**\n * The maximum number of tick-arrays that can traversed across in a swap.\n * @category Constants\n */\nexport const MAX_SWAP_TICK_ARRAYS = 3;\n\n/**\n * The denominator which the protocol fee rate is divided on.\n * @category Constants\n */\nexport const PROTOCOL_FEE_RATE_MUL_VALUE = new BN(10_000);\n\n/**\n * The denominator which the fee rate is divided on.\n * @category Constants\n */\nexport const FEE_RATE_MUL_VALUE = new BN(1_000_000);\n","import { BN, BorshAccountsCoder, Idl } from \"@project-serum/anchor\";\nimport WhirlpoolIDL from \"../../artifacts/whirlpool.json\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * This file contains the types that has the same structure as the types anchor functions returns.\n * These types are hard-casted by the client function.\n *\n * This file must be manually updated every time the idl updates as accounts will\n * be hard-casted to fit the type.\n */\n\n/**\n * Supported parasable account names from the Whirlpool contract.\n * @category Parsables\n */\nexport enum AccountName {\n  WhirlpoolsConfig = \"WhirlpoolsConfig\",\n  Position = \"Position\",\n  TickArray = \"TickArray\",\n  Whirlpool = \"Whirlpool\",\n  FeeTier = \"FeeTier\",\n}\n\nconst IDL = WhirlpoolIDL as Idl;\nexport const WHIRLPOOL_CODER = new BorshAccountsCoder(IDL);\n\n/**\n * Size of the Whirlpool account in bytes.\n */\nexport const WHIRLPOOL_ACCOUNT_SIZE = WHIRLPOOL_CODER.size(IDL.accounts![4]);\n\n/**\n * @category Solana Accounts\n */\nexport type WhirlpoolsConfigData = {\n  feeAuthority: PublicKey;\n  collectProtocolFeesAuthority: PublicKey;\n  rewardEmissionsSuperAuthority: PublicKey;\n  defaultFeeRate: number;\n  defaultProtocolFeeRate: number;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type WhirlpoolRewardInfoData = {\n  mint: PublicKey;\n  vault: PublicKey;\n  authority: PublicKey;\n  emissionsPerSecondX64: BN;\n  growthGlobalX64: BN;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type WhirlpoolBumpsData = {\n  whirlpoolBump: number;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type WhirlpoolData = {\n  whirlpoolsConfig: PublicKey;\n  whirlpoolBump: number[];\n  feeRate: number;\n  protocolFeeRate: number;\n  liquidity: BN;\n  sqrtPrice: BN;\n  tickCurrentIndex: number;\n  protocolFeeOwedA: BN;\n  protocolFeeOwedB: BN;\n  tokenMintA: PublicKey;\n  tokenVaultA: PublicKey;\n  feeGrowthGlobalA: BN;\n  tokenMintB: PublicKey;\n  tokenVaultB: PublicKey;\n  feeGrowthGlobalB: BN;\n  rewardLastUpdatedTimestamp: BN;\n  rewardInfos: WhirlpoolRewardInfoData[];\n  tickSpacing: number;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type TickArrayData = {\n  whirlpool: PublicKey;\n  startTickIndex: number;\n  ticks: TickData[];\n};\n\n/**\n * @category Solana Accounts\n */\nexport type TickData = {\n  initialized: boolean;\n  liquidityNet: BN;\n  liquidityGross: BN;\n  feeGrowthOutsideA: BN;\n  feeGrowthOutsideB: BN;\n  rewardGrowthsOutside: BN[];\n};\n\n/**\n * @category Solana Accounts\n */\nexport type PositionRewardInfoData = {\n  growthInsideCheckpoint: BN;\n  amountOwed: BN;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type OpenPositionBumpsData = {\n  positionBump: number;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type OpenPositionWithMetadataBumpsData = {\n  positionBump: number;\n  metadataBump: number;\n};\n\n/**\n * @category Solana Accounts\n */\nexport type PositionData = {\n  whirlpool: PublicKey;\n  positionMint: PublicKey;\n  liquidity: BN;\n  tickLowerIndex: number;\n  tickUpperIndex: number;\n  feeGrowthCheckpointA: BN;\n  feeOwedA: BN;\n  feeGrowthCheckpointB: BN;\n  feeOwedB: BN;\n  rewardInfos: PositionRewardInfoData[];\n};\n\n/**\n * @category Solana Accounts\n */\nexport type FeeTierData = {\n  whirlpoolsConfig: PublicKey;\n  tickSpacing: number;\n  defaultFeeRate: number;\n};\n","import { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\n\n/**\n * Parameters to close a position in a Whirlpool.\n *\n * @category Instruction Types\n * @param receiver - PublicKey for the wallet that will receive the rented lamports.\n * @param position - PublicKey for the position.\n * @param positionMint - PublicKey for the mint token for the Position token.\n * @param positionTokenAccount - The associated token address for the position token in the owners wallet.\n * @param positionAuthority - Authority that owns the position token.\n */\nexport type ClosePositionParams = {\n  receiver: PublicKey;\n  position: PublicKey;\n  positionMint: PublicKey;\n  positionTokenAccount: PublicKey;\n  positionAuthority: PublicKey;\n};\n\n/**\n * Close a position in a Whirlpool. Burns the position token in the owner's wallet.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - ClosePositionParams object\n * @returns - Instruction to perform the action.\n */\nexport function closePositionIx(\n  program: Program<Whirlpool>,\n  params: ClosePositionParams\n): Instruction {\n  const {\n    positionAuthority,\n    receiver: receiver,\n    position: position,\n    positionMint: positionMint,\n    positionTokenAccount,\n  } = params;\n\n  const ix = program.instruction.closePosition({\n    accounts: {\n      positionAuthority,\n      receiver,\n      position,\n      positionMint,\n      positionTokenAccount,\n      tokenProgram: TOKEN_PROGRAM_ID,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to collect fees from a position.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param position - PublicKey for the  position will be opened for.\n * @param positionTokenAccount - PublicKey for the position token's associated token address.\n * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from.\n * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from.\n * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.\n * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.\n * @param positionAuthority - authority that owns the token corresponding to this desired position.\n */\nexport type CollectFeesParams = {\n  whirlpool: PublicKey;\n  position: PublicKey;\n  positionTokenAccount: PublicKey;\n  tokenOwnerAccountA: PublicKey;\n  tokenOwnerAccountB: PublicKey;\n  tokenVaultA: PublicKey;\n  tokenVaultB: PublicKey;\n  positionAuthority: PublicKey;\n};\n\n/**\n * Collect fees accrued for this position.\n * Call updateFeesAndRewards before this to update the position to the newest accrued values.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - CollectFeesParams object\n * @returns - Instruction to perform the action.\n */\nexport function collectFeesIx(program: Program<Whirlpool>, params: CollectFeesParams): Instruction {\n  const {\n    whirlpool,\n    positionAuthority,\n    position,\n    positionTokenAccount,\n    tokenOwnerAccountA,\n    tokenOwnerAccountB,\n    tokenVaultA,\n    tokenVaultB,\n  } = params;\n\n  const ix = program.instruction.collectFees({\n    accounts: {\n      whirlpool,\n      positionAuthority,\n      position,\n      positionTokenAccount,\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA,\n      tokenVaultB,\n      tokenProgram: TOKEN_PROGRAM_ID,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to collect protocol fees for a Whirlpool\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.\n * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.\n * @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet\n * @param tokenOwnerAccountB - PublicKey for the associated token account for tokenA in the collection wallet\n * @param collectProtocolFeesAuthority - assigned authority in the WhirlpoolsConfig that can collect protocol fees\n */\nexport type CollectProtocolFeesParams = {\n  whirlpoolsConfig: PublicKey;\n  whirlpool: PublicKey;\n  tokenVaultA: PublicKey;\n  tokenVaultB: PublicKey;\n  tokenOwnerAccountA: PublicKey;\n  tokenOwnerAccountB: PublicKey;\n  collectProtocolFeesAuthority: PublicKey;\n};\n\n/**\n * Collect protocol fees accrued in this Whirlpool.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - CollectProtocolFeesParams object\n * @returns - Instruction to perform the action.\n */\nexport function collectProtocolFeesIx(\n  program: Program<Whirlpool>,\n  params: CollectProtocolFeesParams\n): Instruction {\n  const {\n    whirlpoolsConfig,\n    whirlpool,\n    collectProtocolFeesAuthority,\n    tokenVaultA,\n    tokenVaultB,\n    tokenOwnerAccountA: tokenDestinationA,\n    tokenOwnerAccountB: tokenDestinationB,\n  } = params;\n\n  const ix = program.instruction.collectProtocolFees({\n    accounts: {\n      whirlpoolsConfig,\n      whirlpool,\n      collectProtocolFeesAuthority,\n      tokenVaultA,\n      tokenVaultB,\n      tokenDestinationA,\n      tokenDestinationB,\n      tokenProgram: TOKEN_PROGRAM_ID,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to collect rewards from a reward index in a position.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param position - PublicKey for the  position will be opened for.\n * @param positionTokenAccount - PublicKey for the position token's associated token address.\n * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).\n * @param rewardOwnerAccount - PublicKey for the reward token account that the reward will deposit into.\n * @param rewardVault - PublicKey of the vault account that reward will be withdrawn from.\n * @param positionAuthority - authority that owns the token corresponding to this desired position.\n */\nexport type CollectRewardParams = {\n  whirlpool: PublicKey;\n  position: PublicKey;\n  positionTokenAccount: PublicKey;\n  rewardIndex: number;\n  rewardOwnerAccount: PublicKey;\n  rewardVault: PublicKey;\n  positionAuthority: PublicKey;\n};\n\n/**\n * Collect rewards accrued for this reward index in a position.\n * Call updateFeesAndRewards before this to update the position to the newest accrued values.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - CollectRewardParams object\n * @returns - Instruction to perform the action.\n */\nexport function collectRewardIx(\n  program: Program<Whirlpool>,\n  params: CollectRewardParams\n): Instruction {\n  const {\n    whirlpool,\n    positionAuthority,\n    position,\n    positionTokenAccount,\n    rewardOwnerAccount,\n    rewardVault,\n    rewardIndex,\n  } = params;\n\n  const ix = program.instruction.collectReward(rewardIndex, {\n    accounts: {\n      whirlpool,\n      positionAuthority,\n      position,\n      positionTokenAccount,\n      rewardOwnerAccount,\n      rewardVault,\n      tokenProgram: TOKEN_PROGRAM_ID,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Instruction, TokenUtil, TransactionBuilder, ZERO } from \"@orca-so/common-sdk\";\nimport { createWSOLAccountInstructions } from \"@orca-so/common-sdk/dist/helpers/token-instructions\";\nimport { Address } from \"@project-serum/anchor\";\nimport { NATIVE_MINT } from \"@solana/spl-token\";\nimport { PACKET_DATA_SIZE, PublicKey } from \"@solana/web3.js\";\nimport { PositionData, WhirlpoolContext } from \"../..\";\nimport { WhirlpoolIx } from \"../../ix\";\nimport { WhirlpoolData } from \"../../types/public\";\nimport { PDAUtil, PoolUtil, TickUtil } from \"../../utils/public\";\nimport { getAssociatedTokenAddressSync } from \"../../utils/spl-token-utils\";\nimport { convertListToMap } from \"../../utils/txn-utils\";\nimport { getTokenMintsFromWhirlpools, resolveAtaForMints } from \"../../utils/whirlpool-ata-utils\";\nimport { updateFeesAndRewardsIx } from \"../update-fees-and-rewards-ix\";\n\n/**\n * Parameters to collect all fees and rewards from a list of positions.\n *\n * @category Instruction Types\n * @param positionAddrs - An array of Whirlpool position addresses.\n * @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key.\n * @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key.\n * @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key.\n * @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key.\n */\nexport type CollectAllPositionAddressParams = {\n  positions: Address[];\n} & CollectAllParams;\n\n/**\n * Parameters to collect all fees and rewards from a list of positions.\n *\n * @category Instruction Types\n * @param positions - An array of Whirlpool positions.\n * @param receiver - The destination wallet that collected fees & reward will be sent to. Defaults to ctx.wallet key.\n * @param positionOwner - The wallet key that contains the position token. Defaults to ctx.wallet key.\n * @param positionAuthority - The authority key that can authorize operation on the position. Defaults to ctx.wallet key.\n * @param payer - The key that will pay for the initialization of ATA token accounts. Defaults to ctx.wallet key.\n */\nexport type CollectAllPositionParams = {\n  positions: Record<string, PositionData>;\n} & CollectAllParams;\n\ntype CollectAllParams = {\n  receiver?: PublicKey;\n  positionOwner?: PublicKey;\n  positionAuthority?: PublicKey;\n  payer?: PublicKey;\n};\n\n/**\n * Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions.\n *\n * @category Instructions\n * @experimental\n * @param ctx - WhirlpoolContext object for the current environment.\n * @param params - CollectAllPositionAddressParams object\n * @param refresh - if true, will always fetch for the latest on-chain data.\n * @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions.\n *          The first transaction should always be processed as it contains all the resolve ATA instructions to receive tokens.\n */\nexport async function collectAllForPositionAddressesTxns(\n  ctx: WhirlpoolContext,\n  params: CollectAllPositionAddressParams,\n  refresh = false\n): Promise<TransactionBuilder[]> {\n  const { positions, ...rest } = params;\n  const posData = convertListToMap(\n    await ctx.fetcher.listPositions(positions, refresh),\n    positions.map((pos) => pos.toString())\n  );\n  const positionMap: Record<string, PositionData> = {};\n  Object.entries(posData).forEach(([addr, pos]) => {\n    if (pos) {\n      positionMap[addr] = pos;\n    }\n  });\n\n  return collectAllForPositionsTxns(ctx, { positions: positionMap, ...rest });\n}\n\n/**\n * Build a set of transactions to collect fees and rewards for a set of Whirlpool Positions.\n *\n * @experimental\n * @param ctx - WhirlpoolContext object for the current environment.\n * @param params - CollectAllPositionParams object\n * @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions.\n */\nexport async function collectAllForPositionsTxns(\n  ctx: WhirlpoolContext,\n  params: CollectAllPositionParams\n): Promise<TransactionBuilder[]> {\n  const { positions, receiver, positionAuthority, positionOwner, payer } = params;\n  const receiverKey = receiver ?? ctx.wallet.publicKey;\n  const positionAuthorityKey = positionAuthority ?? ctx.wallet.publicKey;\n  const positionOwnerKey = positionOwner ?? ctx.wallet.publicKey;\n  const payerKey = payer ?? ctx.wallet.publicKey;\n  const positionList = Object.entries(positions);\n\n  if (positionList.length === 0) {\n    return [];\n  }\n\n  const whirlpoolAddrs = positionList.map(([, pos]) => pos.whirlpool.toBase58());\n  const whirlpoolDatas = await ctx.fetcher.listPools(whirlpoolAddrs, false);\n  const whirlpools = convertListToMap(whirlpoolDatas, whirlpoolAddrs);\n\n  const accountExemption = await ctx.fetcher.getAccountRentExempt();\n  const { ataTokenAddresses: affliatedTokenAtaMap, resolveAtaIxs } = await resolveAtaForMints(ctx, {\n    mints: getTokenMintsFromWhirlpools(whirlpoolDatas).mintMap,\n    accountExemption,\n    receiver: receiverKey,\n    payer: payerKey,\n  });\n\n  const latestBlockhash = await ctx.connection.getLatestBlockhash(\"singleGossip\");\n  const txBuilders: TransactionBuilder[] = [];\n\n  let pendingTxBuilder = new TransactionBuilder(ctx.connection, ctx.wallet).addInstructions(\n    resolveAtaIxs\n  );\n  let pendingTxBuilderTxSize = await pendingTxBuilder.txnSize({ latestBlockhash });\n  let posIndex = 0;\n  let reattempt = false;\n\n  while (posIndex < positionList.length) {\n    const [positionAddr, position] = positionList[posIndex];\n    let positionTxBuilder = new TransactionBuilder(ctx.connection, ctx.wallet);\n    const { whirlpool: whirlpoolKey, positionMint } = position;\n    const whirlpool = whirlpools[whirlpoolKey.toBase58()];\n\n    if (!whirlpool) {\n      throw new Error(\n        `Unable to process positionMint ${positionMint} - unable to derive whirlpool ${whirlpoolKey.toBase58()}`\n      );\n    }\n    const posHandlesNativeMint =\n      TokenUtil.isNativeMint(whirlpool.tokenMintA) || TokenUtil.isNativeMint(whirlpool.tokenMintB);\n    const txBuilderHasNativeMint = !!affliatedTokenAtaMap[NATIVE_MINT.toBase58()];\n\n    // Add NATIVE_MINT token account creation to this transaction if position requires NATIVE_MINT handling.\n    if (posHandlesNativeMint && !txBuilderHasNativeMint) {\n      addNativeMintHandlingIx(\n        positionTxBuilder,\n        affliatedTokenAtaMap,\n        receiverKey,\n        accountExemption\n      );\n    }\n\n    // Build position instructions\n    const collectIxForPosition = constructCollectPositionIx(\n      ctx,\n      new PublicKey(positionAddr),\n      position,\n      whirlpools,\n      positionOwnerKey,\n      positionAuthorityKey,\n      affliatedTokenAtaMap\n    );\n    positionTxBuilder.addInstructions(collectIxForPosition);\n\n    // Attempt to push the new instructions into the pending builder\n    // Iterate to the next position if possible\n    // Create a builder and reattempt if the current one is full.\n    const incrementTxSize = await positionTxBuilder.txnSize({ latestBlockhash });\n    if (pendingTxBuilderTxSize + incrementTxSize < PACKET_DATA_SIZE) {\n      pendingTxBuilder.addInstruction(positionTxBuilder.compressIx(false));\n      pendingTxBuilderTxSize = pendingTxBuilderTxSize + incrementTxSize;\n      posIndex += 1;\n      reattempt = false;\n    } else {\n      if (reattempt) {\n        throw new Error(\n          `Unable to fit collection ix for ${position.positionMint.toBase58()} in a Transaction.`\n        );\n      }\n\n      txBuilders.push(pendingTxBuilder);\n      delete affliatedTokenAtaMap[NATIVE_MINT.toBase58()];\n      pendingTxBuilder = new TransactionBuilder(ctx.connection, ctx.provider.wallet);\n      pendingTxBuilderTxSize = 0;\n      reattempt = true;\n    }\n  }\n\n  txBuilders.push(pendingTxBuilder);\n  return txBuilders;\n}\n\n/**\n * Helper methods.\n */\nfunction addNativeMintHandlingIx(\n  txBuilder: TransactionBuilder,\n  affliatedTokenAtaMap: Record<string, PublicKey>,\n  destinationWallet: PublicKey,\n  accountExemption: number\n) {\n  let { address: wSOLAta, ...resolveWSolIx } = createWSOLAccountInstructions(\n    destinationWallet,\n    ZERO,\n    accountExemption\n  );\n  affliatedTokenAtaMap[NATIVE_MINT.toBase58()] = wSOLAta;\n  txBuilder.prependInstruction(resolveWSolIx);\n}\n\n// TODO: Once individual collect ix for positions is implemented, maybe migrate over if it can take custom ATA?\nconst constructCollectPositionIx = (\n  ctx: WhirlpoolContext,\n  positionKey: PublicKey,\n  position: PositionData,\n  whirlpools: Record<string, WhirlpoolData | null>,\n  positionOwner: PublicKey,\n  positionAuthority: PublicKey,\n  affliatedTokenAtaMap: Record<string, PublicKey>\n) => {\n  const ixForPosition: Instruction[] = [];\n  const {\n    whirlpool: whirlpoolKey,\n    liquidity,\n    tickLowerIndex,\n    tickUpperIndex,\n    positionMint,\n    rewardInfos: positionRewardInfos,\n  } = position;\n  const whirlpool = whirlpools[whirlpoolKey.toBase58()];\n\n  if (!whirlpool) {\n    throw new Error(\n      `Unable to process positionMint ${positionMint} - unable to derive whirlpool ${whirlpoolKey.toBase58()}`\n    );\n  }\n  const { tickSpacing } = whirlpool;\n\n  // Update fee and reward values if necessary\n  if (!liquidity.eq(ZERO)) {\n    ixForPosition.push(\n      updateFeesAndRewardsIx(ctx.program, {\n        position: positionKey,\n        whirlpool: whirlpoolKey,\n        tickArrayLower: PDAUtil.getTickArray(\n          ctx.program.programId,\n          whirlpoolKey,\n          TickUtil.getStartTickIndex(tickLowerIndex, tickSpacing)\n        ).publicKey,\n        tickArrayUpper: PDAUtil.getTickArray(\n          ctx.program.programId,\n          whirlpoolKey,\n          TickUtil.getStartTickIndex(tickUpperIndex, tickSpacing)\n        ).publicKey,\n      })\n    );\n  }\n\n  // Collect Fee\n  const positionTokenAccount = getAssociatedTokenAddressSync(\n    positionMint.toBase58(),\n    positionOwner.toBase58()\n  );\n  ixForPosition.push(\n    WhirlpoolIx.collectFeesIx(ctx.program, {\n      whirlpool: whirlpoolKey,\n      position: positionKey,\n      positionAuthority,\n      positionTokenAccount,\n      tokenOwnerAccountA: affliatedTokenAtaMap[whirlpool.tokenMintA.toBase58()],\n      tokenOwnerAccountB: affliatedTokenAtaMap[whirlpool.tokenMintB.toBase58()],\n      tokenVaultA: whirlpool.tokenVaultA,\n      tokenVaultB: whirlpool.tokenVaultB,\n    })\n  );\n\n  // Collect Rewards\n  // TODO: handle empty vault values?\n  positionRewardInfos.forEach((_, index) => {\n    const rewardInfo = whirlpool.rewardInfos[index];\n    if (PoolUtil.isRewardInitialized(rewardInfo)) {\n      ixForPosition.push(\n        WhirlpoolIx.collectRewardIx(ctx.program, {\n          whirlpool: whirlpoolKey,\n          position: positionKey,\n          positionAuthority,\n          positionTokenAccount,\n          rewardIndex: index,\n          rewardOwnerAccount: affliatedTokenAtaMap[rewardInfo.mint.toBase58()],\n          rewardVault: rewardInfo.vault,\n        })\n      );\n    }\n  });\n\n  return ixForPosition;\n};\n","import { PDA } from \"@orca-so/common-sdk\";\nimport { Program } from \"@project-serum/anchor\";\nimport { WhirlpoolContext } from \".\";\nimport { Whirlpool } from \"./artifacts/whirlpool\";\nimport * as ix from \"./instructions\";\n\n/**\n * Instruction set for the Whirlpools program.\n *\n * @category Core\n */\nexport class WhirlpoolIx {\n  /**\n   * Initializes a WhirlpoolsConfig account that hosts info & authorities\n   * required to govern a set of Whirlpools.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - InitConfigParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static initializeConfigIx(program: Program<Whirlpool>, params: ix.InitConfigParams) {\n    return ix.initializeConfigIx(program, params);\n  }\n\n  /**\n   * Initializes a fee tier account usable by Whirlpools in this WhirlpoolsConfig space.\n   *\n   *  Special Errors\n   * `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - InitFeeTierParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static initializeFeeTierIx(program: Program<Whirlpool>, params: ix.InitFeeTierParams) {\n    return ix.initializeFeeTierIx(program, params);\n  }\n\n  /**\n   * Initializes a tick_array account to represent a tick-range in a Whirlpool.\n   *\n   * Special Errors\n   * `InvalidTokenMintOrder` - The order of mints have to be ordered by\n   * `SqrtPriceOutOfBounds` - provided initial_sqrt_price is not between 2^-64 to 2^64\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - InitPoolParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static initializePoolIx(program: Program<Whirlpool>, params: ix.InitPoolParams) {\n    return ix.initializePoolIx(program, params);\n  }\n\n  /**\n   * Initialize reward for a Whirlpool. A pool can only support up to a set number of rewards.\n   * The initial emissionsPerSecond is set to 0.\n   *\n   * #### Special Errors\n   * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n   *                          or exceeds NUM_REWARDS, or all reward slots for this pool has been initialized.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - InitializeRewardParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static initializeRewardIx(program: Program<Whirlpool>, params: ix.InitializeRewardParams) {\n    return ix.initializeRewardIx(program, params);\n  }\n\n  /**\n   * Initializes a TickArray account.\n   *\n   * #### Special Errors\n   *  `InvalidStartTick` - if the provided start tick is out of bounds or is not a multiple of TICK_ARRAY_SIZE * tick spacing.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - InitTickArrayParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static initTickArrayIx(program: Program<Whirlpool>, params: ix.InitTickArrayParams) {\n    return ix.initTickArrayIx(program, params);\n  }\n\n  /**\n   * Open a position in a Whirlpool. A unique token will be minted to represent the position in the users wallet.\n   * The position will start off with 0 liquidity.\n   *\n   * #### Special Errors\n   * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.\n   *\n\n   * @param program - program object containing services required to generate the instruction\n   * @param params - OpenPositionParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static openPositionIx(program: Program<Whirlpool>, params: ix.OpenPositionParams) {\n    return ix.openPositionIx(program, params);\n  }\n\n  /**\n   * Open a position in a Whirlpool. A unique token will be minted to represent the position\n   * in the users wallet. Additional Metaplex metadata is appended to identify the token.\n   * The position will start off with 0 liquidity.\n   *\n   * #### Special Errors\n   * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.\n   *\n\n   * @param program - program object containing services required to generate the instruction\n   * @param params - OpenPositionParams object and a derived PDA that hosts the position's metadata.\n   * @returns - Instruction to perform the action.\n   */\n  public static openPositionWithMetadataIx(\n    program: Program<Whirlpool>,\n    params: ix.OpenPositionParams & { metadataPda: PDA }\n  ) {\n    return ix.openPositionWithMetadataIx(program, params);\n  }\n\n  /**\n   * Add liquidity to a position in the Whirlpool. This call also updates the position's accrued fees and rewards.\n   *\n   * #### Special Errors\n   * `LiquidityZero` - Provided liquidity amount is zero.\n   * `LiquidityTooHigh` - Provided liquidity exceeds u128::max.\n   * `TokenMaxExceeded` - The required token to perform this operation exceeds the user defined amount.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - IncreaseLiquidityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static increaseLiquidityIx(\n    program: Program<Whirlpool>,\n    params: ix.IncreaseLiquidityParams\n  ) {\n    return ix.increaseLiquidityIx(program, params);\n  }\n\n  /**\n   * Remove liquidity to a position in the Whirlpool. This call also updates the position's accrued fees and rewards.\n   *\n   * #### Special Errors\n   * - `LiquidityZero` - Provided liquidity amount is zero.\n   * - `LiquidityTooHigh` - Provided liquidity exceeds u128::max.\n   * - `TokenMinSubceeded` - The required token to perform this operation subceeds the user defined amount.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - DecreaseLiquidityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static decreaseLiquidityIx(\n    program: Program<Whirlpool>,\n    params: ix.DecreaseLiquidityParams\n  ) {\n    return ix.decreaseLiquidityIx(program, params);\n  }\n\n  /**\n   * Close a position in a Whirlpool. Burns the position token in the owner's wallet.\n   *\n\n   * @param program - program object containing services required to generate the instruction\n   * @param params - ClosePositionParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static closePositionIx(program: Program<Whirlpool>, params: ix.ClosePositionParams) {\n    return ix.closePositionIx(program, params);\n  }\n\n  /**\n   * Perform a swap in this Whirlpool\n   *\n   * #### Special Errors\n   * - `ZeroTradableAmount` - User provided parameter `amount` is 0.\n   * - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.\n   * - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.\n   * - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.\n   * - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.\n   * - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.\n   * - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.\n   * - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.\n   *\n   * ### Parameters\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SwapParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static swapIx(program: Program<Whirlpool>, params: ix.SwapParams) {\n    return ix.swapIx(program, params);\n  }\n\n  /**\n   * Update the accrued fees and rewards for a position.\n   *\n   * #### Special Errors\n   * `TickNotFound` - Provided tick array account does not contain the tick for this position.\n   * `LiquidityZero` - Position has zero liquidity and therefore already has the most updated fees and reward values.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - UpdateFeesAndRewardsParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static updateFeesAndRewardsIx(\n    program: Program<Whirlpool>,\n    params: ix.UpdateFeesAndRewardsParams\n  ) {\n    return ix.updateFeesAndRewardsIx(program, params);\n  }\n\n  /**\n   * Collect fees accrued for this position.\n   * Call updateFeesAndRewards before this to update the position to the newest accrued values.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - CollectFeesParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static collectFeesIx(program: Program<Whirlpool>, params: ix.CollectFeesParams) {\n    return ix.collectFeesIx(program, params);\n  }\n\n  /**\n   * Collect protocol fees accrued in this Whirlpool.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - CollectProtocolFeesParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static collectProtocolFeesIx(\n    program: Program<Whirlpool>,\n    params: ix.CollectProtocolFeesParams\n  ) {\n    return ix.collectProtocolFeesIx(program, params);\n  }\n\n  /**\n   * Collect rewards accrued for this reward index in a position.\n   * Call updateFeesAndRewards before this to update the position to the newest accrued values.\n   *\n\n   * @param program - program object containing services required to generate the instruction\n   * @param params - CollectRewardParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static collectRewardIx(program: Program<Whirlpool>, params: ix.CollectRewardParams) {\n    return ix.collectRewardIx(program, params);\n  }\n\n  /**\n   * Sets the fee authority to collect protocol fees for a WhirlpoolsConfig.\n   * Only the current collect protocol fee authority has permission to invoke this instruction.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetCollectProtocolFeesAuthorityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setCollectProtocolFeesAuthorityIx(\n    program: Program<Whirlpool>,\n    params: ix.SetCollectProtocolFeesAuthorityParams\n  ) {\n    return ix.setCollectProtocolFeesAuthorityIx(program, params);\n  }\n\n  /**\n   * Updates a fee tier account with a new default fee rate. The new rate will not retroactively update\n   * initialized pools.\n   *\n   * #### Special Errors\n   * - `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetDefaultFeeRateParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setDefaultFeeRateIx(\n    program: Program<Whirlpool>,\n    params: ix.SetDefaultFeeRateParams\n  ) {\n    return ix.setDefaultFeeRateIx(program, params);\n  }\n\n  /**\n   * Updates a WhirlpoolsConfig with a new default protocol fee rate. The new rate will not retroactively update\n   * initialized pools.\n   *\n   * #### Special Errors\n   * - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetDefaultFeeRateParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setDefaultProtocolFeeRateIx(\n    program: Program<Whirlpool>,\n    params: ix.SetDefaultProtocolFeeRateParams\n  ) {\n    return ix.setDefaultProtocolFeeRateIx(program, params);\n  }\n\n  /**\n   * Sets the fee authority for a WhirlpoolsConfig.\n   * The fee authority can set the fee & protocol fee rate for individual pools or set the default fee rate for newly minted pools.\n   * Only the current fee authority has permission to invoke this instruction.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetFeeAuthorityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setFeeAuthorityIx(program: Program<Whirlpool>, params: ix.SetFeeAuthorityParams) {\n    return ix.setFeeAuthorityIx(program, params);\n  }\n\n  /**\n   * Sets the fee rate for a Whirlpool.\n   * Only the current fee authority has permission to invoke this instruction.\n   *\n   * #### Special Errors\n   * - `FeeRateMaxExceeded` - If the provided fee_rate exceeds MAX_FEE_RATE.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetFeeRateParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setFeeRateIx(program: Program<Whirlpool>, params: ix.SetFeeRateParams) {\n    return ix.setFeeRateIx(program, params);\n  }\n\n  /**\n   * Sets the protocol fee rate for a Whirlpool.\n   * Only the current fee authority has permission to invoke this instruction.\n   *\n   * #### Special Errors\n   * - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetFeeRateParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setProtocolFeeRateIx(\n    program: Program<Whirlpool>,\n    params: ix.SetProtocolFeeRateParams\n  ) {\n    return ix.setProtocolFeeRateIx(program, params);\n  }\n\n  /**\n   * Set the whirlpool reward authority at the provided `reward_index`.\n   * Only the current reward super authority has permission to invoke this instruction.\n   *\n   * #### Special Errors\n   * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n   *                          or exceeds NUM_REWARDS.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetRewardAuthorityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setRewardAuthorityBySuperAuthorityIx(\n    program: Program<Whirlpool>,\n    params: ix.SetRewardAuthorityBySuperAuthorityParams\n  ) {\n    return ix.setRewardAuthorityBySuperAuthorityIx(program, params);\n  }\n\n  /**\n   * Set the whirlpool reward authority at the provided `reward_index`.\n   * Only the current reward authority for this reward index has permission to invoke this instruction.\n   *\n   * #### Special Errors\n   * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n   *                          or exceeds NUM_REWARDS.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetRewardAuthorityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setRewardAuthorityIx(\n    program: Program<Whirlpool>,\n    params: ix.SetRewardAuthorityParams\n  ) {\n    return ix.setRewardAuthorityIx(program, params);\n  }\n\n  /**\n   * Set the reward emissions for a reward in a Whirlpool.\n   *\n   * #### Special Errors\n   * - `RewardVaultAmountInsufficient` - The amount of rewards in the reward vault cannot emit more than a day of desired emissions.\n   * - `InvalidTimestamp` - Provided timestamp is not in order with the previous timestamp.\n   * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n   *                          or exceeds NUM_REWARDS.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetRewardEmissionsParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setRewardEmissionsIx(\n    program: Program<Whirlpool>,\n    params: ix.SetRewardEmissionsParams\n  ) {\n    return ix.setRewardEmissionsIx(program, params);\n  }\n\n  /**\n   * Set the whirlpool reward super authority for a WhirlpoolsConfig\n   * Only the current reward super authority has permission to invoke this instruction.\n   * This instruction will not change the authority on any `WhirlpoolRewardInfo` whirlpool rewards.\n   *\n   * @param program - program object containing services required to generate the instruction\n   * @param params - SetRewardEmissionsSuperAuthorityParams object\n   * @returns - Instruction to perform the action.\n   */\n  public static setRewardEmissionsSuperAuthorityIx(\n    program: Program<Whirlpool>,\n    params: ix.SetRewardEmissionsSuperAuthorityParams\n  ) {\n    return ix.setRewardEmissionsSuperAuthorityIx(program, params);\n  }\n\n  /**\n   * A set of transactions to collect all fees and rewards from a list of positions.\n   *\n   * @param ctx - WhirlpoolContext object for the current environment.\n   * @param params - CollectAllPositionAddressParams object.\n   * @param refresh - if true, will always fetch for the latest values on chain to compute.\n   * @returns\n   */\n  public static collectAllForPositionsTxns(\n    ctx: WhirlpoolContext,\n    params: ix.CollectAllPositionAddressParams,\n    refresh: boolean\n  ) {\n    return ix.collectAllForPositionAddressesTxns(ctx, params, refresh);\n  }\n}\n","import { TransactionBuilder, Instruction } from \"@orca-so/common-sdk\";\nimport { WhirlpoolContext } from \"../../context\";\n\nexport function toTx(ctx: WhirlpoolContext, ix: Instruction): TransactionBuilder {\n  return new TransactionBuilder(ctx.provider.connection, ctx.provider.wallet).addInstruction(ix);\n}\n","import { AddressUtil } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { METADATA_PROGRAM_ADDRESS } from \"../../types/public\";\nimport { PriceMath } from \"./price-math\";\nimport { TickUtil } from \"./tick-utils\";\n\nconst PDA_WHIRLPOOL_SEED = \"whirlpool\";\nconst PDA_POSITION_SEED = \"position\";\nconst PDA_METADATA_SEED = \"metadata\";\nconst PDA_TICK_ARRAY_SEED = \"tick_array\";\nconst PDA_FEE_TIER_SEED = \"fee_tier\";\nconst PDA_ORACLE_SEED = \"oracle\";\n\n/**\n * @category Whirlpool Utils\n */\nexport class PDAUtil {\n  /**\n   *\n   * @param programId\n   * @param whirlpoolsConfigKey\n   * @param tokenMintAKey\n   * @param tokenMintBKey\n   * @param tickSpacing\n   * @returns\n   */\n  public static getWhirlpool(\n    programId: PublicKey,\n    whirlpoolsConfigKey: PublicKey,\n    tokenMintAKey: PublicKey,\n    tokenMintBKey: PublicKey,\n    tickSpacing: number\n  ) {\n    return AddressUtil.findProgramAddress(\n      [\n        Buffer.from(PDA_WHIRLPOOL_SEED),\n        whirlpoolsConfigKey.toBuffer(),\n        tokenMintAKey.toBuffer(),\n        tokenMintBKey.toBuffer(),\n        new BN(tickSpacing).toArrayLike(Buffer, \"le\", 2),\n      ],\n      programId\n    );\n  }\n\n  /**\n   * @category Program Derived Addresses\n   * @param programId\n   * @param positionMintKey\n   * @returns\n   */\n  public static getPosition(programId: PublicKey, positionMintKey: PublicKey) {\n    return AddressUtil.findProgramAddress(\n      [Buffer.from(PDA_POSITION_SEED), positionMintKey.toBuffer()],\n      programId\n    );\n  }\n\n  /**\n   * @category Program Derived Addresses\n   * @param positionMintKey\n   * @returns\n   */\n  public static getPositionMetadata(positionMintKey: PublicKey) {\n    return AddressUtil.findProgramAddress(\n      [\n        Buffer.from(PDA_METADATA_SEED),\n        METADATA_PROGRAM_ADDRESS.toBuffer(),\n        positionMintKey.toBuffer(),\n      ],\n      METADATA_PROGRAM_ADDRESS\n    );\n  }\n\n  /**\n   * @category Program Derived Addresses\n   * @param programId\n   * @param whirlpoolAddress\n   * @param startTick\n   * @returns\n   */\n  public static getTickArray(programId: PublicKey, whirlpoolAddress: PublicKey, startTick: number) {\n    return AddressUtil.findProgramAddress(\n      [\n        Buffer.from(PDA_TICK_ARRAY_SEED),\n        whirlpoolAddress.toBuffer(),\n        Buffer.from(startTick.toString()),\n      ],\n      programId\n    );\n  }\n\n  /**\n   * Get the PDA of the tick array containing tickIndex.\n   * tickArrayOffset can be used to get neighboring tick arrays.\n   *\n   * @param tickIndex\n   * @param tickSpacing\n   * @param whirlpool\n   * @param programId\n   * @param tickArrayOffset\n   * @returns\n   */\n  public static getTickArrayFromTickIndex(\n    tickIndex: number,\n    tickSpacing: number,\n    whirlpool: PublicKey,\n    programId: PublicKey,\n    tickArrayOffset = 0\n  ) {\n    const startIndex = TickUtil.getStartTickIndex(tickIndex, tickSpacing, tickArrayOffset);\n    return PDAUtil.getTickArray(\n      AddressUtil.toPubKey(programId),\n      AddressUtil.toPubKey(whirlpool),\n      startIndex\n    );\n  }\n\n  public static getTickArrayFromSqrtPrice(\n    sqrtPriceX64: BN,\n    tickSpacing: number,\n    whirlpool: PublicKey,\n    programId: PublicKey,\n    tickArrayOffset = 0\n  ) {\n    const tickIndex = PriceMath.sqrtPriceX64ToTickIndex(sqrtPriceX64);\n    return PDAUtil.getTickArrayFromTickIndex(\n      tickIndex,\n      tickSpacing,\n      whirlpool,\n      programId,\n      tickArrayOffset\n    );\n  }\n\n  /**\n   * @category Program Derived Addresses\n   * @param programId\n   * @param whirlpoolsConfigAddress\n   * @param tickSpacing\n   * @returns\n   */\n  public static getFeeTier(\n    programId: PublicKey,\n    whirlpoolsConfigAddress: PublicKey,\n    tickSpacing: number\n  ) {\n    return AddressUtil.findProgramAddress(\n      [\n        Buffer.from(PDA_FEE_TIER_SEED),\n        whirlpoolsConfigAddress.toBuffer(),\n        new BN(tickSpacing).toArrayLike(Buffer, \"le\", 2),\n      ],\n      programId\n    );\n  }\n\n  /**\n   * @category Program Derived Addresses\n   * @param programId\n   * @param whirlpoolAddress\n   * @returns\n   */\n  public static getOracle(programId: PublicKey, whirlpoolAddress: PublicKey) {\n    return AddressUtil.findProgramAddress(\n      [Buffer.from(PDA_ORACLE_SEED), whirlpoolAddress.toBuffer()],\n      programId\n    );\n  }\n}\n","import { MathUtil } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport Decimal from \"decimal.js\";\nimport { MAX_SQRT_PRICE, MIN_SQRT_PRICE } from \"../../types/public\";\nimport { TickUtil } from \"./tick-utils\";\n\nconst BIT_PRECISION = 14;\nconst LOG_B_2_X32 = \"59543866431248\";\nconst LOG_B_P_ERR_MARGIN_LOWER_X64 = \"184467440737095516\";\nconst LOG_B_P_ERR_MARGIN_UPPER_X64 = \"15793534762490258745\";\n\n/**\n * A collection of utility functions to convert between price, tickIndex and sqrtPrice.\n *\n * @category Whirlpool Utils\n */\nexport class PriceMath {\n  public static priceToSqrtPriceX64(price: Decimal, decimalsA: number, decimalsB: number): BN {\n    return MathUtil.toX64(price.mul(Decimal.pow(10, decimalsB - decimalsA)).sqrt());\n  }\n\n  public static sqrtPriceX64ToPrice(\n    sqrtPriceX64: BN,\n    decimalsA: number,\n    decimalsB: number\n  ): Decimal {\n    return MathUtil.fromX64(sqrtPriceX64)\n      .pow(2)\n      .mul(Decimal.pow(10, decimalsA - decimalsB));\n  }\n\n  /**\n   * @param tickIndex\n   * @returns\n   */\n  public static tickIndexToSqrtPriceX64(tickIndex: number): BN {\n    if (tickIndex > 0) {\n      return new BN(tickIndexToSqrtPricePositive(tickIndex));\n    } else {\n      return new BN(tickIndexToSqrtPriceNegative(tickIndex));\n    }\n  }\n\n  /**\n   *\n   * @param sqrtPriceX64\n   * @returns\n   */\n  public static sqrtPriceX64ToTickIndex(sqrtPriceX64: BN): number {\n    if (sqrtPriceX64.gt(new BN(MAX_SQRT_PRICE)) || sqrtPriceX64.lt(new BN(MIN_SQRT_PRICE))) {\n      throw new Error(\"Provided sqrtPrice is not within the supported sqrtPrice range.\");\n    }\n\n    const msb = sqrtPriceX64.bitLength() - 1;\n    const adjustedMsb = new BN(msb - 64);\n    const log2pIntegerX32 = signedShiftLeft(adjustedMsb, 32, 128);\n\n    let bit = new BN(\"8000000000000000\", \"hex\");\n    let precision = 0;\n    let log2pFractionX64 = new BN(0);\n\n    let r = msb >= 64 ? sqrtPriceX64.shrn(msb - 63) : sqrtPriceX64.shln(63 - msb);\n\n    while (bit.gt(new BN(0)) && precision < BIT_PRECISION) {\n      r = r.mul(r);\n      let rMoreThanTwo = r.shrn(127);\n      r = r.shrn(63 + rMoreThanTwo.toNumber());\n      log2pFractionX64 = log2pFractionX64.add(bit.mul(rMoreThanTwo));\n      bit = bit.shrn(1);\n      precision += 1;\n    }\n\n    const log2pFractionX32 = log2pFractionX64.shrn(32);\n\n    const log2pX32 = log2pIntegerX32.add(log2pFractionX32);\n    const logbpX64 = log2pX32.mul(new BN(LOG_B_2_X32));\n\n    const tickLow = signedShiftRight(\n      logbpX64.sub(new BN(LOG_B_P_ERR_MARGIN_LOWER_X64)),\n      64,\n      128\n    ).toNumber();\n    const tickHigh = signedShiftRight(\n      logbpX64.add(new BN(LOG_B_P_ERR_MARGIN_UPPER_X64)),\n      64,\n      128\n    ).toNumber();\n\n    if (tickLow == tickHigh) {\n      return tickLow;\n    } else {\n      const derivedTickHighSqrtPriceX64 = PriceMath.tickIndexToSqrtPriceX64(tickHigh);\n      if (derivedTickHighSqrtPriceX64.lte(sqrtPriceX64)) {\n        return tickHigh;\n      } else {\n        return tickLow;\n      }\n    }\n  }\n\n  public static tickIndexToPrice(tickIndex: number, decimalsA: number, decimalsB: number): Decimal {\n    return PriceMath.sqrtPriceX64ToPrice(\n      PriceMath.tickIndexToSqrtPriceX64(tickIndex),\n      decimalsA,\n      decimalsB\n    );\n  }\n\n  public static priceToTickIndex(price: Decimal, decimalsA: number, decimalsB: number): number {\n    return PriceMath.sqrtPriceX64ToTickIndex(\n      PriceMath.priceToSqrtPriceX64(price, decimalsA, decimalsB)\n    );\n  }\n\n  public static priceToInitializableTickIndex(\n    price: Decimal,\n    decimalsA: number,\n    decimalsB: number,\n    tickSpacing: number\n  ): number {\n    return TickUtil.getInitializableTickIndex(\n      PriceMath.priceToTickIndex(price, decimalsA, decimalsB),\n      tickSpacing\n    );\n  }\n\n  /**\n   * Utility to invert the price Pb/Pa to Pa/Pb\n   * @param price Pb / Pa\n   * @param decimalsA Decimals of original token A (i.e. token A in the given Pb / Pa price)\n   * @param decimalsB Decimals of original token B (i.e. token B in the given Pb / Pa price)\n   * @returns inverted price, i.e. Pa / Pb\n   */\n  public static invertPrice(price: Decimal, decimalsA: number, decimalsB: number): Decimal {\n    const tick = PriceMath.priceToTickIndex(price, decimalsA, decimalsB);\n    const invTick = TickUtil.invertTick(tick);\n    return PriceMath.tickIndexToPrice(invTick, decimalsB, decimalsA);\n  }\n\n  /**\n   * Utility to invert the sqrtPriceX64 from X64 repr. of sqrt(Pb/Pa) to X64 repr. of sqrt(Pa/Pb)\n   * @param sqrtPriceX64 X64 representation of sqrt(Pb / Pa)\n   * @returns inverted sqrtPriceX64, i.e. X64 representation of sqrt(Pa / Pb)\n   */\n  public static invertSqrtPriceX64(sqrtPriceX64: BN): BN {\n    const tick = PriceMath.sqrtPriceX64ToTickIndex(sqrtPriceX64);\n    const invTick = TickUtil.invertTick(tick);\n    return PriceMath.tickIndexToSqrtPriceX64(invTick);\n  }\n}\n\n// Private Functions\n\nfunction tickIndexToSqrtPricePositive(tick: number) {\n  let ratio: BN;\n\n  if ((tick & 1) != 0) {\n    ratio = new BN(\"79232123823359799118286999567\");\n  } else {\n    ratio = new BN(\"79228162514264337593543950336\");\n  }\n\n  if ((tick & 2) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79236085330515764027303304731\")), 96, 256);\n  }\n  if ((tick & 4) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79244008939048815603706035061\")), 96, 256);\n  }\n  if ((tick & 8) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79259858533276714757314932305\")), 96, 256);\n  }\n  if ((tick & 16) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79291567232598584799939703904\")), 96, 256);\n  }\n  if ((tick & 32) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79355022692464371645785046466\")), 96, 256);\n  }\n  if ((tick & 64) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79482085999252804386437311141\")), 96, 256);\n  }\n  if ((tick & 128) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"79736823300114093921829183326\")), 96, 256);\n  }\n  if ((tick & 256) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"80248749790819932309965073892\")), 96, 256);\n  }\n  if ((tick & 512) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"81282483887344747381513967011\")), 96, 256);\n  }\n  if ((tick & 1024) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"83390072131320151908154831281\")), 96, 256);\n  }\n  if ((tick & 2048) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"87770609709833776024991924138\")), 96, 256);\n  }\n  if ((tick & 4096) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"97234110755111693312479820773\")), 96, 256);\n  }\n  if ((tick & 8192) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"119332217159966728226237229890\")), 96, 256);\n  }\n  if ((tick & 16384) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"179736315981702064433883588727\")), 96, 256);\n  }\n  if ((tick & 32768) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"407748233172238350107850275304\")), 96, 256);\n  }\n  if ((tick & 65536) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"2098478828474011932436660412517\")), 96, 256);\n  }\n  if ((tick & 131072) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"55581415166113811149459800483533\")), 96, 256);\n  }\n  if ((tick & 262144) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"38992368544603139932233054999993551\")), 96, 256);\n  }\n\n  return signedShiftRight(ratio, 32, 256);\n}\n\nfunction tickIndexToSqrtPriceNegative(tickIndex: number) {\n  let tick = Math.abs(tickIndex);\n  let ratio: BN;\n\n  if ((tick & 1) != 0) {\n    ratio = new BN(\"18445821805675392311\");\n  } else {\n    ratio = new BN(\"18446744073709551616\");\n  }\n\n  if ((tick & 2) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18444899583751176498\")), 64, 256);\n  }\n  if ((tick & 4) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18443055278223354162\")), 64, 256);\n  }\n  if ((tick & 8) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18439367220385604838\")), 64, 256);\n  }\n  if ((tick & 16) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18431993317065449817\")), 64, 256);\n  }\n  if ((tick & 32) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18417254355718160513\")), 64, 256);\n  }\n  if ((tick & 64) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18387811781193591352\")), 64, 256);\n  }\n  if ((tick & 128) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18329067761203520168\")), 64, 256);\n  }\n  if ((tick & 256) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"18212142134806087854\")), 64, 256);\n  }\n  if ((tick & 512) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"17980523815641551639\")), 64, 256);\n  }\n  if ((tick & 1024) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"17526086738831147013\")), 64, 256);\n  }\n  if ((tick & 2048) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"16651378430235024244\")), 64, 256);\n  }\n  if ((tick & 4096) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"15030750278693429944\")), 64, 256);\n  }\n  if ((tick & 8192) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"12247334978882834399\")), 64, 256);\n  }\n  if ((tick & 16384) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"8131365268884726200\")), 64, 256);\n  }\n  if ((tick & 32768) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"3584323654723342297\")), 64, 256);\n  }\n  if ((tick & 65536) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"696457651847595233\")), 64, 256);\n  }\n  if ((tick & 131072) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"26294789957452057\")), 64, 256);\n  }\n  if ((tick & 262144) != 0) {\n    ratio = signedShiftRight(ratio.mul(new BN(\"37481735321082\")), 64, 256);\n  }\n\n  return ratio;\n}\n\nfunction signedShiftLeft(n0: BN, shiftBy: number, bitWidth: number) {\n  let twosN0 = n0.toTwos(bitWidth).shln(shiftBy);\n  twosN0.imaskn(bitWidth + 1);\n  return twosN0.fromTwos(bitWidth);\n}\n\nfunction signedShiftRight(n0: BN, shiftBy: number, bitWidth: number) {\n  let twoN0 = n0.toTwos(bitWidth).shrn(shiftBy);\n  twoN0.imaskn(bitWidth - shiftBy + 1);\n  return twoN0.fromTwos(bitWidth - shiftBy);\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport invariant from \"tiny-invariant\";\nimport { AccountFetcher } from \"../../network/public\";\nimport {\n  MAX_TICK_INDEX,\n  MIN_TICK_INDEX,\n  TickArrayData,\n  TickData,\n  TICK_ARRAY_SIZE,\n} from \"../../types/public\";\nimport { PDAUtil } from \"./pda-utils\";\n\nenum TickSearchDirection {\n  Left,\n  Right,\n}\n\n/**\n * A collection of utility functions when interacting with Ticks.\n * @category Whirlpool Utils\n */\nexport class TickUtil {\n  private constructor() {}\n\n  /**\n   * Get the offset index to access a tick at a given tick-index in a tick-array\n   *\n   * @param tickIndex The tick index for the tick that this offset would access\n   * @param arrayStartIndex The starting tick for the array that this tick-index resides in\n   * @param tickSpacing The tickSpacing for the Whirlpool that this tickArray belongs to\n   * @returns The offset index that can access the desired tick at the given tick-array\n   */\n  public static getOffsetIndex(tickIndex: number, arrayStartIndex: number, tickSpacing: number) {\n    return Math.floor((tickIndex - arrayStartIndex) / tickSpacing);\n  }\n\n  /**\n   * Get the startIndex of the tick array containing tickIndex.\n   *\n   * @param tickIndex\n   * @param tickSpacing\n   * @param offset can be used to get neighboring tick array startIndex.\n   * @returns\n   */\n  public static getStartTickIndex(tickIndex: number, tickSpacing: number, offset = 0): number {\n    const realIndex = Math.floor(tickIndex / tickSpacing / TICK_ARRAY_SIZE);\n    const startTickIndex = (realIndex + offset) * tickSpacing * TICK_ARRAY_SIZE;\n\n    const ticksInArray = TICK_ARRAY_SIZE * tickSpacing;\n    const minTickIndex = MIN_TICK_INDEX - ((MIN_TICK_INDEX % ticksInArray) + ticksInArray);\n    invariant(startTickIndex >= minTickIndex, `startTickIndex is too small - - ${startTickIndex}`);\n    invariant(startTickIndex <= MAX_TICK_INDEX, `startTickIndex is too large - ${startTickIndex}`);\n    return startTickIndex;\n  }\n\n  /**\n   * Get the nearest (rounding down) valid tick index from the tickIndex.\n   * A valid tick index is a point on the tick spacing grid line.\n   */\n  public static getInitializableTickIndex(tickIndex: number, tickSpacing: number): number {\n    return tickIndex - (tickIndex % tickSpacing);\n  }\n\n  public static getNextInitializableTickIndex(tickIndex: number, tickSpacing: number) {\n    return TickUtil.getInitializableTickIndex(tickIndex, tickSpacing) + tickSpacing;\n  }\n\n  public static getPrevInitializableTickIndex(tickIndex: number, tickSpacing: number) {\n    return TickUtil.getInitializableTickIndex(tickIndex, tickSpacing) - tickSpacing;\n  }\n\n  /**\n   * Get the previous initialized tick index within the same tick array.\n   *\n   * @param account\n   * @param currentTickIndex\n   * @param tickSpacing\n   * @returns\n   */\n  public static findPreviousInitializedTickIndex(\n    account: TickArrayData,\n    currentTickIndex: number,\n    tickSpacing: number\n  ): number | null {\n    return TickUtil.findInitializedTick(\n      account,\n      currentTickIndex,\n      tickSpacing,\n      TickSearchDirection.Left\n    );\n  }\n\n  /**\n   * Get the next initialized tick index within the same tick array.\n   * @param account\n   * @param currentTickIndex\n   * @param tickSpacing\n   * @returns\n   */\n  public static findNextInitializedTickIndex(\n    account: TickArrayData,\n    currentTickIndex: number,\n    tickSpacing: number\n  ): number | null {\n    return TickUtil.findInitializedTick(\n      account,\n      currentTickIndex,\n      tickSpacing,\n      TickSearchDirection.Right\n    );\n  }\n\n  private static findInitializedTick(\n    account: TickArrayData,\n    currentTickIndex: number,\n    tickSpacing: number,\n    searchDirection: TickSearchDirection\n  ): number | null {\n    const currentTickArrayIndex = tickIndexToInnerIndex(\n      account.startTickIndex,\n      currentTickIndex,\n      tickSpacing\n    );\n\n    const increment = searchDirection === TickSearchDirection.Right ? 1 : -1;\n\n    let stepInitializedTickArrayIndex =\n      searchDirection === TickSearchDirection.Right\n        ? currentTickArrayIndex + increment\n        : currentTickArrayIndex;\n    while (\n      stepInitializedTickArrayIndex >= 0 &&\n      stepInitializedTickArrayIndex < account.ticks.length\n    ) {\n      if (account.ticks[stepInitializedTickArrayIndex]?.initialized) {\n        return innerIndexToTickIndex(\n          account.startTickIndex,\n          stepInitializedTickArrayIndex,\n          tickSpacing\n        );\n      }\n\n      stepInitializedTickArrayIndex += increment;\n    }\n\n    return null;\n  }\n\n  public static checkTickInBounds(tick: number) {\n    return tick <= MAX_TICK_INDEX && tick >= MIN_TICK_INDEX;\n  }\n\n  public static isTickInitializable(tick: number, tickSpacing: number) {\n    return tick % tickSpacing === 0;\n  }\n\n  /**\n   *\n   * Returns the tick for the inverse of the price that this tick represents.\n   * Eg: Consider tick i where Pb/Pa = 1.0001 ^ i\n   * inverse of this, i.e. Pa/Pb = 1 / (1.0001 ^ i) = 1.0001^-i\n   * @param tick The tick to invert\n   * @returns\n   */\n  public static invertTick(tick: number) {\n    return -tick;\n  }\n}\n\n/**\n * A collection of utility functions when interacting with a TickArray.\n * @category Whirlpool Utils\n */\nexport class TickArrayUtil {\n  /**\n   * Get the tick from tickArray with a global tickIndex.\n   */\n  public static getTickFromArray(\n    tickArray: TickArrayData,\n    tickIndex: number,\n    tickSpacing: number\n  ): TickData {\n    const realIndex = tickIndexToInnerIndex(tickArray.startTickIndex, tickIndex, tickSpacing);\n    const tick = tickArray.ticks[realIndex];\n    invariant(\n      !!tick,\n      `tick realIndex out of range - start - ${tickArray.startTickIndex} index - ${tickIndex}, realIndex - ${realIndex}`\n    );\n    return tick;\n  }\n\n  /**\n   * Return a sequence of tick array pdas based on the sequence start index.\n   * @param tick - A tick in the first tick-array of your sequence\n   * @param tickSpacing - Tick spacing for the whirlpool\n   * @param numOfTickArrays - The number of TickArray PDAs to generate\n   * @param programId - Program Id of the whirlpool for these tick-arrays\n   * @param whirlpoolAddress - Address for the Whirlpool for these tick-arrays\n   * @returns TickArray PDAs for the sequence`\n   */\n  public static async getTickArrayPDAs(\n    tick: number,\n    tickSpacing: number,\n    numOfTickArrays: number,\n    programId: PublicKey,\n    whirlpoolAddress: PublicKey,\n    aToB: boolean\n  ) {\n    let arrayIndexList = [...Array(numOfTickArrays).keys()];\n    if (aToB) {\n      arrayIndexList = arrayIndexList.map((value) => -value);\n    }\n    return arrayIndexList.map((value) => {\n      const startTick = TickUtil.getStartTickIndex(tick, tickSpacing, value);\n      return PDAUtil.getTickArray(programId, whirlpoolAddress, startTick);\n    });\n  }\n\n  public static async getUninitializedArraysPDAs(\n    ticks: number[],\n    programId: PublicKey,\n    whirlpoolAddress: PublicKey,\n    tickSpacing: number,\n    fetcher: AccountFetcher,\n    refresh: boolean\n  ) {\n    const startTicks = ticks.map((tick) => TickUtil.getStartTickIndex(tick, tickSpacing));\n    const removeDupeTicks = [...new Set(startTicks)];\n    const tickArrayPDAs = removeDupeTicks.map((tick) =>\n      PDAUtil.getTickArray(programId, whirlpoolAddress, tick)\n    );\n    const fetchedArrays = await fetcher.listTickArrays(\n      tickArrayPDAs.map((pda) => pda.publicKey),\n      refresh\n    );\n    const uninitializedIndices = TickArrayUtil.getUninitializedArrays(fetchedArrays);\n    return uninitializedIndices.map((index) => {\n      return {\n        startIndex: removeDupeTicks[index],\n        pda: tickArrayPDAs[index],\n      };\n    });\n  }\n\n  /**\n   * Evaluate a list of tick-array data and return the array of indices which the tick-arrays are not initialized.\n   * @param tickArrays - a list of TickArrayData or null objects from AccountFetcher.listTickArrays\n   * @returns an array of array-index for the input tickArrays that requires initialization.\n   */\n  public static getUninitializedArrays(tickArrays: (TickArrayData | null)[]): number[] {\n    return tickArrays\n      .map((value, index) => {\n        if (!value) {\n          return index;\n        }\n        return -1;\n      })\n      .filter((index) => index >= 0);\n  }\n}\n\nfunction tickIndexToInnerIndex(\n  startTickIndex: number,\n  tickIndex: number,\n  tickSpacing: number\n): number {\n  return Math.floor((tickIndex - startTickIndex) / tickSpacing);\n}\n\nfunction innerIndexToTickIndex(\n  startTickIndex: number,\n  tickArrayIndex: number,\n  tickSpacing: number\n): number {\n  return startTickIndex + tickArrayIndex * tickSpacing;\n}\n","import { AddressUtil, MathUtil, Percentage } from \"@orca-so/common-sdk\";\nimport { Address, BN } from \"@project-serum/anchor\";\nimport { u64 } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport Decimal from \"decimal.js\";\nimport { WhirlpoolData, WhirlpoolRewardInfoData } from \"../../types/public\";\nimport { PriceMath } from \"./price-math\";\nimport { TokenType } from \"./types\";\n\n/**\n * @category Whirlpool Utils\n */\nexport class PoolUtil {\n  private constructor() {}\n\n  public static isRewardInitialized(rewardInfo: WhirlpoolRewardInfoData): boolean {\n    return (\n      !PublicKey.default.equals(rewardInfo.mint) && !PublicKey.default.equals(rewardInfo.vault)\n    );\n  }\n\n  /**\n   * Return the corresponding token type (TokenA/B) for this mint key for a Whirlpool.\n   *\n   * @param pool The Whirlpool to evaluate the mint against\n   * @param mint The token mint PublicKey\n   * @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.\n   */\n  public static getTokenType(pool: WhirlpoolData, mint: PublicKey): TokenType | undefined {\n    if (pool.tokenMintA.equals(mint)) {\n      return TokenType.TokenA;\n    } else if (pool.tokenMintB.equals(mint)) {\n      return TokenType.TokenB;\n    }\n    return undefined;\n  }\n\n  public static getFeeRate(feeRate: number): Percentage {\n    /**\n     * Smart Contract comment: https://github.com/orca-so/whirlpool/blob/main/programs/whirlpool/src/state/whirlpool.rs#L9-L11\n     * // Stored as hundredths of a basis point\n     * // u16::MAX corresponds to ~6.5%\n     * pub fee_rate: u16,\n     */\n    return Percentage.fromFraction(feeRate, 1e6); // TODO\n  }\n\n  public static getProtocolFeeRate(protocolFeeRate: number): Percentage {\n    /**\n     * Smart Contract comment: https://github.com/orca-so/whirlpool/blob/main/programs/whirlpool/src/state/whirlpool.rs#L13-L14\n     * // Stored as a basis point\n     * pub protocol_fee_rate: u16,\n     */\n    return Percentage.fromFraction(protocolFeeRate, 1e4); // TODO\n  }\n\n  public static orderMints(mintX: Address, mintY: Address): [Address, Address] {\n    let mintA, mintB;\n    if (\n      Buffer.compare(\n        AddressUtil.toPubKey(mintX).toBuffer(),\n        AddressUtil.toPubKey(mintY).toBuffer()\n      ) < 0\n    ) {\n      mintA = mintX;\n      mintB = mintY;\n    } else {\n      mintA = mintY;\n      mintB = mintX;\n    }\n\n    return [mintA, mintB];\n  }\n\n  /**\n   * @category Whirlpool Utils\n   * @param liquidity\n   * @param currentSqrtPrice\n   * @param lowerSqrtPrice\n   * @param upperSqrtPrice\n   * @param round_up\n   * @returns\n   */\n  public static getTokenAmountsFromLiquidity(\n    liquidity: BN,\n    currentSqrtPrice: BN,\n    lowerSqrtPrice: BN,\n    upperSqrtPrice: BN,\n    round_up: boolean\n  ): TokenAmounts {\n    const _liquidity = new Decimal(liquidity.toString());\n    const _currentPrice = new Decimal(currentSqrtPrice.toString());\n    const _lowerPrice = new Decimal(lowerSqrtPrice.toString());\n    const _upperPrice = new Decimal(upperSqrtPrice.toString());\n    let tokenA, tokenB;\n    if (currentSqrtPrice.lt(lowerSqrtPrice)) {\n      // x = L * (pb - pa) / (pa * pb)\n      tokenA = MathUtil.toX64_Decimal(_liquidity)\n        .mul(_upperPrice.sub(_lowerPrice))\n        .div(_lowerPrice.mul(_upperPrice));\n      tokenB = new Decimal(0);\n    } else if (currentSqrtPrice.lt(upperSqrtPrice)) {\n      // x = L * (pb - p) / (p * pb)\n      // y = L * (p - pa)\n      tokenA = MathUtil.toX64_Decimal(_liquidity)\n        .mul(_upperPrice.sub(_currentPrice))\n        .div(_currentPrice.mul(_upperPrice));\n      tokenB = MathUtil.fromX64_Decimal(_liquidity.mul(_currentPrice.sub(_lowerPrice)));\n    } else {\n      // y = L * (pb - pa)\n      tokenA = new Decimal(0);\n      tokenB = MathUtil.fromX64_Decimal(_liquidity.mul(_upperPrice.sub(_lowerPrice)));\n    }\n\n    // TODO: round up\n    if (round_up) {\n      return {\n        tokenA: new u64(tokenA.ceil().toString()),\n        tokenB: new u64(tokenB.ceil().toString()),\n      };\n    } else {\n      return {\n        tokenA: new u64(tokenA.floor().toString()),\n        tokenB: new u64(tokenB.floor().toString()),\n      };\n    }\n  }\n\n  /**\n   * Estimate the liquidity amount required to increase/decrease liquidity.\n   *\n   * // TODO: At the top end of the price range, tick calcuation is off therefore the results can be off\n   *\n   * @category Whirlpool Utils\n   * @param currTick - Whirlpool's current tick index (aka price)\n   * @param lowerTick - Position lower tick index\n   * @param upperTick - Position upper tick index\n   * @param tokenAmount - The desired amount of tokens to deposit/withdraw\n   * @returns An estimated amount of liquidity needed to deposit/withdraw the desired amount of tokens.\n   */\n  public static estimateLiquidityFromTokenAmounts(\n    currTick: number,\n    lowerTick: number,\n    upperTick: number,\n    tokenAmount: TokenAmounts\n  ): BN {\n    if (upperTick < lowerTick) {\n      throw new Error(\"upper tick cannot be lower than the lower tick\");\n    }\n\n    const currSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(currTick);\n    const lowerSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(lowerTick);\n    const upperSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(upperTick);\n\n    if (currTick >= upperTick) {\n      return estLiquidityForTokenB(upperSqrtPrice, lowerSqrtPrice, tokenAmount.tokenB);\n    } else if (currTick < lowerTick) {\n      return estLiquidityForTokenA(lowerSqrtPrice, upperSqrtPrice, tokenAmount.tokenA);\n    } else {\n      const estLiquidityAmountA = estLiquidityForTokenA(\n        currSqrtPrice,\n        upperSqrtPrice,\n        tokenAmount.tokenA\n      );\n      const estLiquidityAmountB = estLiquidityForTokenB(\n        currSqrtPrice,\n        lowerSqrtPrice,\n        tokenAmount.tokenB\n      );\n      return BN.min(estLiquidityAmountA, estLiquidityAmountB);\n    }\n  }\n\n  /**\n   * Given an arbitrary pair of token mints, this function returns an ordering of the token mints\n   * in the format [base, quote]. USD based stable coins are prioritized as the quote currency\n   * followed by variants of SOL.\n   *\n   * @category Whirlpool Utils\n   * @param tokenMintAKey - The mint of token A in the token pair.\n   * @param tokenMintBKey - The mint of token B in the token pair.\n   * @returns A two-element array with the tokens sorted in the order of [baseToken, quoteToken].\n   */\n  public static toBaseQuoteOrder(\n    tokenMintAKey: PublicKey,\n    tokenMintBKey: PublicKey\n  ): [PublicKey, PublicKey] {\n    const pair: [PublicKey, PublicKey] = [tokenMintAKey, tokenMintBKey];\n    return pair.sort(sortByQuotePriority);\n  }\n}\n\n/**\n * @category Whirlpool Utils\n */\nexport type TokenAmounts = {\n  tokenA: u64;\n  tokenB: u64;\n};\n\n/**\n * @category Whirlpool Utils\n */\nexport function toTokenAmount(a: number, b: number): TokenAmounts {\n  return {\n    tokenA: new u64(a.toString()),\n    tokenB: new u64(b.toString()),\n  };\n}\n\n// These are the token mints that will be prioritized as the second token in the pair (quote).\n// The number that the mint maps to determines the priority that it will be used as the quote\n// currency.\nconst QUOTE_TOKENS: { [mint: string]: number } = {\n  Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB: 100, // USDT\n  EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: 90, // USDC\n  USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX: 80, // USDH\n  So11111111111111111111111111111111111111112: 70, // SOL\n  mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So: 60, // mSOL\n  \"7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj\": 50, // stSOL\n};\n\nconst DEFAULT_QUOTE_PRIORITY = 0;\n\nfunction getQuoteTokenPriority(mint: string): number {\n  const value = QUOTE_TOKENS[mint];\n  if (value) {\n    return value;\n  }\n  return DEFAULT_QUOTE_PRIORITY;\n}\n\nfunction sortByQuotePriority(mintLeft: PublicKey, mintRight: PublicKey): number {\n  return getQuoteTokenPriority(mintLeft.toString()) - getQuoteTokenPriority(mintRight.toString());\n}\n\n// Convert this function based on Delta A = Delta L * (1/sqrt(lower) - 1/sqrt(upper))\nfunction estLiquidityForTokenA(sqrtPrice1: BN, sqrtPrice2: BN, tokenAmount: u64) {\n  const lowerSqrtPriceX64 = BN.min(sqrtPrice1, sqrtPrice2);\n  const upperSqrtPriceX64 = BN.max(sqrtPrice1, sqrtPrice2);\n\n  const num = MathUtil.fromX64_BN(tokenAmount.mul(upperSqrtPriceX64).mul(lowerSqrtPriceX64));\n  const dem = upperSqrtPriceX64.sub(lowerSqrtPriceX64);\n\n  return num.div(dem);\n}\n\n// Convert this function based on Delta B = Delta L * (sqrt_price(upper) - sqrt_price(lower))\nfunction estLiquidityForTokenB(sqrtPrice1: BN, sqrtPrice2: BN, tokenAmount: u64) {\n  const lowerSqrtPriceX64 = BN.min(sqrtPrice1, sqrtPrice2);\n  const upperSqrtPriceX64 = BN.max(sqrtPrice1, sqrtPrice2);\n\n  const delta = upperSqrtPriceX64.sub(lowerSqrtPriceX64);\n\n  return tokenAmount.shln(64).div(delta);\n}\n","/**\n * An enum for the direction of a swap.\n * @category Whirlpool Utils\n */\nexport enum SwapDirection {\n  AtoB = \"aToB\",\n  BtoA = \"bToA\",\n}\n\n/**\n * An enum for the token type in a Whirlpool.\n * @category Whirlpool Utils\n */\nexport enum TokenType {\n  TokenA = 1,\n  TokenB,\n}\n","import { ZERO, U64_MAX, Percentage } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { AccountFetcher } from \"../../network/public\";\nimport {\n  MIN_SQRT_PRICE,\n  MAX_SQRT_PRICE,\n  WhirlpoolData,\n  MAX_SWAP_TICK_ARRAYS,\n  TickArray,\n  SwapInput,\n} from \"../../types/public\";\nimport { adjustForSlippage } from \"../math/token-math\";\nimport { PDAUtil } from \"./pda-utils\";\nimport { PoolUtil } from \"./pool-utils\";\nimport { TickUtil } from \"./tick-utils\";\nimport { SwapDirection, TokenType } from \"./types\";\n\n/**\n * @category Whirlpool Utils\n */\nexport class SwapUtils {\n  /**\n   * Get the default values for the sqrtPriceLimit parameter in a swap.\n   * @param aToB - The direction of a swap\n   * @returns The default values for the sqrtPriceLimit parameter in a swap.\n   */\n  public static getDefaultSqrtPriceLimit(aToB: boolean) {\n    return new BN(aToB ? MIN_SQRT_PRICE : MAX_SQRT_PRICE);\n  }\n\n  /**\n   * Get the default values for the otherAmountThreshold parameter in a swap.\n   * @param amountSpecifiedIsInput - The direction of a swap\n   * @returns The default values for the otherAmountThreshold parameter in a swap.\n   */\n  public static getDefaultOtherAmountThreshold(amountSpecifiedIsInput: boolean) {\n    return amountSpecifiedIsInput ? ZERO : U64_MAX;\n  }\n\n  /**\n   * Given the intended token mint to swap, return the swap direction of a swap for a Whirlpool\n   * @param pool The Whirlpool to evaluate the mint against\n   * @param swapTokenMint The token mint PublicKey the user bases their swap against\n   * @param swapTokenIsInput Whether the swap token is the input token. (similar to amountSpecifiedIsInput from swap Ix)\n   * @returns The direction of the swap given the swapTokenMint. undefined if the token mint is not part of the trade pair of the pool.\n   */\n  public static getSwapDirection(\n    pool: WhirlpoolData,\n    swapTokenMint: PublicKey,\n    swapTokenIsInput: boolean\n  ): SwapDirection | undefined {\n    const tokenType = PoolUtil.getTokenType(pool, swapTokenMint);\n    if (!tokenType) {\n      return undefined;\n    }\n\n    return (tokenType === TokenType.TokenA) === swapTokenIsInput\n      ? SwapDirection.AtoB\n      : SwapDirection.BtoA;\n  }\n\n  /**\n   * Given the current tick-index, returns the dervied PDA and fetched data\n   * for the tick-arrays that this swap may traverse across.\n   *\n   * @category Whirlpool Utils\n   * @param tickCurrentIndex - The current tickIndex for the Whirlpool to swap on.\n   * @param tickSpacing - The tickSpacing for the Whirlpool.\n   * @param aToB - The direction of the trade.\n   * @param programId - The Whirlpool programId which the Whirlpool lives on.\n   * @param whirlpoolAddress - PublicKey of the whirlpool to swap on.\n   * @returns An array of PublicKey[] for the tickArray accounts that this swap may traverse across.\n   */\n  public static getTickArrayPublicKeys(\n    tickCurrentIndex: number,\n    tickSpacing: number,\n    aToB: boolean,\n    programId: PublicKey,\n    whirlpoolAddress: PublicKey\n  ) {\n    const shift = aToB ? 0 : tickSpacing;\n\n    let offset = 0;\n    let tickArrayAddresses: PublicKey[] = [];\n    for (let i = 0; i < MAX_SWAP_TICK_ARRAYS; i++) {\n      let startIndex: number;\n      try {\n        startIndex = TickUtil.getStartTickIndex(tickCurrentIndex + shift, tickSpacing, offset);\n      } catch {\n        return tickArrayAddresses;\n      }\n\n      const pda = PDAUtil.getTickArray(programId, whirlpoolAddress, startIndex);\n      tickArrayAddresses.push(pda.publicKey);\n      offset = aToB ? offset - 1 : offset + 1;\n    }\n\n    return tickArrayAddresses;\n  }\n\n  /**\n   * Given the current tick-index, returns TickArray objects that this swap may traverse across.\n   *\n   * @category Whirlpool Utils\n   * @param tickCurrentIndex - The current tickIndex for the Whirlpool to swap on.\n   * @param tickSpacing - The tickSpacing for the Whirlpool.\n   * @param aToB - The direction of the trade.\n   * @param programId - The Whirlpool programId which the Whirlpool lives on.\n   * @param whirlpoolAddress - PublicKey of the whirlpool to swap on.\n   * @param fetcher - AccountFetcher object to fetch solana accounts\n   * @param refresh - If true, fetcher would default to fetching the latest accounts\n   * @returns An array of PublicKey[] for the tickArray accounts that this swap may traverse across.\n   */\n  public static async getTickArrays(\n    tickCurrentIndex: number,\n    tickSpacing: number,\n    aToB: boolean,\n    programId: PublicKey,\n    whirlpoolAddress: PublicKey,\n    fetcher: AccountFetcher,\n    refresh: boolean\n  ): Promise<TickArray[]> {\n    const addresses = SwapUtils.getTickArrayPublicKeys(\n      tickCurrentIndex,\n      tickSpacing,\n      aToB,\n      programId,\n      whirlpoolAddress\n    );\n    const data = await fetcher.listTickArrays(addresses, refresh);\n    return addresses.map((addr, index) => {\n      return {\n        address: addr,\n        data: data[index],\n      };\n    });\n  }\n\n  /**\n   * Calculate the SwapInput parameters `amount` & `otherAmountThreshold` based on the amountIn & amountOut estimates from a quote.\n   * @param amount - The amount of tokens the user wanted to swap from.\n   * @param estAmountIn - The estimated amount of input tokens expected in a `SwapQuote`\n   * @param estAmountOut - The estimated amount of output tokens expected from a `SwapQuote`\n   * @param slippageTolerance - The amount of slippage to adjust for.\n   * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents in the swap quote. If true, the amount represents\n   *                                 the input token of the swap.\n   * @returns A Partial `SwapInput` object containing the slippage adjusted 'amount' & 'otherAmountThreshold' parameters.\n   */\n  public static calculateSwapAmountsFromQuote(\n    amount: BN,\n    amountSpecifiedIsInput: boolean\n  ): Pick<SwapInput, \"amount\"> {\n    if (amountSpecifiedIsInput) {\n      return {\n        amount,\n      };\n    } else {\n      return {\n        amount,\n      };\n    }\n  }\n}\n","import { Instruction } from \"@orca-so/common-sdk\";\nimport {\n  AccountLayout,\n  ASSOCIATED_TOKEN_PROGRAM_ID,\n  NATIVE_MINT,\n  Token,\n  TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { Keypair, PublicKey, SystemProgram } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nexport function isNativeMint(mint: PublicKey) {\n  return mint.equals(NATIVE_MINT);\n}\n\n// TODO: Update spl-token so we get this method\nexport function getAssociatedTokenAddressSync(\n  mint: string,\n  owner: string,\n  programId = TOKEN_PROGRAM_ID,\n  associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID\n): PublicKey {\n  const [address] = PublicKey.findProgramAddressSync(\n    [new PublicKey(owner).toBuffer(), programId.toBuffer(), new PublicKey(mint).toBuffer()],\n    associatedTokenProgramId\n  );\n\n  return address;\n}\n\n// TODO: This is a temp fn to help add payer / differing destination params to the original method\n// Deprecate this as soon as we move to sync-native. Can consider moving to common-sdk for posterity.\nexport function createWSOLAccountInstructions(\n  owner: PublicKey,\n  amountToWrap: BN,\n  accountExemption: number,\n  payer?: PublicKey,\n  unwrapDestination?: PublicKey\n): { address: PublicKey } & Instruction {\n  const payerKey = payer ?? owner;\n  const unwrapDestinationKey = unwrapDestination ?? payer ?? owner;\n  const tempAccount = new Keypair();\n\n  const createIx = SystemProgram.createAccount({\n    fromPubkey: payerKey,\n    newAccountPubkey: tempAccount.publicKey,\n    lamports: amountToWrap.toNumber() + accountExemption,\n    space: AccountLayout.span,\n    programId: TOKEN_PROGRAM_ID,\n  });\n\n  const initIx = Token.createInitAccountInstruction(\n    TOKEN_PROGRAM_ID,\n    NATIVE_MINT,\n    tempAccount.publicKey,\n    owner\n  );\n\n  const closeIx = Token.createCloseAccountInstruction(\n    TOKEN_PROGRAM_ID,\n    tempAccount.publicKey,\n    unwrapDestinationKey,\n    owner,\n    []\n  );\n\n  return {\n    address: tempAccount.publicKey,\n    instructions: [createIx, initIx],\n    cleanupInstructions: [closeIx],\n    signers: [tempAccount],\n  };\n}\n","export function convertListToMap<T>(fetchedData: T[], addresses: string[]) {\n  const result: Record<string, T> = {};\n  fetchedData.forEach((data, index) => {\n    if (data) {\n      const addr = addresses[index];\n      result[addr] = data;\n    }\n  });\n  return result;\n}\n","import { Instruction, resolveOrCreateATAs, TokenUtil } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { PoolUtil, WhirlpoolContext } from \"..\";\nimport { WhirlpoolData } from \"../types/public\";\nimport { convertListToMap } from \"./txn-utils\";\n\nexport enum TokenMintTypes {\n  ALL = \"ALL\",\n  POOL_ONLY = \"POOL_ONLY\",\n  REWARD_ONLY = \"REWARDS_ONLY\",\n}\n\n/**\n * Fetch a list of affliated tokens from a list of whirlpools\n *\n * SOL tokens does not use the ATA program and therefore not handled.\n * @param whirlpoolDatas An array of whirlpoolData (from fetcher.listPools)\n * @param mintTypes The set of mints to collect from these whirlpools\n * @returns All the whirlpool, reward token mints in the given set of whirlpools\n */\nexport function getTokenMintsFromWhirlpools(\n  whirlpoolDatas: (WhirlpoolData | null)[],\n  mintTypes = TokenMintTypes.ALL\n) {\n  let hasNativeMint = false;\n  const mints = Array.from(\n    whirlpoolDatas.reduce<Set<PublicKey>>((accu, whirlpoolData) => {\n      if (whirlpoolData) {\n        if (mintTypes === TokenMintTypes.ALL || mintTypes === TokenMintTypes.POOL_ONLY) {\n          const { tokenMintA, tokenMintB } = whirlpoolData;\n          // TODO: Once we move to sync-native for wSOL wrapping, we can simplify and use wSOL ATA instead of a custom token account.\n          if (!TokenUtil.isNativeMint(tokenMintA)) {\n            accu.add(tokenMintA);\n          } else {\n            hasNativeMint = true;\n          }\n\n          if (!TokenUtil.isNativeMint(tokenMintB)) {\n            accu.add(tokenMintB);\n          } else {\n            hasNativeMint = true;\n          }\n        }\n\n        if (mintTypes === TokenMintTypes.ALL || mintTypes === TokenMintTypes.REWARD_ONLY) {\n          const rewardInfos = whirlpoolData.rewardInfos;\n          rewardInfos.forEach((reward) => {\n            if (TokenUtil.isNativeMint(reward.mint)) {\n              hasNativeMint = true;\n            }\n            if (PoolUtil.isRewardInitialized(reward)) {\n              accu.add(reward.mint);\n            }\n          });\n        }\n      }\n      return accu;\n    }, new Set<PublicKey>())\n  );\n  return {\n    mintMap: mints,\n    hasNativeMint,\n  };\n}\n\n/**\n * Parameters to resolve ATAs for affliated tokens in a list of Whirlpools\n *\n * @category Instruction Types\n * @param mints - The list of mints to generate affliated tokens for.\n * @param accountExemption - The value from the most recent getMinimumBalanceForRentExemption().\n * @param destinationWallet - the wallet to generate ATAs against\n * @param payer - The payer address that would pay for the creation of ATA addresses\n */\nexport type ResolveAtaInstructionParams = {\n  mints: PublicKey[];\n  accountExemption: number;\n  receiver?: PublicKey;\n  payer?: PublicKey;\n};\n\n/**\n * An interface of mapping between tokenMint & ATA & the instruction set to initialize them.\n *\n * @category Instruction Types\n * @param ataTokenAddresses - A record between the token mint & generated ATA addresses\n * @param resolveAtaIxs - An array of instructions to initialize all uninitialized ATA token accounts for the list above.\n */\nexport type ResolvedATAInstructionSet = {\n  ataTokenAddresses: Record<string, PublicKey>;\n  resolveAtaIxs: Instruction[];\n};\n\n/**\n * Build instructions to resolve ATAs (Associated Tokens Addresses) for affliated tokens in a list of Whirlpools.\n * Affliated tokens are tokens that are part of the trade pair or reward in a Whirlpool.\n *\n * @param ctx - WhirlpoolContext object for the current environment.\n * @param params - ResolveAtaInstructionParams\n * @returns a ResolvedTokenAddressesIxSet containing the derived ATA addresses & ix set to initialize the accounts.\n */\nexport async function resolveAtaForMints(\n  ctx: WhirlpoolContext,\n  params: ResolveAtaInstructionParams\n): Promise<ResolvedATAInstructionSet> {\n  const { mints, receiver, payer, accountExemption } = params;\n  const receiverKey = receiver ?? ctx.wallet.publicKey;\n  const payerKey = payer ?? ctx.wallet.publicKey;\n\n  const resolvedAtaResults = await resolveOrCreateATAs(\n    ctx.connection,\n    receiverKey,\n    mints.map((tokenMint) => {\n      return { tokenMint };\n    }),\n    async () => accountExemption,\n    payerKey\n  );\n\n  // Convert the results back into the specified format\n  const { resolveAtaIxs, resolvedAtas } = resolvedAtaResults.reduce<{\n    resolvedAtas: PublicKey[];\n    resolveAtaIxs: Instruction[];\n  }>(\n    (accu, curr) => {\n      const { address, ...ix } = curr;\n      accu.resolvedAtas.push(address);\n\n      // TODO: common-sdk needs to have an easier way to check for empty instruction\n      if (ix.instructions.length) {\n        accu.resolveAtaIxs.push(ix);\n      }\n      return accu;\n    },\n    { resolvedAtas: [], resolveAtaIxs: [] }\n  );\n\n  const affliatedTokenAtaMap = convertListToMap(\n    resolvedAtas,\n    mints.map((mint) => mint.toBase58())\n  );\n  return {\n    ataTokenAddresses: affliatedTokenAtaMap,\n    resolveAtaIxs,\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { PublicKey } from \"@solana/web3.js\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to update fees and reward values for a position.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param position - PublicKey for the  position will be opened for.\n * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index.\n * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index.\n */\nexport type UpdateFeesAndRewardsParams = {\n  whirlpool: PublicKey;\n  position: PublicKey;\n  tickArrayLower: PublicKey;\n  tickArrayUpper: PublicKey;\n};\n\n/**\n * Update the accrued fees and rewards for a position.\n *\n * #### Special Errors\n * `TickNotFound` - Provided tick array account does not contain the tick for this position.\n * `LiquidityZero` - Position has zero liquidity and therefore already has the most updated fees and reward values.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - UpdateFeesAndRewardsParams object\n * @returns - Instruction to perform the action.\n */\nexport function updateFeesAndRewardsIx(\n  program: Program<Whirlpool>,\n  params: UpdateFeesAndRewardsParams\n): Instruction {\n  const { whirlpool, position, tickArrayLower, tickArrayUpper } = params;\n\n  const ix = program.instruction.updateFeesAndRewards({\n    accounts: {\n      whirlpool,\n      position,\n      tickArrayLower,\n      tickArrayUpper,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { BN } from \"@project-serum/anchor\";\n\n/**\n * Parameters to remove liquidity from a position.\n *\n * @category Instruction Types\n * @param liquidityAmount - The total amount of Liquidity the user is withdrawing\n * @param tokenMinA - The minimum amount of token A to remove from the position.\n * @param tokenMinB - The minimum amount of token B to remove from the position.\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param position - PublicKey for the  position will be opened for.\n * @param positionTokenAccount - PublicKey for the position token's associated token address.\n * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from.\n * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from.\n * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.\n * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.\n * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index.\n * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index.\n * @param positionAuthority - authority that owns the token corresponding to this desired position.\n */\nexport type DecreaseLiquidityParams = {\n  whirlpool: PublicKey;\n  position: PublicKey;\n  positionTokenAccount: PublicKey;\n  tokenOwnerAccountA: PublicKey;\n  tokenOwnerAccountB: PublicKey;\n  tokenVaultA: PublicKey;\n  tokenVaultB: PublicKey;\n  tickArrayLower: PublicKey;\n  tickArrayUpper: PublicKey;\n  positionAuthority: PublicKey;\n} & DecreaseLiquidityInput;\n\n/**\n * @category Instruction Types\n */\nexport type DecreaseLiquidityInput = {\n  tokenMinA: BN;\n  tokenMinB: BN;\n  liquidityAmount: BN;\n};\n\n/**\n * Remove liquidity to a position in the Whirlpool.\n *\n * #### Special Errors\n * - `LiquidityZero` - Provided liquidity amount is zero.\n * - `LiquidityTooHigh` - Provided liquidity exceeds u128::max.\n * - `TokenMinSubceeded` - The required token to perform this operation subceeds the user defined amount.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - DecreaseLiquidityParams object\n * @returns - Instruction to perform the action.\n */\nexport function decreaseLiquidityIx(\n  program: Program<Whirlpool>,\n  params: DecreaseLiquidityParams\n): Instruction {\n  const {\n    liquidityAmount,\n    tokenMinA,\n    tokenMinB,\n    whirlpool,\n    positionAuthority,\n    position,\n    positionTokenAccount,\n    tokenOwnerAccountA,\n    tokenOwnerAccountB,\n    tokenVaultA,\n    tokenVaultB,\n    tickArrayLower,\n    tickArrayUpper,\n  } = params;\n\n  const ix = program.instruction.decreaseLiquidity(liquidityAmount, tokenMinA, tokenMinB, {\n    accounts: {\n      whirlpool,\n      tokenProgram: TOKEN_PROGRAM_ID,\n      positionAuthority,\n      position,\n      positionTokenAccount,\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA,\n      tokenVaultB,\n      tickArrayLower,\n      tickArrayUpper,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program, BN } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { TOKEN_PROGRAM_ID, u64 } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to increase liquidity for a position.\n *\n * @category Instruction Types\n * @param liquidityAmount - The total amount of Liquidity the user is willing to deposit.\n * @param tokenMaxA - The maximum amount of token A to add to the position.\n * @param tokenMaxB - The maximum amount of token B to add to the position.\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param position - PublicKey for the  position will be opened for.\n * @param positionTokenAccount - PublicKey for the position token's associated token address.\n * @param tokenOwnerAccountA - PublicKey for the token A account that will be withdrawed from.\n * @param tokenOwnerAccountB - PublicKey for the token B account that will be withdrawed from.\n * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.\n * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.\n * @param tickArrayLower - PublicKey for the tick-array account that hosts the tick at the lower tick index.\n * @param tickArrayUpper - PublicKey for the tick-array account that hosts the tick at the upper tick index.\n * @param positionAuthority - authority that owns the token corresponding to this desired position.\n */\nexport type IncreaseLiquidityParams = {\n  whirlpool: PublicKey;\n  position: PublicKey;\n  positionTokenAccount: PublicKey;\n  tokenOwnerAccountA: PublicKey;\n  tokenOwnerAccountB: PublicKey;\n  tokenVaultA: PublicKey;\n  tokenVaultB: PublicKey;\n  tickArrayLower: PublicKey;\n  tickArrayUpper: PublicKey;\n  positionAuthority: PublicKey;\n} & IncreaseLiquidityInput;\n\n/**\n * Input parameters to deposit liquidity into a position.\n *\n * This type is usually generated by a quote class to estimate the amount of tokens required to\n * deposit a certain amount of liquidity into a position.\n *\n * @category Instruction Types\n * @param tokenMaxA - the maximum amount of tokenA allowed to withdraw from the source wallet.\n * @param tokenMaxB - the maximum amount of tokenB allowed to withdraw from the source wallet.\n * @param liquidityAmount - the desired amount of liquidity to deposit into the position/\n */\nexport type IncreaseLiquidityInput = {\n  tokenMaxA: u64;\n  tokenMaxB: u64;\n  liquidityAmount: BN;\n};\n\n/**\n * Add liquidity to a position in the Whirlpool.\n *\n * #### Special Errors\n * `LiquidityZero` - Provided liquidity amount is zero.\n * `LiquidityTooHigh` - Provided liquidity exceeds u128::max.\n * `TokenMaxExceeded` - The required token to perform this operation exceeds the user defined amount.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - IncreaseLiquidityParams object\n * @returns - Instruction to perform the action.\n */\nexport function increaseLiquidityIx(\n  program: Program<Whirlpool>,\n  params: IncreaseLiquidityParams\n): Instruction {\n  const {\n    liquidityAmount,\n    tokenMaxA,\n    tokenMaxB,\n    whirlpool,\n    positionAuthority,\n    position,\n    positionTokenAccount,\n    tokenOwnerAccountA,\n    tokenOwnerAccountB,\n    tokenVaultA,\n    tokenVaultB,\n    tickArrayLower,\n    tickArrayUpper,\n  } = params;\n\n  const ix = program.instruction.increaseLiquidity(liquidityAmount, tokenMaxA, tokenMaxB, {\n    accounts: {\n      whirlpool,\n      tokenProgram: TOKEN_PROGRAM_ID,\n      positionAuthority,\n      position,\n      positionTokenAccount,\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA,\n      tokenVaultB,\n      tickArrayLower,\n      tickArrayUpper,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { SystemProgram, Keypair, PublicKey } from \"@solana/web3.js\";\nimport { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to initialize a WhirlpoolsConfig account.\n *\n * @category Instruction Types\n * @param whirlpoolsConfigKeypair - Generated keypair for the WhirlpoolsConfig.\n * @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees.\n * @param collect_protocol_fees_authority - Authority authorized to collect protocol fees.\n * @param rewardEmissionsSuperAuthority - Authority authorized to set reward authorities in pools.\n * @param defaultProtocolFeeRate - The default protocol fee rate. Stored as a basis point of the total fees collected by feeRate.\n * @param funder - The account that would fund the creation of this account\n */\nexport type InitConfigParams = {\n  whirlpoolsConfigKeypair: Keypair;\n  feeAuthority: PublicKey;\n  collectProtocolFeesAuthority: PublicKey;\n  rewardEmissionsSuperAuthority: PublicKey;\n  defaultProtocolFeeRate: number;\n  funder: PublicKey;\n};\n\n/**\n * Initializes a WhirlpoolsConfig account that hosts info & authorities\n * required to govern a set of Whirlpools.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - InitConfigParams object\n * @returns - Instruction to perform the action.\n */\nexport function initializeConfigIx(\n  program: Program<Whirlpool>,\n  params: InitConfigParams\n): Instruction {\n  const {\n    feeAuthority,\n    collectProtocolFeesAuthority,\n    rewardEmissionsSuperAuthority,\n    defaultProtocolFeeRate,\n    funder,\n  } = params;\n\n  const ix = program.instruction.initializeConfig(\n    feeAuthority,\n    collectProtocolFeesAuthority,\n    rewardEmissionsSuperAuthority,\n    defaultProtocolFeeRate,\n    {\n      accounts: {\n        config: params.whirlpoolsConfigKeypair.publicKey,\n        funder,\n        systemProgram: SystemProgram.programId,\n      },\n    }\n  );\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [params.whirlpoolsConfigKeypair],\n  };\n}\n","import { SystemProgram, PublicKey } from \"@solana/web3.js\";\nimport { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { PDA } from \"@orca-so/common-sdk\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to initialize a FeeTier account.\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - PublicKey for the whirlpool config space that the fee-tier will be initialized for.\n * @param feeTierPda - PDA for the fee-tier account that will be initialized\n * @param tickSpacing - The tick spacing this fee tier recommends its default fee rate for.\n * @param defaultFeeRate - The default fee rate for this fee-tier. Stored as a hundredths of a basis point.\n * @param feeAuthority - Authority authorized to initialize fee-tiers and set customs fees.\n * @param funder - The account that would fund the creation of this account\n */\nexport type InitFeeTierParams = {\n  whirlpoolsConfig: PublicKey;\n  feeTierPda: PDA;\n  tickSpacing: number;\n  defaultFeeRate: number;\n  feeAuthority: PublicKey;\n  funder: PublicKey;\n};\n\n/**\n * Initializes a fee tier account usable by Whirlpools in this WhirlpoolsConfig space.\n *\n *  Special Errors\n * `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - InitFeeTierParams object\n * @returns - Instruction to perform the action.\n */\nexport function initializeFeeTierIx(\n  program: Program<Whirlpool>,\n  params: InitFeeTierParams\n): Instruction {\n  const { feeTierPda, whirlpoolsConfig, tickSpacing, feeAuthority, defaultFeeRate, funder } =\n    params;\n\n  const ix = program.instruction.initializeFeeTier(tickSpacing, defaultFeeRate, {\n    accounts: {\n      config: whirlpoolsConfig,\n      feeTier: feeTierPda.publicKey,\n      feeAuthority,\n      funder,\n      systemProgram: SystemProgram.programId,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { SystemProgram, SYSVAR_RENT_PUBKEY, PublicKey, Keypair } from \"@solana/web3.js\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { WhirlpoolBumpsData } from \"../types/public/anchor-types\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { BN } from \"@project-serum/anchor\";\nimport { PDA } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to initialize a Whirlpool account.\n *\n * @category Instruction Types\n * @param initSqrtPrice - The desired initial sqrt-price for this pool\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param whirlpoolPda - PDA for the whirlpool account that would be initialized\n * @param tokenMintA - Mint public key for token A\n * @param tokenMintB - Mint public key for token B\n * @param tokenVaultAKeypair - Keypair of the token A vault for this pool\n * @param tokenVaultBKeypair - Keypair of the token B vault for this pool\n * @param feeTierKey - PublicKey of the fee-tier account that this pool would use for the fee-rate\n * @param tickSpacing - The desired tick spacing for this pool.\n * @param funder - The account that would fund the creation of this account\n */\nexport type InitPoolParams = {\n  initSqrtPrice: BN;\n  whirlpoolsConfig: PublicKey;\n  whirlpoolPda: PDA;\n  tokenMintA: PublicKey;\n  tokenMintB: PublicKey;\n  tokenVaultAKeypair: Keypair;\n  tokenVaultBKeypair: Keypair;\n  feeTierKey: PublicKey;\n  tickSpacing: number;\n  funder: PublicKey;\n};\n\n/**\n * Initializes a tick_array account to represent a tick-range in a Whirlpool.\n *\n * Special Errors\n * `InvalidTokenMintOrder` - The order of mints have to be ordered by\n * `SqrtPriceOutOfBounds` - provided initial_sqrt_price is not between 2^-64 to 2^64\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - InitPoolParams object\n * @returns - Instruction to perform the action.\n */\nexport function initializePoolIx(program: Program<Whirlpool>, params: InitPoolParams): Instruction {\n  const {\n    initSqrtPrice,\n    tokenMintA,\n    tokenMintB,\n    whirlpoolsConfig,\n    whirlpoolPda,\n    feeTierKey,\n    tokenVaultAKeypair,\n    tokenVaultBKeypair,\n    tickSpacing,\n    funder,\n  } = params;\n\n  const whirlpoolBumps: WhirlpoolBumpsData = {\n    whirlpoolBump: whirlpoolPda.bump,\n  };\n\n  const ix = program.instruction.initializePool(whirlpoolBumps, tickSpacing, initSqrtPrice, {\n    accounts: {\n      whirlpoolsConfig,\n      tokenMintA,\n      tokenMintB,\n      funder,\n      whirlpool: whirlpoolPda.publicKey,\n      tokenVaultA: tokenVaultAKeypair.publicKey,\n      tokenVaultB: tokenVaultBKeypair.publicKey,\n      feeTier: feeTierKey,\n      tokenProgram: TOKEN_PROGRAM_ID,\n      systemProgram: SystemProgram.programId,\n      rent: SYSVAR_RENT_PUBKEY,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [tokenVaultAKeypair, tokenVaultBKeypair],\n  };\n}\n","import * as anchor from \"@project-serum/anchor\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { SystemProgram, Keypair, PublicKey } from \"@solana/web3.js\";\nimport { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\n\nimport { Instruction } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to initialize a rewards for a Whirlpool\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool config space that the fee-tier will be initialized for.\n * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).\n * @param rewardMint - PublicKey for the reward mint that we'd use for the reward index.\n * @param rewardVaultKeypair - Keypair of the vault for this reward index.\n * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool\n * @param funder - The account that would fund the creation of this account\n */\nexport type InitializeRewardParams = {\n  whirlpool: PublicKey;\n  rewardIndex: number;\n  rewardMint: PublicKey;\n  rewardVaultKeypair: Keypair;\n  rewardAuthority: PublicKey;\n  funder: PublicKey;\n};\n\n/**\n * Initialize reward for a Whirlpool. A pool can only support up to a set number of rewards.\n * The initial emissionsPerSecond is set to 0.\n *\n * #### Special Errors\n * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n *                          or exceeds NUM_REWARDS, or all reward slots for this pool has been initialized.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - InitializeRewardParams object\n * @returns - Instruction to perform the action.\n */\nexport function initializeRewardIx(\n  program: Program<Whirlpool>,\n  params: InitializeRewardParams\n): Instruction {\n  const { rewardAuthority, funder, whirlpool, rewardMint, rewardVaultKeypair, rewardIndex } =\n    params;\n\n  const ix = program.instruction.initializeReward(rewardIndex, {\n    accounts: {\n      rewardAuthority,\n      funder,\n      whirlpool,\n      rewardMint,\n      rewardVault: rewardVaultKeypair.publicKey,\n      tokenProgram: TOKEN_PROGRAM_ID,\n      systemProgram: SystemProgram.programId,\n      rent: anchor.web3.SYSVAR_RENT_PUBKEY,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [rewardVaultKeypair],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport * as anchor from \"@project-serum/anchor\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { PDA } from \"@orca-so/common-sdk\";\n\n/**\n * Parameters to initialize a TickArray account.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool that the initialized tick-array will host ticks for.\n * @param tickArrayPda - PDA for the tick array account that will be initialized\n * @param startTick - The starting tick index for this tick-array. Has to be a multiple of TickArray size & the tick spacing of this pool.\n * @param funder - The account that would fund the creation of this account\n */\nexport type InitTickArrayParams = {\n  whirlpool: PublicKey;\n  tickArrayPda: PDA;\n  startTick: number;\n  funder: PublicKey;\n};\n\n/**\n * Initializes a TickArray account.\n *\n * #### Special Errors\n *  `InvalidStartTick` - if the provided start tick is out of bounds or is not a multiple of TICK_ARRAY_SIZE * tick spacing.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - InitTickArrayParams object\n * @returns - Instruction to perform the action.\n */\nexport function initTickArrayIx(\n  program: Program<Whirlpool>,\n  params: InitTickArrayParams\n): Instruction {\n  const { whirlpool, funder, tickArrayPda } = params;\n\n  const ix = program.instruction.initializeTickArray(params.startTick, {\n    accounts: {\n      whirlpool,\n      funder,\n      tickArray: tickArrayPda.publicKey,\n      systemProgram: anchor.web3.SystemProgram.programId,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { PDA, Instruction } from \"@orca-so/common-sdk\";\nimport { METADATA_PROGRAM_ADDRESS } from \"..\";\nimport {\n  OpenPositionBumpsData,\n  OpenPositionWithMetadataBumpsData,\n} from \"../types/public/anchor-types\";\nimport { openPositionAccounts } from \"../utils/instructions-util\";\n\n/**\n * Parameters to open a position in a Whirlpool.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param ownerKey - PublicKey for the wallet that will host the minted position token.\n * @param positionPda - PDA for the derived position address.\n * @param positionMintAddress - PublicKey for the mint token for the Position token.\n * @param positionTokenAccount - The associated token address for the position token in the owners wallet.\n * @param tickLowerIndex - The tick specifying the lower end of the position range.\n * @param tickUpperIndex - The tick specifying the upper end of the position range.\n * @param funder - The account that would fund the creation of this account\n */\nexport type OpenPositionParams = {\n  whirlpool: PublicKey;\n  owner: PublicKey;\n  positionPda: PDA;\n  positionMintAddress: PublicKey;\n  positionTokenAccount: PublicKey;\n  tickLowerIndex: number;\n  tickUpperIndex: number;\n  funder: PublicKey;\n};\n\n/**\n * Open a position in a Whirlpool. A unique token will be minted to represent the position in the users wallet.\n * The position will start off with 0 liquidity.\n *\n * #### Special Errors\n * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - OpenPositionParams object\n * @returns - Instruction to perform the action.\n */\nexport function openPositionIx(\n  program: Program<Whirlpool>,\n  params: OpenPositionParams\n): Instruction {\n  const { positionPda, tickLowerIndex, tickUpperIndex } = params;\n\n  const bumps: OpenPositionBumpsData = {\n    positionBump: positionPda.bump,\n  };\n\n  const ix = program.instruction.openPosition(bumps, tickLowerIndex, tickUpperIndex, {\n    accounts: openPositionAccounts(params),\n  });\n\n  // TODO: Require Keypair and auto sign this ix\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n\n/**\n * Open a position in a Whirlpool. A unique token will be minted to represent the position\n * in the users wallet. Additional Metaplex metadata is appended to identify the token.\n * The position will start off with 0 liquidity.\n *\n * #### Special Errors\n * `InvalidTickIndex` - If a provided tick is out of bounds, out of order or not a multiple of the tick-spacing in this pool.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - OpenPositionParams object and a derived PDA that hosts the position's metadata.\n * @returns - Instruction to perform the action.\n */\nexport function openPositionWithMetadataIx(\n  program: Program<Whirlpool>,\n  params: OpenPositionParams & { metadataPda: PDA }\n): Instruction {\n  const { positionPda, metadataPda, tickLowerIndex, tickUpperIndex } = params;\n\n  const bumps: OpenPositionWithMetadataBumpsData = {\n    positionBump: positionPda.bump,\n    metadataBump: metadataPda.bump,\n  };\n\n  const ix = program.instruction.openPositionWithMetadata(bumps, tickLowerIndex, tickUpperIndex, {\n    accounts: {\n      ...openPositionAccounts(params),\n      positionMetadataAccount: metadataPda.publicKey,\n      metadataProgram: METADATA_PROGRAM_ADDRESS,\n      metadataUpdateAuth: new PublicKey(\"3axbTs2z5GBy6usVbNVoqEgZMng3vZvMnAoX29BFfwhr\"),\n    },\n  });\n\n  // TODO: Require Keypair and auto sign this ix\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { OpenPositionParams } from \"../instructions\";\nimport * as anchor from \"@project-serum/anchor\";\nimport { SystemProgram } from \"@solana/web3.js\";\n\nexport function openPositionAccounts(params: OpenPositionParams) {\n  const {\n    funder,\n    owner,\n    positionPda,\n    positionMintAddress,\n    positionTokenAccount: positionTokenAccountAddress,\n    whirlpool: whirlpoolKey,\n  } = params;\n  return {\n    funder: funder,\n    owner,\n    position: positionPda.publicKey,\n    positionMint: positionMintAddress,\n    positionTokenAccount: positionTokenAccountAddress,\n    whirlpool: whirlpoolKey,\n    tokenProgram: TOKEN_PROGRAM_ID,\n    systemProgram: SystemProgram.programId,\n    rent: anchor.web3.SYSVAR_RENT_PUBKEY,\n    associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID,\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set the collect fee authority in a WhirlpoolsConfig\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param collectProtocolFeesAuthority - The current collectProtocolFeesAuthority in the WhirlpoolsConfig\n * @param newCollectProtocolFeesAuthority - The new collectProtocolFeesAuthority in the WhirlpoolsConfig\n */\nexport type SetCollectProtocolFeesAuthorityParams = {\n  whirlpoolsConfig: PublicKey;\n  collectProtocolFeesAuthority: PublicKey;\n  newCollectProtocolFeesAuthority: PublicKey;\n};\n\n/**\n * Sets the fee authority to collect protocol fees for a WhirlpoolsConfig.\n * Only the current collect protocol fee authority has permission to invoke this instruction.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetCollectProtocolFeesAuthorityParams object\n * @returns - Instruction to perform the action.\n */\nexport function setCollectProtocolFeesAuthorityIx(\n  program: Program<Whirlpool>,\n  params: SetCollectProtocolFeesAuthorityParams\n): Instruction {\n  const { whirlpoolsConfig, collectProtocolFeesAuthority, newCollectProtocolFeesAuthority } =\n    params;\n\n  const ix = program.instruction.setCollectProtocolFeesAuthority({\n    accounts: {\n      whirlpoolsConfig,\n      collectProtocolFeesAuthority,\n      newCollectProtocolFeesAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\nimport { PDAUtil } from \"../utils/public\";\n\n/**\n * Parameters to set the default fee rate for a FeeTier.\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this fee-tier is initialized in\n * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.\n * @param tickSpacing - The tick spacing of the fee-tier that we would like to update.\n * @param defaultFeeRate - The new default fee rate for this fee-tier. Stored as a hundredths of a basis point.\n */\nexport type SetDefaultFeeRateParams = {\n  whirlpoolsConfig: PublicKey;\n  feeAuthority: PublicKey;\n  tickSpacing: number;\n  defaultFeeRate: number;\n};\n\n/**\n * Updates a fee tier account with a new default fee rate. The new rate will not retroactively update\n * initialized pools.\n *\n * #### Special Errors\n * - `FeeRateMaxExceeded` - If the provided default_fee_rate exceeds MAX_FEE_RATE.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetDefaultFeeRateParams object\n * @returns - Instruction to perform the action.\n */\nexport function setDefaultFeeRateIx(\n  program: Program<Whirlpool>,\n  params: SetDefaultFeeRateParams\n): Instruction {\n  const { whirlpoolsConfig, feeAuthority, tickSpacing, defaultFeeRate } = params;\n\n  const feeTierPda = PDAUtil.getFeeTier(program.programId, whirlpoolsConfig, tickSpacing);\n\n  const ix = program.instruction.setDefaultFeeRate(defaultFeeRate, {\n    accounts: {\n      whirlpoolsConfig,\n      feeTier: feeTierPda.publicKey,\n      feeAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set the default fee rate for a FeeTier.\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.\n * @param defaultProtocolFeeRate - The new default protocol fee rate for this config. Stored as a basis point of the total fees collected by feeRate.\n */\nexport type SetDefaultProtocolFeeRateParams = {\n  whirlpoolsConfig: PublicKey;\n  feeAuthority: PublicKey;\n  defaultProtocolFeeRate: number;\n};\n\n/**\n * Updates a WhirlpoolsConfig with a new default protocol fee rate. The new rate will not retroactively update\n * initialized pools.\n *\n * #### Special Errors\n * - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetDefaultFeeRateParams object\n * @returns - Instruction to perform the action.\n */\nexport function setDefaultProtocolFeeRateIx(\n  program: Program<Whirlpool>,\n  params: SetDefaultProtocolFeeRateParams\n): Instruction {\n  const { whirlpoolsConfig, feeAuthority, defaultProtocolFeeRate } = params;\n\n  const ix = program.instruction.setDefaultProtocolFeeRate(defaultProtocolFeeRate, {\n    accounts: {\n      whirlpoolsConfig,\n      feeAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set the fee authority in a WhirlpoolsConfig\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param feeAuthority - The current feeAuthority in the WhirlpoolsConfig\n * @param newFeeAuthority - The new feeAuthority in the WhirlpoolsConfig\n */\nexport type SetFeeAuthorityParams = {\n  whirlpoolsConfig: PublicKey;\n  feeAuthority: PublicKey;\n  newFeeAuthority: PublicKey;\n};\n\n/**\n * Sets the fee authority for a WhirlpoolsConfig.\n * The fee authority can set the fee & protocol fee rate for individual pools or set the default fee rate for newly minted pools.\n * Only the current fee authority has permission to invoke this instruction.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetFeeAuthorityParams object\n * @returns - Instruction to perform the action.\n */\nexport function setFeeAuthorityIx(\n  program: Program<Whirlpool>,\n  params: SetFeeAuthorityParams\n): Instruction {\n  const { whirlpoolsConfig, feeAuthority, newFeeAuthority } = params;\n\n  const ix = program.instruction.setFeeAuthority({\n    accounts: {\n      whirlpoolsConfig,\n      feeAuthority,\n      newFeeAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set fee rate for a Whirlpool.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space.\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.\n * @param feeRate - The new fee rate for this fee-tier. Stored as a hundredths of a basis point.\n */\nexport type SetFeeRateParams = {\n  whirlpool: PublicKey;\n  whirlpoolsConfig: PublicKey;\n  feeAuthority: PublicKey;\n  feeRate: number;\n};\n\n/**\n * Sets the fee rate for a Whirlpool.\n * Only the current fee authority has permission to invoke this instruction.\n *\n * #### Special Errors\n * - `FeeRateMaxExceeded` - If the provided fee_rate exceeds MAX_FEE_RATE.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetFeeRateParams object\n * @returns - Instruction to perform the action.\n */\nexport function setFeeRateIx(program: Program<Whirlpool>, params: SetFeeRateParams): Instruction {\n  const { whirlpoolsConfig, whirlpool, feeAuthority, feeRate } = params;\n\n  const ix = program.instruction.setFeeRate(feeRate, {\n    accounts: {\n      whirlpoolsConfig,\n      whirlpool,\n      feeAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set fee rate for a Whirlpool.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space.\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param feeAuthority - Authority authorized in the WhirlpoolsConfig to set default fee rates.\n * @param protocolFeeRate - The new default protocol fee rate for this pool. Stored as a basis point of the total fees collected by feeRate.\n */\nexport type SetProtocolFeeRateParams = {\n  whirlpool: PublicKey;\n  whirlpoolsConfig: PublicKey;\n  feeAuthority: PublicKey;\n  protocolFeeRate: number;\n};\n\n/**\n * Sets the protocol fee rate for a Whirlpool.\n * Only the current fee authority has permission to invoke this instruction.\n *\n * #### Special Errors\n * - `ProtocolFeeRateMaxExceeded` - If the provided default_protocol_fee_rate exceeds MAX_PROTOCOL_FEE_RATE.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetFeeRateParams object\n * @returns - Instruction to perform the action.\n */\nexport function setProtocolFeeRateIx(\n  program: Program<Whirlpool>,\n  params: SetProtocolFeeRateParams\n): Instruction {\n  const { whirlpoolsConfig, whirlpool, feeAuthority, protocolFeeRate } = params;\n\n  const ix = program.instruction.setProtocolFeeRate(protocolFeeRate, {\n    accounts: {\n      whirlpoolsConfig,\n      whirlpool,\n      feeAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to update the reward authority at a particular rewardIndex on a Whirlpool.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool to update. This whirlpool has to be part of the provided WhirlpoolsConfig space.\n * @param whirlpoolsConfig - The public key for the WhirlpoolsConfig this pool is initialized in\n * @param rewardIndex - The reward index that we'd like to update. (0 <= index <= NUM_REWARDS).\n * @param rewardEmissionsSuperAuthority - The current rewardEmissionsSuperAuthority in the WhirlpoolsConfig\n * @param newRewardAuthority - The new rewardAuthority in the Whirlpool at the rewardIndex\n */\nexport type SetRewardAuthorityBySuperAuthorityParams = {\n  whirlpool: PublicKey;\n  whirlpoolsConfig: PublicKey;\n  rewardIndex: number;\n  rewardEmissionsSuperAuthority: PublicKey;\n  newRewardAuthority: PublicKey;\n};\n\n/**\n * Set the whirlpool reward authority at the provided `reward_index`.\n * Only the current reward super authority has permission to invoke this instruction.\n *\n * #### Special Errors\n * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n *                          or exceeds NUM_REWARDS.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetRewardAuthorityParams object\n * @returns - Instruction to perform the action.\n */\nexport function setRewardAuthorityBySuperAuthorityIx(\n  program: Program<Whirlpool>,\n  params: SetRewardAuthorityBySuperAuthorityParams\n): Instruction {\n  const {\n    whirlpoolsConfig,\n    whirlpool,\n    rewardEmissionsSuperAuthority,\n    newRewardAuthority,\n    rewardIndex,\n  } = params;\n\n  const ix = program.instruction.setRewardAuthorityBySuperAuthority(rewardIndex, {\n    accounts: {\n      whirlpoolsConfig,\n      whirlpool,\n      rewardEmissionsSuperAuthority,\n      newRewardAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to update the reward authority at a particular rewardIndex on a Whirlpool.\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool to update.\n * @param rewardIndex - The reward index that we'd like to update. (0 <= index <= NUM_REWARDS).\n * @param rewardAuthority - The current rewardAuthority in the Whirlpool at the rewardIndex\n * @param newRewardAuthority - The new rewardAuthority in the Whirlpool at the rewardIndex\n */\nexport type SetRewardAuthorityParams = {\n  whirlpool: PublicKey;\n  rewardIndex: number;\n  rewardAuthority: PublicKey;\n  newRewardAuthority: PublicKey;\n};\n\n/**\n * Set the whirlpool reward authority at the provided `reward_index`.\n * Only the current reward authority for this reward index has permission to invoke this instruction.\n *\n * #### Special Errors\n * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n *                          or exceeds NUM_REWARDS.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetRewardAuthorityParams object\n * @returns - Instruction to perform the action.\n */\nexport function setRewardAuthorityIx(\n  program: Program<Whirlpool>,\n  params: SetRewardAuthorityParams\n): Instruction {\n  const { whirlpool, rewardAuthority, newRewardAuthority, rewardIndex } = params;\n  const ix = program.instruction.setRewardAuthority(rewardIndex, {\n    accounts: {\n      whirlpool,\n      rewardAuthority,\n      newRewardAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { BN } from \"@project-serum/anchor\";\n\n/**\n * Parameters to set rewards emissions for a reward in a Whirlpool\n *\n * @category Instruction Types\n * @param whirlpool - PublicKey for the whirlpool which the reward resides in.\n * @param rewardIndex - The reward index that we'd like to initialize. (0 <= index <= NUM_REWARDS).\n * @param rewardVaultKey - PublicKey of the vault for this reward index.\n * @param rewardAuthority - Assigned authority by the reward_super_authority for the specified reward-index in this Whirlpool\n * @param emissionsPerSecondX64 - The new emissions per second to set for this reward.\n */\nexport type SetRewardEmissionsParams = {\n  whirlpool: PublicKey;\n  rewardIndex: number;\n  rewardVaultKey: PublicKey;\n  rewardAuthority: PublicKey;\n  emissionsPerSecondX64: BN;\n};\n\n/**\n * Set the reward emissions for a reward in a Whirlpool.\n *\n * #### Special Errors\n * - `RewardVaultAmountInsufficient` - The amount of rewards in the reward vault cannot emit more than a day of desired emissions.\n * - `InvalidTimestamp` - Provided timestamp is not in order with the previous timestamp.\n * - `InvalidRewardIndex` - If the provided reward index doesn't match the lowest uninitialized index in this pool,\n *                          or exceeds NUM_REWARDS.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetRewardEmissionsParams object\n * @returns - Instruction to perform the action.\n */\nexport function setRewardEmissionsIx(\n  program: Program<Whirlpool>,\n  params: SetRewardEmissionsParams\n): Instruction {\n  const {\n    rewardAuthority,\n    whirlpool,\n    rewardIndex,\n    rewardVaultKey: rewardVault,\n    emissionsPerSecondX64,\n  } = params;\n\n  const ix = program.instruction.setRewardEmissions(rewardIndex, emissionsPerSecondX64, {\n    accounts: {\n      rewardAuthority,\n      whirlpool,\n      rewardVault,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Program } from \"@project-serum/anchor\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\nimport { Instruction } from \"@orca-so/common-sdk\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n/**\n * Parameters to set rewards emissions for a reward in a Whirlpool\n *\n * @category Instruction Types\n * @param whirlpoolsConfig - PublicKey for the WhirlpoolsConfig that we want to update.\n * @param rewardEmissionsSuperAuthority - Current reward emission super authority in this WhirlpoolsConfig\n * @param newRewardEmissionsSuperAuthority - New reward emission super authority for this WhirlpoolsConfig\n */\nexport type SetRewardEmissionsSuperAuthorityParams = {\n  whirlpoolsConfig: PublicKey;\n  rewardEmissionsSuperAuthority: PublicKey;\n  newRewardEmissionsSuperAuthority: PublicKey;\n};\n\n/**\n * Set the whirlpool reward super authority for a WhirlpoolsConfig\n * Only the current reward super authority has permission to invoke this instruction.\n * This instruction will not change the authority on any `WhirlpoolRewardInfo` whirlpool rewards.\n *\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SetRewardEmissionsSuperAuthorityParams object\n * @returns - Instruction to perform the action.\n */\nexport function setRewardEmissionsSuperAuthorityIx(\n  program: Program<Whirlpool>,\n  params: SetRewardEmissionsSuperAuthorityParams\n): Instruction {\n  const { whirlpoolsConfig, rewardEmissionsSuperAuthority, newRewardEmissionsSuperAuthority } =\n    params;\n\n  const ix = program.instruction.setRewardEmissionsSuperAuthority({\n    accounts: {\n      whirlpoolsConfig,\n      rewardEmissionsSuperAuthority: rewardEmissionsSuperAuthority,\n      newRewardEmissionsSuperAuthority,\n    },\n  });\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import { Instruction } from \"@orca-so/common-sdk\";\nimport { BN, Program } from \"@project-serum/anchor\";\nimport { TOKEN_PROGRAM_ID, u64 } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { Whirlpool } from \"../artifacts/whirlpool\";\n\n/**\n * Parameters and accounts to swap on a Whirlpool\n *\n * @category Instruction Types\n * @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A.\n * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents\n *                                 the input token of the swap.\n * @param amount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).\n * @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).\n * @param sqrtPriceLimit - The maximum/minimum price the swap will swap to.\n * @param tickArray0 - PublicKey of the tick-array where the Whirlpool's currentTickIndex resides in\n * @param tickArray1 - The next tick-array in the swap direction. If the swap will not reach the next tick-aray, input the same array as tickArray0.\n * @param tickArray2 - The next tick-array in the swap direction after tickArray2. If the swap will not reach the next tick-aray, input the same array as tickArray1.\n * @param whirlpool - PublicKey for the whirlpool that the position will be opened for.\n * @param tokenOwnerAccountA - PublicKey for the associated token account for tokenA in the collection wallet\n * @param tokenOwnerAccountB - PublicKey for the associated token account for tokenB in the collection wallet\n * @param tokenVaultA - PublicKey for the tokenA vault for this whirlpool.\n * @param tokenVaultB - PublicKey for the tokenB vault for this whirlpool.\n * @param oracle - PublicKey for the oracle account for this Whirlpool.\n * @param tokenAuthority - authority to withdraw tokens from the input token account\n */\nexport type SwapParams = SwapInput & {\n  whirlpool: PublicKey;\n  tokenOwnerAccountA: PublicKey;\n  tokenOwnerAccountB: PublicKey;\n  tokenVaultA: PublicKey;\n  tokenVaultB: PublicKey;\n  oracle: PublicKey;\n  tokenAuthority: PublicKey;\n};\n\n/**\n * Parameters to swap on a Whirlpool\n *\n * @category Instruction Types\n * @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A.\n * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents\n *                                 the input token of the swap.\n * @param amount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).\n * @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).\n * @param sqrtPriceLimit - The maximum/minimum price the swap will swap to.\n * @param tickArray0 - PublicKey of the tick-array where the Whirlpool's currentTickIndex resides in\n * @param tickArray1 - The next tick-array in the swap direction. If the swap will not reach the next tick-aray, input the same array as tickArray0.\n * @param tickArray2 - The next tick-array in the swap direction after tickArray2. If the swap will not reach the next tick-aray, input the same array as tickArray1.\n */\nexport type SwapInput = {\n  amount: u64;\n  otherAmountThreshold: u64;\n  sqrtPriceLimit: BN;\n  amountSpecifiedIsInput: boolean;\n  aToB: boolean;\n  tickArray0: PublicKey;\n  tickArray1: PublicKey;\n  tickArray2: PublicKey;\n};\n\n/**\n * Parameters to swap on a Whirlpool with developer fees\n *\n * @category Instruction Types\n * @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A.\n * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents\n *                                 the input token of the swap.\n * @param amount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).\n * @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).\n * @param sqrtPriceLimit - The maximum/minimum price the swap will swap to.\n * @param tickArray0 - PublicKey of the tick-array where the Whirlpool's currentTickIndex resides in\n * @param tickArray1 - The next tick-array in the swap direction. If the swap will not reach the next tick-aray, input the same array as tickArray0.\n * @param tickArray2 - The next tick-array in the swap direction after tickArray2. If the swap will not reach the next tick-aray, input the same array as tickArray1.\n * @param devFeeAmount -  FeeAmount (developer fees) charged on this swap\n */\nexport type DevFeeSwapInput = SwapInput & {\n  devFeeAmount: u64;\n};\n\n/**\n * Perform a swap in this Whirlpool\n *\n * #### Special Errors\n * - `ZeroTradableAmount` - User provided parameter `amount` is 0.\n * - `InvalidSqrtPriceLimitDirection` - User provided parameter `sqrt_price_limit` does not match the direction of the trade.\n * - `SqrtPriceOutOfBounds` - User provided parameter `sqrt_price_limit` is over Whirlppool's max/min bounds for sqrt-price.\n * - `InvalidTickArraySequence` - User provided tick-arrays are not in sequential order required to proceed in this trade direction.\n * - `TickArraySequenceInvalidIndex` - The swap loop attempted to access an invalid array index during the query of the next initialized tick.\n * - `TickArrayIndexOutofBounds` - The swap loop attempted to access an invalid array index during tick crossing.\n * - `LiquidityOverflow` - Liquidity value overflowed 128bits during tick crossing.\n * - `InvalidTickSpacing` - The swap pool was initialized with tick-spacing of 0.\n *\n * ### Parameters\n * @category Instructions\n * @param context - Context object containing services required to generate the instruction\n * @param params - SwapParams object\n * @returns - Instruction to perform the action.\n */\nexport function swapIx(program: Program<Whirlpool>, params: SwapParams): Instruction {\n  const {\n    amount,\n    otherAmountThreshold,\n    sqrtPriceLimit,\n    amountSpecifiedIsInput,\n    aToB,\n    whirlpool,\n    tokenAuthority,\n    tokenOwnerAccountA,\n    tokenVaultA,\n    tokenOwnerAccountB,\n    tokenVaultB,\n    tickArray0,\n    tickArray1,\n    tickArray2,\n    oracle,\n  } = params;\n\n  const ix = program.instruction.swap(\n    amount,\n    otherAmountThreshold,\n    sqrtPriceLimit,\n    amountSpecifiedIsInput,\n    aToB,\n    {\n      accounts: {\n        tokenProgram: TOKEN_PROGRAM_ID,\n        tokenAuthority: tokenAuthority,\n        whirlpool,\n        tokenOwnerAccountA,\n        tokenVaultA,\n        tokenOwnerAccountB,\n        tokenVaultB,\n        tickArray0,\n        tickArray1,\n        tickArray2,\n        oracle,\n      },\n    }\n  );\n\n  return {\n    instructions: [ix],\n    cleanupInstructions: [],\n    signers: [],\n  };\n}\n","import {\n  AddressUtil,\n  deriveATA,\n  Instruction,\n  resolveOrCreateATAs,\n  TransactionBuilder,\n  ZERO,\n} from \"@orca-so/common-sdk\";\nimport { Address } from \"@project-serum/anchor\";\nimport { NATIVE_MINT } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport invariant from \"tiny-invariant\";\nimport { WhirlpoolContext } from \"../context\";\nimport {\n  collectFeesIx,\n  collectRewardIx,\n  DecreaseLiquidityInput,\n  decreaseLiquidityIx,\n  IncreaseLiquidityInput,\n  increaseLiquidityIx,\n  updateFeesAndRewardsIx,\n} from \"../instructions\";\nimport { PositionData, TickArrayData, TickData, WhirlpoolData } from \"../types/public\";\nimport { getTickArrayDataForPosition } from \"../utils/builder/position-builder-util\";\nimport { PDAUtil, PoolUtil, TickArrayUtil, TickUtil } from \"../utils/public\";\nimport { createWSOLAccountInstructions } from \"../utils/spl-token-utils\";\nimport {\n  getTokenMintsFromWhirlpools,\n  resolveAtaForMints,\n  TokenMintTypes,\n} from \"../utils/whirlpool-ata-utils\";\nimport { Position } from \"../whirlpool-client\";\n\nexport class PositionImpl implements Position {\n  private data: PositionData;\n  private whirlpoolData: WhirlpoolData;\n  private lowerTickArrayData: TickArrayData;\n  private upperTickArrayData: TickArrayData;\n  constructor(\n    readonly ctx: WhirlpoolContext,\n    readonly address: PublicKey,\n    data: PositionData,\n    whirlpoolData: WhirlpoolData,\n    lowerTickArrayData: TickArrayData,\n    upperTickArrayData: TickArrayData\n  ) {\n    this.data = data;\n    this.whirlpoolData = whirlpoolData;\n    this.lowerTickArrayData = lowerTickArrayData;\n    this.upperTickArrayData = upperTickArrayData;\n  }\n\n  getAddress(): PublicKey {\n    return this.address;\n  }\n\n  getData(): PositionData {\n    return this.data;\n  }\n\n  getWhirlpoolData(): WhirlpoolData {\n    return this.whirlpoolData;\n  }\n\n  getLowerTickData(): TickData {\n    return TickArrayUtil.getTickFromArray(\n      this.lowerTickArrayData,\n      this.data.tickLowerIndex,\n      this.whirlpoolData.tickSpacing\n    );\n  }\n\n  getUpperTickData(): TickData {\n    return TickArrayUtil.getTickFromArray(\n      this.upperTickArrayData,\n      this.data.tickUpperIndex,\n      this.whirlpoolData.tickSpacing\n    );\n  }\n\n  async refreshData() {\n    await this.refresh();\n    return this.data;\n  }\n\n  async increaseLiquidity(\n    liquidityInput: IncreaseLiquidityInput,\n    resolveATA = true,\n    sourceWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address\n  ) {\n    const sourceWalletKey = sourceWallet\n      ? AddressUtil.toPubKey(sourceWallet)\n      : this.ctx.wallet.publicKey;\n    const positionWalletKey = positionWallet\n      ? AddressUtil.toPubKey(positionWallet)\n      : this.ctx.wallet.publicKey;\n    const ataPayerKey = ataPayer ? AddressUtil.toPubKey(ataPayer) : this.ctx.wallet.publicKey;\n\n    const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, true);\n    if (!whirlpool) {\n      throw new Error(\"Unable to fetch whirlpool for this position.\");\n    }\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    let tokenOwnerAccountA: PublicKey;\n    let tokenOwnerAccountB: PublicKey;\n\n    if (resolveATA) {\n      const [ataA, ataB] = await resolveOrCreateATAs(\n        this.ctx.connection,\n        sourceWalletKey,\n        [\n          { tokenMint: whirlpool.tokenMintA, wrappedSolAmountIn: liquidityInput.tokenMaxA },\n          { tokenMint: whirlpool.tokenMintB, wrappedSolAmountIn: liquidityInput.tokenMaxB },\n        ],\n        () => this.ctx.fetcher.getAccountRentExempt(),\n        ataPayerKey\n      );\n      const { address: ataAddrA, ...tokenOwnerAccountAIx } = ataA!;\n      const { address: ataAddrB, ...tokenOwnerAccountBIx } = ataB!;\n      tokenOwnerAccountA = ataAddrA;\n      tokenOwnerAccountB = ataAddrB;\n      txBuilder.addInstruction(tokenOwnerAccountAIx);\n      txBuilder.addInstruction(tokenOwnerAccountBIx);\n    } else {\n      tokenOwnerAccountA = await deriveATA(sourceWalletKey, whirlpool.tokenMintA);\n      tokenOwnerAccountB = await deriveATA(sourceWalletKey, whirlpool.tokenMintB);\n    }\n    const positionTokenAccount = await deriveATA(positionWalletKey, this.data.positionMint);\n\n    const increaseIx = increaseLiquidityIx(this.ctx.program, {\n      ...liquidityInput,\n      whirlpool: this.data.whirlpool,\n      position: this.address,\n      positionTokenAccount,\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA: whirlpool.tokenVaultA,\n      tokenVaultB: whirlpool.tokenVaultB,\n      tickArrayLower: PDAUtil.getTickArray(\n        this.ctx.program.programId,\n        this.data.whirlpool,\n        TickUtil.getStartTickIndex(this.data.tickLowerIndex, whirlpool.tickSpacing)\n      ).publicKey,\n      tickArrayUpper: PDAUtil.getTickArray(\n        this.ctx.program.programId,\n        this.data.whirlpool,\n        TickUtil.getStartTickIndex(this.data.tickUpperIndex, whirlpool.tickSpacing)\n      ).publicKey,\n      positionAuthority: positionWalletKey,\n    });\n    txBuilder.addInstruction(increaseIx);\n    return txBuilder;\n  }\n\n  async decreaseLiquidity(\n    liquidityInput: DecreaseLiquidityInput,\n    resolveATA = true,\n    sourceWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address\n  ) {\n    const sourceWalletKey = sourceWallet\n      ? AddressUtil.toPubKey(sourceWallet)\n      : this.ctx.wallet.publicKey;\n    const positionWalletKey = positionWallet\n      ? AddressUtil.toPubKey(positionWallet)\n      : this.ctx.wallet.publicKey;\n    const ataPayerKey = ataPayer ? AddressUtil.toPubKey(ataPayer) : this.ctx.wallet.publicKey;\n    const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, true);\n\n    if (!whirlpool) {\n      throw new Error(\"Unable to fetch whirlpool for this position.\");\n    }\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n    let tokenOwnerAccountA: PublicKey;\n    let tokenOwnerAccountB: PublicKey;\n\n    if (resolveATA) {\n      const [ataA, ataB] = await resolveOrCreateATAs(\n        this.ctx.connection,\n        sourceWalletKey,\n        [{ tokenMint: whirlpool.tokenMintA }, { tokenMint: whirlpool.tokenMintB }],\n        () => this.ctx.fetcher.getAccountRentExempt(),\n        ataPayerKey\n      );\n      const { address: ataAddrA, ...tokenOwnerAccountAIx } = ataA!;\n      const { address: ataAddrB, ...tokenOwnerAccountBIx } = ataB!;\n      tokenOwnerAccountA = ataAddrA;\n      tokenOwnerAccountB = ataAddrB;\n      txBuilder.addInstruction(tokenOwnerAccountAIx);\n      txBuilder.addInstruction(tokenOwnerAccountBIx);\n    } else {\n      tokenOwnerAccountA = await deriveATA(sourceWalletKey, whirlpool.tokenMintA);\n      tokenOwnerAccountB = await deriveATA(sourceWalletKey, whirlpool.tokenMintB);\n    }\n\n    const decreaseIx = decreaseLiquidityIx(this.ctx.program, {\n      ...liquidityInput,\n      whirlpool: this.data.whirlpool,\n      position: this.address,\n      positionTokenAccount: await deriveATA(positionWalletKey, this.data.positionMint),\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA: whirlpool.tokenVaultA,\n      tokenVaultB: whirlpool.tokenVaultB,\n      tickArrayLower: PDAUtil.getTickArray(\n        this.ctx.program.programId,\n        this.data.whirlpool,\n        TickUtil.getStartTickIndex(this.data.tickLowerIndex, whirlpool.tickSpacing)\n      ).publicKey,\n      tickArrayUpper: PDAUtil.getTickArray(\n        this.ctx.program.programId,\n        this.data.whirlpool,\n        TickUtil.getStartTickIndex(this.data.tickUpperIndex, whirlpool.tickSpacing)\n      ).publicKey,\n      positionAuthority: positionWalletKey,\n    });\n    txBuilder.addInstruction(decreaseIx);\n    return txBuilder;\n  }\n\n  async collectFees(\n    updateFeesAndRewards: boolean = true,\n    ownerTokenAccountMap?: Partial<Record<string, Address>>,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address,\n    refresh = false\n  ): Promise<TransactionBuilder> {\n    const [destinationWalletKey, positionWalletKey, ataPayerKey] = AddressUtil.toPubKeys([\n      destinationWallet ?? this.ctx.wallet.publicKey,\n      positionWallet ?? this.ctx.wallet.publicKey,\n      ataPayer ?? this.ctx.wallet.publicKey,\n    ]);\n\n    const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, refresh);\n    if (!whirlpool) {\n      throw new Error(\n        `Unable to fetch whirlpool (${this.data.whirlpool}) for this position (${this.address}).`\n      );\n    }\n\n    let txBuilder = new TransactionBuilder(this.ctx.provider.connection, this.ctx.provider.wallet);\n\n    const accountExemption = await this.ctx.fetcher.getAccountRentExempt();\n\n    let ataMap = { ...ownerTokenAccountMap };\n\n    if (!ownerTokenAccountMap) {\n      const affliatedMints = getTokenMintsFromWhirlpools([whirlpool], TokenMintTypes.POOL_ONLY);\n      const { ataTokenAddresses: affliatedTokenAtaMap, resolveAtaIxs } = await resolveAtaForMints(\n        this.ctx,\n        {\n          mints: affliatedMints.mintMap,\n          accountExemption,\n          receiver: destinationWalletKey,\n          payer: ataPayerKey,\n        }\n      );\n\n      txBuilder.addInstructions(resolveAtaIxs);\n\n      if (affliatedMints.hasNativeMint) {\n        let { address: wSOLAta, ...resolveWSolIx } = createWSOLAccountInstructions(\n          destinationWalletKey,\n          ZERO,\n          accountExemption,\n          ataPayerKey,\n          destinationWalletKey\n        );\n        affliatedTokenAtaMap[NATIVE_MINT.toBase58()] = wSOLAta;\n        txBuilder.addInstruction(resolveWSolIx);\n      }\n\n      ataMap = { ...affliatedTokenAtaMap };\n    }\n\n    const tokenOwnerAccountA = ataMap[whirlpool.tokenMintA.toBase58()];\n    invariant(\n      !!tokenOwnerAccountA,\n      `No owner token account provided for wallet ${destinationWalletKey.toBase58()} for token A ${whirlpool.tokenMintA.toBase58()} `\n    );\n    const tokenOwnerAccountB = ataMap[whirlpool.tokenMintB.toBase58()];\n    invariant(\n      !!tokenOwnerAccountB,\n      `No owner token account provided for wallet ${destinationWalletKey.toBase58()} for token B ${whirlpool.tokenMintB.toBase58()} `\n    );\n\n    const positionTokenAccount = await deriveATA(positionWalletKey, this.data.positionMint);\n\n    if (updateFeesAndRewards) {\n      const updateIx = await this.updateFeesAndRewards();\n      txBuilder.addInstruction(updateIx);\n    }\n\n    const ix = collectFeesIx(this.ctx.program, {\n      whirlpool: this.data.whirlpool,\n      position: this.address,\n      positionTokenAccount,\n      tokenOwnerAccountA: AddressUtil.toPubKey(tokenOwnerAccountA),\n      tokenOwnerAccountB: AddressUtil.toPubKey(tokenOwnerAccountB),\n      tokenVaultA: whirlpool.tokenVaultA,\n      tokenVaultB: whirlpool.tokenVaultB,\n      positionAuthority: positionWalletKey,\n    });\n\n    txBuilder.addInstruction(ix);\n\n    return txBuilder;\n  }\n\n  async collectRewards(\n    rewardsToCollect?: Address[],\n    updateFeesAndRewards: boolean = true,\n    ownerTokenAccountMap?: Partial<Record<string, Address>>,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address,\n    refresh = true\n  ): Promise<TransactionBuilder> {\n    const [destinationWalletKey, positionWalletKey, ataPayerKey] = AddressUtil.toPubKeys([\n      destinationWallet ?? this.ctx.wallet.publicKey,\n      positionWallet ?? this.ctx.wallet.publicKey,\n      ataPayer ?? this.ctx.wallet.publicKey,\n    ]);\n\n    const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool, refresh);\n    if (!whirlpool) {\n      throw new Error(\n        `Unable to fetch whirlpool(${this.data.whirlpool}) for this position(${this.address}).`\n      );\n    }\n\n    const initializedRewards = whirlpool.rewardInfos.filter((info) =>\n      PoolUtil.isRewardInitialized(info)\n    );\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    const accountExemption = await this.ctx.fetcher.getAccountRentExempt();\n\n    let ataMap = { ...ownerTokenAccountMap };\n    if (!ownerTokenAccountMap) {\n      const rewardMints = getTokenMintsFromWhirlpools([whirlpool], TokenMintTypes.REWARD_ONLY);\n      const { ataTokenAddresses: affliatedTokenAtaMap, resolveAtaIxs } = await resolveAtaForMints(\n        this.ctx,\n        {\n          mints: rewardMints.mintMap,\n          accountExemption,\n          receiver: destinationWalletKey,\n          payer: ataPayerKey,\n        }\n      );\n\n      if (rewardMints.hasNativeMint) {\n        let { address: wSOLAta, ...resolveWSolIx } = createWSOLAccountInstructions(\n          destinationWalletKey,\n          ZERO,\n          accountExemption\n        );\n        affliatedTokenAtaMap[NATIVE_MINT.toBase58()] = wSOLAta;\n        txBuilder.addInstruction(resolveWSolIx);\n      }\n\n      txBuilder.addInstructions(resolveAtaIxs);\n\n      ataMap = { ...affliatedTokenAtaMap };\n    }\n\n    const positionTokenAccount = await deriveATA(positionWalletKey, this.data.positionMint);\n    if (updateFeesAndRewards) {\n      const updateIx = await this.updateFeesAndRewards();\n      txBuilder.addInstruction(updateIx);\n    }\n\n    initializedRewards.forEach((info, index) => {\n      if (\n        rewardsToCollect &&\n        !rewardsToCollect.some((r) => r.toString() === info.mint.toBase58())\n      ) {\n        // If rewardsToCollect is specified and this reward is not in it,\n        // don't include collectIX for that in TX\n        return;\n      }\n\n      const rewardOwnerAccount = ataMap[info.mint.toBase58()];\n      invariant(\n        !!rewardOwnerAccount,\n        `No owner token account provided for wallet ${destinationWalletKey.toBase58()} for reward ${index} token ${info.mint.toBase58()} `\n      );\n\n      const ix = collectRewardIx(this.ctx.program, {\n        whirlpool: this.data.whirlpool,\n        position: this.address,\n        positionTokenAccount,\n        rewardIndex: index,\n        rewardOwnerAccount: AddressUtil.toPubKey(rewardOwnerAccount),\n        rewardVault: info.vault,\n        positionAuthority: positionWalletKey,\n      });\n\n      txBuilder.addInstruction(ix);\n    });\n\n    return txBuilder;\n  }\n\n  private async refresh() {\n    const positionAccount = await this.ctx.fetcher.getPosition(this.address, true);\n    if (!!positionAccount) {\n      this.data = positionAccount;\n    }\n    const whirlpoolAccount = await this.ctx.fetcher.getPool(this.data.whirlpool, true);\n    if (!!whirlpoolAccount) {\n      this.whirlpoolData = whirlpoolAccount;\n    }\n\n    const [lowerTickArray, upperTickArray] = await getTickArrayDataForPosition(\n      this.ctx,\n      this.data,\n      this.whirlpoolData,\n      true\n    );\n    if (lowerTickArray) {\n      this.lowerTickArrayData = lowerTickArray;\n    }\n    if (upperTickArray) {\n      this.upperTickArrayData = upperTickArray;\n    }\n  }\n\n  private async updateFeesAndRewards(): Promise<Instruction> {\n    const whirlpool = await this.ctx.fetcher.getPool(this.data.whirlpool);\n    if (!whirlpool) {\n      throw new Error(\n        `Unable to fetch whirlpool(${this.data.whirlpool}) for this position(${this.address}).`\n      );\n    }\n\n    const [tickArrayLowerPda, tickArrayUpperPda] = [\n      this.data.tickLowerIndex,\n      this.data.tickUpperIndex,\n    ].map((tickIndex) =>\n      PDAUtil.getTickArrayFromTickIndex(\n        tickIndex,\n        whirlpool.tickSpacing,\n        this.data.whirlpool,\n        this.ctx.program.programId\n      )\n    );\n\n    const updateIx = updateFeesAndRewardsIx(this.ctx.program, {\n      whirlpool: this.data.whirlpool,\n      position: this.address,\n      tickArrayLower: tickArrayLowerPda.publicKey,\n      tickArrayUpper: tickArrayUpperPda.publicKey,\n    });\n\n    return updateIx;\n  }\n}\n","import { WhirlpoolContext } from \"../..\";\nimport { PositionData, WhirlpoolData } from \"../../types/public\";\nimport { PDAUtil } from \"../public\";\n\nexport async function getTickArrayDataForPosition(\n  ctx: WhirlpoolContext,\n  position: PositionData,\n  whirlpool: WhirlpoolData,\n  refresh: boolean\n) {\n  const lowerTickArrayKey = PDAUtil.getTickArrayFromTickIndex(\n    position.tickLowerIndex,\n    whirlpool.tickSpacing,\n    position.whirlpool,\n    ctx.program.programId\n  ).publicKey;\n  const upperTickArrayKey = PDAUtil.getTickArrayFromTickIndex(\n    position.tickUpperIndex,\n    whirlpool.tickSpacing,\n    position.whirlpool,\n    ctx.program.programId\n  ).publicKey;\n\n  return await ctx.fetcher.listTickArrays([lowerTickArrayKey, upperTickArrayKey], refresh);\n}\n","import { AddressUtil, DecimalUtil, Percentage, ZERO } from \"@orca-so/common-sdk\";\nimport { Address, BN } from \"@project-serum/anchor\";\nimport { u64 } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport Decimal from \"decimal.js\";\nimport invariant from \"tiny-invariant\";\nimport { IncreaseLiquidityInput } from \"../../instructions\";\nimport {\n  PositionUtil,\n  PositionStatus,\n  getLiquidityFromTokenA,\n  adjustForSlippage,\n  getTokenAFromLiquidity,\n  getTokenBFromLiquidity,\n  getLiquidityFromTokenB,\n} from \"../../utils/position-util\";\nimport { PriceMath, TickUtil } from \"../../utils/public\";\nimport { Whirlpool } from \"../../whirlpool-client\";\n\n/**\n * @category Quotes\n * @param inputTokenAmount - The amount of input tokens to deposit.\n * @param inputTokenMint - The mint of the input token the user would like to deposit.\n * @param tokenMintA - The mint of tokenA in the Whirlpool the user is depositing into.\n * @param tokenMintB -The mint of tokenB in the Whirlpool the user is depositing into.\n * @param tickCurrentIndex - The Whirlpool's current tickIndex\n * @param sqrtPrice - The Whirlpool's current sqrtPrice\n * @param tickLowerIndex - The lower index of the position that we are withdrawing from.\n * @param tickUpperIndex - The upper index of the position that we are withdrawing from.\n * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received.\n */\nexport type IncreaseLiquidityQuoteParam = {\n  inputTokenAmount: u64;\n  inputTokenMint: PublicKey;\n  tokenMintA: PublicKey;\n  tokenMintB: PublicKey;\n  tickCurrentIndex: number;\n  sqrtPrice: BN;\n  tickLowerIndex: number;\n  tickUpperIndex: number;\n  slippageTolerance: Percentage;\n};\n\n/**\n * Return object from increase liquidity quote functions.\n * @category Quotes\n */\nexport type IncreaseLiquidityQuote = IncreaseLiquidityInput & { tokenEstA: u64; tokenEstB: u64 };\n\n/**\n * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount.\n *\n * @category Quotes\n * @param inputTokenAmount - The amount of input tokens to deposit.\n * @param inputTokenMint - The mint of the input token the user would like to deposit.\n * @param tickLower - The lower index of the position that we are withdrawing from.\n * @param tickUpper - The upper index of the position that we are withdrawing from.\n * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received.\n * @param whirlpool - A Whirlpool helper class to help interact with the Whirlpool account.\n * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix.\n */\nexport function increaseLiquidityQuoteByInputToken(\n  inputTokenMint: Address,\n  inputTokenAmount: Decimal,\n  tickLower: number,\n  tickUpper: number,\n  slippageTolerance: Percentage,\n  whirlpool: Whirlpool\n) {\n  const data = whirlpool.getData();\n  const tokenAInfo = whirlpool.getTokenAInfo();\n  const tokenBInfo = whirlpool.getTokenBInfo();\n\n  const inputMint = AddressUtil.toPubKey(inputTokenMint);\n  const inputTokenInfo = inputMint.equals(tokenAInfo.mint) ? tokenAInfo : tokenBInfo;\n\n  return increaseLiquidityQuoteByInputTokenWithParams({\n    inputTokenMint: inputMint,\n    inputTokenAmount: DecimalUtil.toU64(inputTokenAmount, inputTokenInfo.decimals),\n    tickLowerIndex: TickUtil.getInitializableTickIndex(tickLower, data.tickSpacing),\n    tickUpperIndex: TickUtil.getInitializableTickIndex(tickUpper, data.tickSpacing),\n    slippageTolerance,\n    ...data,\n  });\n}\n\n/**\n * Get an estimated quote on the maximum tokens required to deposit based on a specified input token amount.\n *\n * @category Quotes\n * @param param IncreaseLiquidityQuoteParam\n * @returns An IncreaseLiquidityInput object detailing the required token amounts & liquidity values to use when calling increase-liquidity-ix.\n */\nexport function increaseLiquidityQuoteByInputTokenWithParams(\n  param: IncreaseLiquidityQuoteParam\n): IncreaseLiquidityQuote {\n  invariant(TickUtil.checkTickInBounds(param.tickLowerIndex), \"tickLowerIndex is out of bounds.\");\n  invariant(TickUtil.checkTickInBounds(param.tickUpperIndex), \"tickUpperIndex is out of bounds.\");\n  invariant(\n    param.inputTokenMint.equals(param.tokenMintA) || param.inputTokenMint.equals(param.tokenMintB),\n    `input token mint ${param.inputTokenMint.toBase58()} does not match any tokens in the provided pool.`\n  );\n\n  const positionStatus = PositionUtil.getPositionStatus(\n    param.tickCurrentIndex,\n    param.tickLowerIndex,\n    param.tickUpperIndex\n  );\n\n  switch (positionStatus) {\n    case PositionStatus.BelowRange:\n      return quotePositionBelowRange(param);\n    case PositionStatus.InRange:\n      return quotePositionInRange(param);\n    case PositionStatus.AboveRange:\n      return quotePositionAboveRange(param);\n    default:\n      throw new Error(`type ${positionStatus} is an unknown PositionStatus`);\n  }\n}\n\n/*** Private ***/\n\nfunction quotePositionBelowRange(param: IncreaseLiquidityQuoteParam): IncreaseLiquidityQuote {\n  const {\n    tokenMintA,\n    inputTokenMint,\n    inputTokenAmount,\n    tickLowerIndex,\n    tickUpperIndex,\n    slippageTolerance,\n  } = param;\n\n  if (!tokenMintA.equals(inputTokenMint)) {\n    return {\n      tokenMaxA: ZERO,\n      tokenMaxB: ZERO,\n      tokenEstA: ZERO,\n      tokenEstB: ZERO,\n      liquidityAmount: ZERO,\n    };\n  }\n\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n\n  const liquidityAmount = getLiquidityFromTokenA(\n    inputTokenAmount,\n    sqrtPriceLowerX64,\n    sqrtPriceUpperX64,\n    false\n  );\n\n  const tokenEstA = getTokenAFromLiquidity(\n    liquidityAmount,\n    sqrtPriceLowerX64,\n    sqrtPriceUpperX64,\n    true\n  );\n  const tokenMaxA = adjustForSlippage(tokenEstA, slippageTolerance, true);\n\n  return {\n    tokenMaxA,\n    tokenMaxB: ZERO,\n    tokenEstA,\n    tokenEstB: ZERO,\n    liquidityAmount,\n  };\n}\n\nfunction quotePositionInRange(param: IncreaseLiquidityQuoteParam): IncreaseLiquidityQuote {\n  const {\n    tokenMintA,\n    sqrtPrice,\n    inputTokenMint,\n    inputTokenAmount,\n    tickLowerIndex,\n    tickUpperIndex,\n    slippageTolerance,\n  } = param;\n\n  const sqrtPriceX64 = sqrtPrice;\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n\n  let [tokenEstA, tokenEstB] = tokenMintA.equals(inputTokenMint)\n    ? [inputTokenAmount, undefined]\n    : [undefined, inputTokenAmount];\n\n  let liquidityAmount: BN;\n\n  if (tokenEstA) {\n    liquidityAmount = getLiquidityFromTokenA(tokenEstA, sqrtPriceX64, sqrtPriceUpperX64, false);\n    tokenEstA = getTokenAFromLiquidity(liquidityAmount, sqrtPriceX64, sqrtPriceUpperX64, true);\n    tokenEstB = getTokenBFromLiquidity(liquidityAmount, sqrtPriceLowerX64, sqrtPriceX64, true);\n  } else if (tokenEstB) {\n    liquidityAmount = getLiquidityFromTokenB(tokenEstB, sqrtPriceLowerX64, sqrtPriceX64, false);\n    tokenEstA = getTokenAFromLiquidity(liquidityAmount, sqrtPriceX64, sqrtPriceUpperX64, true);\n    tokenEstB = getTokenBFromLiquidity(liquidityAmount, sqrtPriceLowerX64, sqrtPriceX64, true);\n  } else {\n    throw new Error(\"invariant violation\");\n  }\n\n  const tokenMaxA = adjustForSlippage(tokenEstA, slippageTolerance, true);\n  const tokenMaxB = adjustForSlippage(tokenEstB, slippageTolerance, true);\n\n  return {\n    tokenMaxA,\n    tokenMaxB,\n    tokenEstA: tokenEstA!,\n    tokenEstB: tokenEstB!,\n    liquidityAmount,\n  };\n}\n\nfunction quotePositionAboveRange(param: IncreaseLiquidityQuoteParam): IncreaseLiquidityQuote {\n  const {\n    tokenMintB,\n    inputTokenMint,\n    inputTokenAmount,\n    tickLowerIndex,\n    tickUpperIndex,\n    slippageTolerance,\n  } = param;\n\n  if (!tokenMintB.equals(inputTokenMint)) {\n    return {\n      tokenMaxA: ZERO,\n      tokenMaxB: ZERO,\n      tokenEstA: ZERO,\n      tokenEstB: ZERO,\n      liquidityAmount: ZERO,\n    };\n  }\n\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n  const liquidityAmount = getLiquidityFromTokenB(\n    inputTokenAmount,\n    sqrtPriceLowerX64,\n    sqrtPriceUpperX64,\n    false\n  );\n\n  const tokenEstB = getTokenBFromLiquidity(\n    liquidityAmount,\n    sqrtPriceLowerX64,\n    sqrtPriceUpperX64,\n    true\n  );\n  const tokenMaxB = adjustForSlippage(tokenEstB, slippageTolerance, true);\n\n  return {\n    tokenMaxA: ZERO,\n    tokenMaxB,\n    tokenEstA: ZERO,\n    tokenEstB,\n    liquidityAmount,\n  };\n}\n","import { MathUtil, Percentage } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport {\n  getLowerSqrtPriceFromTokenA,\n  getUpperSqrtPriceFromTokenA,\n  getUpperSqrtPriceFromTokenB,\n  getLowerSqrtPriceFromTokenB,\n} from \"./swap-utils\";\n\nexport enum SwapDirection {\n  AtoB = \"Swap A to B\",\n  BtoA = \"Swap B to A\",\n}\n\nexport enum AmountSpecified {\n  Input = \"Specified input amount\",\n  Output = \"Specified output amount\",\n}\n\nexport enum PositionStatus {\n  BelowRange,\n  InRange,\n  AboveRange,\n}\n\nexport class PositionUtil {\n  private constructor() {}\n\n  public static getPositionStatus(\n    tickCurrentIndex: number,\n    tickLowerIndex: number,\n    tickUpperIndex: number\n  ): PositionStatus {\n    if (tickCurrentIndex < tickLowerIndex) {\n      return PositionStatus.BelowRange;\n    } else if (tickCurrentIndex < tickUpperIndex) {\n      return PositionStatus.InRange;\n    } else {\n      return PositionStatus.AboveRange;\n    }\n  }\n}\n\nexport function adjustForSlippage(\n  n: BN,\n  { numerator, denominator }: Percentage,\n  adjustUp: boolean\n): BN {\n  if (adjustUp) {\n    return n.mul(denominator.add(numerator)).div(denominator);\n  } else {\n    return n.mul(denominator).div(denominator.add(numerator));\n  }\n}\n\nexport function adjustAmountForSlippage(\n  amountIn: BN,\n  amountOut: BN,\n  { numerator, denominator }: Percentage,\n  amountSpecified: AmountSpecified\n): BN {\n  if (amountSpecified === AmountSpecified.Input) {\n    return amountOut.mul(denominator).div(denominator.add(numerator));\n  } else {\n    return amountIn.mul(denominator.add(numerator)).div(denominator);\n  }\n}\n\nexport function getLiquidityFromTokenA(\n  amount: BN,\n  sqrtPriceLowerX64: BN,\n  sqrtPriceUpperX64: BN,\n  roundUp: boolean\n) {\n  const result = amount\n    .mul(sqrtPriceLowerX64)\n    .mul(sqrtPriceUpperX64)\n    .div(sqrtPriceUpperX64.sub(sqrtPriceLowerX64));\n  if (roundUp) {\n    return MathUtil.shiftRightRoundUp(result);\n  } else {\n    return result.shrn(64);\n  }\n}\n\nexport function getLiquidityFromTokenB(\n  amount: BN,\n  sqrtPriceLowerX64: BN,\n  sqrtPriceUpperX64: BN,\n  roundUp: boolean\n) {\n  const numerator = amount.shln(64);\n  const denominator = sqrtPriceUpperX64.sub(sqrtPriceLowerX64);\n  if (roundUp) {\n    return MathUtil.divRoundUp(numerator, denominator);\n  } else {\n    return numerator.div(denominator);\n  }\n}\n\nexport function getAmountFixedDelta(\n  currentSqrtPriceX64: BN,\n  targetSqrtPriceX64: BN,\n  liquidity: BN,\n  amountSpecified: AmountSpecified,\n  swapDirection: SwapDirection\n) {\n  if ((amountSpecified == AmountSpecified.Input) == (swapDirection == SwapDirection.AtoB)) {\n    return getTokenAFromLiquidity(\n      liquidity,\n      currentSqrtPriceX64,\n      targetSqrtPriceX64,\n      amountSpecified == AmountSpecified.Input\n    );\n  } else {\n    return getTokenBFromLiquidity(\n      liquidity,\n      currentSqrtPriceX64,\n      targetSqrtPriceX64,\n      amountSpecified == AmountSpecified.Input\n    );\n  }\n}\n\nexport function getAmountUnfixedDelta(\n  currentSqrtPriceX64: BN,\n  targetSqrtPriceX64: BN,\n  liquidity: BN,\n  amountSpecified: AmountSpecified,\n  swapDirection: SwapDirection\n) {\n  if ((amountSpecified == AmountSpecified.Input) == (swapDirection == SwapDirection.AtoB)) {\n    return getTokenBFromLiquidity(\n      liquidity,\n      currentSqrtPriceX64,\n      targetSqrtPriceX64,\n      amountSpecified == AmountSpecified.Output\n    );\n  } else {\n    return getTokenAFromLiquidity(\n      liquidity,\n      currentSqrtPriceX64,\n      targetSqrtPriceX64,\n      amountSpecified == AmountSpecified.Output\n    );\n  }\n}\n\nexport function getNextSqrtPrice(\n  sqrtPriceX64: BN,\n  liquidity: BN,\n  amount: BN,\n  amountSpecified: AmountSpecified,\n  swapDirection: SwapDirection\n) {\n  if (amountSpecified === AmountSpecified.Input && swapDirection === SwapDirection.AtoB) {\n    return getLowerSqrtPriceFromTokenA(amount, liquidity, sqrtPriceX64);\n  } else if (amountSpecified === AmountSpecified.Output && swapDirection === SwapDirection.BtoA) {\n    return getUpperSqrtPriceFromTokenA(amount, liquidity, sqrtPriceX64);\n  } else if (amountSpecified === AmountSpecified.Input && swapDirection === SwapDirection.BtoA) {\n    return getUpperSqrtPriceFromTokenB(amount, liquidity, sqrtPriceX64);\n  } else {\n    return getLowerSqrtPriceFromTokenB(amount, liquidity, sqrtPriceX64);\n  }\n}\n\nexport function getTokenAFromLiquidity(\n  liquidity: BN,\n  sqrtPrice0X64: BN,\n  sqrtPrice1X64: BN,\n  roundUp: boolean\n) {\n  const [sqrtPriceLowerX64, sqrtPriceUpperX64] = orderSqrtPrice(sqrtPrice0X64, sqrtPrice1X64);\n\n  const numerator = liquidity.mul(sqrtPriceUpperX64.sub(sqrtPriceLowerX64)).shln(64);\n  const denominator = sqrtPriceUpperX64.mul(sqrtPriceLowerX64);\n  if (roundUp) {\n    return MathUtil.divRoundUp(numerator, denominator);\n  } else {\n    return numerator.div(denominator);\n  }\n}\n\nexport function getTokenBFromLiquidity(\n  liquidity: BN,\n  sqrtPrice0X64: BN,\n  sqrtPrice1X64: BN,\n  roundUp: boolean\n) {\n  const [sqrtPriceLowerX64, sqrtPriceUpperX64] = orderSqrtPrice(sqrtPrice0X64, sqrtPrice1X64);\n\n  const result = liquidity.mul(sqrtPriceUpperX64.sub(sqrtPriceLowerX64));\n  if (roundUp) {\n    return MathUtil.shiftRightRoundUp(result);\n  } else {\n    return result.shrn(64);\n  }\n}\n\n/** Private */\n\nfunction orderSqrtPrice(sqrtPrice0X64: BN, sqrtPrice1X64: BN): [BN, BN] {\n  if (sqrtPrice0X64.lt(sqrtPrice1X64)) {\n    return [sqrtPrice0X64, sqrtPrice1X64];\n  } else {\n    return [sqrtPrice1X64, sqrtPrice0X64];\n  }\n}\n","import { MathUtil } from \"@orca-so/common-sdk\";\nimport BN from \"bn.js\";\n\nexport function getLowerSqrtPriceFromTokenA(amount: BN, liquidity: BN, sqrtPriceX64: BN): BN {\n  const numerator = liquidity.mul(sqrtPriceX64).shln(64);\n  const denominator = liquidity.shln(64).add(amount.mul(sqrtPriceX64));\n\n  // always round up\n  return MathUtil.divRoundUp(numerator, denominator);\n}\n\nexport function getUpperSqrtPriceFromTokenA(amount: BN, liquidity: BN, sqrtPriceX64: BN): BN {\n  const numerator = liquidity.mul(sqrtPriceX64).shln(64);\n  const denominator = liquidity.shln(64).sub(amount.mul(sqrtPriceX64));\n\n  // always round up\n  return MathUtil.divRoundUp(numerator, denominator);\n}\n\nexport function getLowerSqrtPriceFromTokenB(amount: BN, liquidity: BN, sqrtPriceX64: BN): BN {\n  // always round down\n  return sqrtPriceX64.sub(MathUtil.divRoundUp(amount.shln(64), liquidity));\n}\n\nexport function getUpperSqrtPriceFromTokenB(amount: BN, liquidity: BN, sqrtPriceX64: BN): BN {\n  // always round down (rounding up a negative number)\n  return sqrtPriceX64.add(amount.shln(64).div(liquidity));\n}\n","import { Percentage, ZERO } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport invariant from \"tiny-invariant\";\nimport { DecreaseLiquidityInput } from \"../../instructions\";\nimport {\n  adjustForSlippage,\n  getTokenAFromLiquidity,\n  getTokenBFromLiquidity,\n  PositionStatus,\n  PositionUtil,\n} from \"../../utils/position-util\";\nimport { PriceMath, TickUtil } from \"../../utils/public\";\nimport { Position, Whirlpool } from \"../../whirlpool-client\";\n\n/**\n * @category Quotes\n * @param liquidity - The desired liquidity to withdraw from the Whirlpool\n * @param tickCurrentIndex - The Whirlpool's current tickIndex\n * @param sqrtPrice - The Whirlpool's current sqrtPrice\n * @param tickLowerIndex - The lower index of the position that we are withdrawing from.\n * @param tickUpperIndex - The upper index of the position that we are withdrawing from.\n * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received.\n */\nexport type DecreaseLiquidityQuoteParam = {\n  liquidity: BN;\n  tickCurrentIndex: number;\n  sqrtPrice: BN;\n  tickLowerIndex: number;\n  tickUpperIndex: number;\n  slippageTolerance: Percentage;\n};\n\n/**\n * Return object from decrease liquidity quote functions.\n * @category Quotes\n */\nexport type DecreaseLiquidityQuote = DecreaseLiquidityInput & { tokenEstA: BN; tokenEstB: BN };\n\n/**\n * Get an estimated quote on the minimum tokens receivable based on the desired withdraw liquidity value.\n *\n * @category Quotes\n * @param liquidity - The desired liquidity to withdraw from the Whirlpool\n * @param slippageTolerance - The maximum slippage allowed when calculating the minimum tokens received.\n * @param position - A Position helper class to help interact with the Position account.\n * @param whirlpool - A Whirlpool helper class to help interact with the Whirlpool account.\n * @returns An DecreaseLiquidityQuote object detailing the tokenMin & liquidity values to use when calling decrease-liquidity-ix.\n */\nexport function decreaseLiquidityQuoteByLiquidity(\n  liquidity: BN,\n  slippageTolerance: Percentage,\n  position: Position,\n  whirlpool: Whirlpool\n) {\n  const positionData = position.getData();\n  const whirlpoolData = whirlpool.getData();\n\n  invariant(\n    liquidity.lte(positionData.liquidity),\n    \"Quote liquidity is more than the position liquidity.\"\n  );\n\n  return decreaseLiquidityQuoteByLiquidityWithParams({\n    liquidity,\n    slippageTolerance,\n    tickLowerIndex: positionData.tickLowerIndex,\n    tickUpperIndex: positionData.tickUpperIndex,\n    sqrtPrice: whirlpoolData.sqrtPrice,\n    tickCurrentIndex: whirlpoolData.tickCurrentIndex,\n  });\n}\n\n/**\n * Get an estimated quote on the minimum tokens receivable based on the desired withdraw liquidity value.\n *\n * @category Quotes\n * @param param DecreaseLiquidityQuoteParam\n * @returns An DecreaseLiquidityInput object detailing the tokenMin & liquidity values to use when calling decrease-liquidity-ix.\n */\nexport function decreaseLiquidityQuoteByLiquidityWithParams(\n  param: DecreaseLiquidityQuoteParam\n): DecreaseLiquidityQuote {\n  invariant(TickUtil.checkTickInBounds(param.tickLowerIndex), \"tickLowerIndex is out of bounds.\");\n  invariant(TickUtil.checkTickInBounds(param.tickUpperIndex), \"tickUpperIndex is out of bounds.\");\n  invariant(\n    TickUtil.checkTickInBounds(param.tickCurrentIndex),\n    \"tickCurrentIndex is out of bounds.\"\n  );\n\n  const positionStatus = PositionUtil.getPositionStatus(\n    param.tickCurrentIndex,\n    param.tickLowerIndex,\n    param.tickUpperIndex\n  );\n\n  switch (positionStatus) {\n    case PositionStatus.BelowRange:\n      return quotePositionBelowRange(param);\n    case PositionStatus.InRange:\n      return quotePositionInRange(param);\n    case PositionStatus.AboveRange:\n      return quotePositionAboveRange(param);\n    default:\n      throw new Error(`type ${positionStatus} is an unknown PositionStatus`);\n  }\n}\n\nfunction quotePositionBelowRange(param: DecreaseLiquidityQuoteParam): DecreaseLiquidityQuote {\n  const { tickLowerIndex, tickUpperIndex, liquidity, slippageTolerance } = param;\n\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n\n  const tokenEstA = getTokenAFromLiquidity(liquidity, sqrtPriceLowerX64, sqrtPriceUpperX64, false);\n  const tokenMinA = adjustForSlippage(tokenEstA, slippageTolerance, false);\n\n  return {\n    tokenMinA,\n    tokenMinB: ZERO,\n    tokenEstA,\n    tokenEstB: ZERO,\n    liquidityAmount: liquidity,\n  };\n}\n\nfunction quotePositionInRange(param: DecreaseLiquidityQuoteParam): DecreaseLiquidityQuote {\n  const { sqrtPrice, tickLowerIndex, tickUpperIndex, liquidity, slippageTolerance } = param;\n\n  const sqrtPriceX64 = sqrtPrice;\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n\n  const tokenEstA = getTokenAFromLiquidity(liquidity, sqrtPriceX64, sqrtPriceUpperX64, false);\n  const tokenMinA = adjustForSlippage(tokenEstA, slippageTolerance, false);\n  const tokenEstB = getTokenBFromLiquidity(liquidity, sqrtPriceLowerX64, sqrtPriceX64, false);\n  const tokenMinB = adjustForSlippage(tokenEstB, slippageTolerance, false);\n\n  return {\n    tokenMinA,\n    tokenMinB,\n    tokenEstA,\n    tokenEstB,\n    liquidityAmount: liquidity,\n  };\n}\n\nfunction quotePositionAboveRange(param: DecreaseLiquidityQuoteParam): DecreaseLiquidityQuote {\n  const { tickLowerIndex, tickUpperIndex, liquidity, slippageTolerance: slippageTolerance } = param;\n\n  const sqrtPriceLowerX64 = PriceMath.tickIndexToSqrtPriceX64(tickLowerIndex);\n  const sqrtPriceUpperX64 = PriceMath.tickIndexToSqrtPriceX64(tickUpperIndex);\n\n  const tokenEstB = getTokenBFromLiquidity(liquidity, sqrtPriceLowerX64, sqrtPriceUpperX64, false);\n  const tokenMinB = adjustForSlippage(tokenEstB, slippageTolerance, false);\n\n  return {\n    tokenMinA: ZERO,\n    tokenMinB,\n    tokenEstA: ZERO,\n    tokenEstB,\n    liquidityAmount: liquidity,\n  };\n}\n","import { MathUtil } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport { PositionData, TickData, WhirlpoolData } from \"../../types/public\";\n\n/**\n * @category Quotes\n */\nexport type CollectFeesQuoteParam = {\n  whirlpool: WhirlpoolData;\n  position: PositionData;\n  tickLower: TickData;\n  tickUpper: TickData;\n};\n\n/**\n * @category Quotes\n */\nexport type CollectFeesQuote = {\n  feeOwedA: BN;\n  feeOwedB: BN;\n};\n\n/**\n * Get a quote on the outstanding fees owed to a position.\n *\n * @category Quotes\n * @param param A collection of fetched Whirlpool accounts to faciliate the quote.\n * @returns A quote object containing the fees owed for each token in the pool.\n */\nexport function collectFeesQuote(param: CollectFeesQuoteParam): CollectFeesQuote {\n  const { whirlpool, position, tickLower, tickUpper } = param;\n\n  const {\n    tickCurrentIndex,\n    feeGrowthGlobalA: feeGrowthGlobalAX64,\n    feeGrowthGlobalB: feeGrowthGlobalBX64,\n  } = whirlpool;\n  const {\n    tickLowerIndex,\n    tickUpperIndex,\n    liquidity,\n    feeOwedA,\n    feeOwedB,\n    feeGrowthCheckpointA: feeGrowthCheckpointAX64,\n    feeGrowthCheckpointB: feeGrowthCheckpointBX64,\n  } = position;\n  const {\n    feeGrowthOutsideA: tickLowerFeeGrowthOutsideAX64,\n    feeGrowthOutsideB: tickLowerFeeGrowthOutsideBX64,\n  } = tickLower;\n  const {\n    feeGrowthOutsideA: tickUpperFeeGrowthOutsideAX64,\n    feeGrowthOutsideB: tickUpperFeeGrowthOutsideBX64,\n  } = tickUpper;\n\n  // Calculate the fee growths inside the position\n\n  let feeGrowthBelowAX64: BN | null = null;\n  let feeGrowthBelowBX64: BN | null = null;\n\n  if (tickCurrentIndex < tickLowerIndex) {\n    feeGrowthBelowAX64 = MathUtil.subUnderflowU128(\n      feeGrowthGlobalAX64,\n      tickLowerFeeGrowthOutsideAX64\n    );\n    feeGrowthBelowBX64 = MathUtil.subUnderflowU128(\n      feeGrowthGlobalBX64,\n      tickLowerFeeGrowthOutsideBX64\n    );\n  } else {\n    feeGrowthBelowAX64 = tickLowerFeeGrowthOutsideAX64;\n    feeGrowthBelowBX64 = tickLowerFeeGrowthOutsideBX64;\n  }\n\n  let feeGrowthAboveAX64: BN | null = null;\n  let feeGrowthAboveBX64: BN | null = null;\n\n  if (tickCurrentIndex < tickUpperIndex) {\n    feeGrowthAboveAX64 = tickUpperFeeGrowthOutsideAX64;\n    feeGrowthAboveBX64 = tickUpperFeeGrowthOutsideBX64;\n  } else {\n    feeGrowthAboveAX64 = MathUtil.subUnderflowU128(\n      feeGrowthGlobalAX64,\n      tickUpperFeeGrowthOutsideAX64\n    );\n    feeGrowthAboveBX64 = MathUtil.subUnderflowU128(\n      feeGrowthGlobalBX64,\n      tickUpperFeeGrowthOutsideBX64\n    );\n  }\n\n  const feeGrowthInsideAX64 = MathUtil.subUnderflowU128(\n    MathUtil.subUnderflowU128(feeGrowthGlobalAX64, feeGrowthBelowAX64),\n    feeGrowthAboveAX64\n  );\n  const feeGrowthInsideBX64 = MathUtil.subUnderflowU128(\n    MathUtil.subUnderflowU128(feeGrowthGlobalBX64, feeGrowthBelowBX64),\n    feeGrowthAboveBX64\n  );\n\n  // Calculate the updated fees owed\n  const feeOwedADelta = MathUtil.subUnderflowU128(feeGrowthInsideAX64, feeGrowthCheckpointAX64)\n    .mul(liquidity)\n    .shrn(64);\n  const feeOwedBDelta = MathUtil.subUnderflowU128(feeGrowthInsideBX64, feeGrowthCheckpointBX64)\n    .mul(liquidity)\n    .shrn(64);\n\n  const updatedFeeOwedA = feeOwedA.add(feeOwedADelta);\n  const updatedFeeOwedB = feeOwedB.add(feeOwedBDelta);\n\n  return {\n    feeOwedA: updatedFeeOwedA,\n    feeOwedB: updatedFeeOwedB,\n  };\n}\n","import { MathUtil } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport invariant from \"tiny-invariant\";\nimport { NUM_REWARDS, PositionData, TickData, WhirlpoolData } from \"../../types/public\";\nimport { PoolUtil } from \"../../utils/public/pool-utils\";\n\n/**\n * @category Quotes\n */\nexport type CollectRewardsQuoteParam = {\n  whirlpool: WhirlpoolData;\n  position: PositionData;\n  tickLower: TickData;\n  tickUpper: TickData;\n};\n\n/**\n * @category Quotes\n */\nexport type CollectRewardsQuote = [BN | undefined, BN | undefined, BN | undefined];\n\n/**\n * Get a quote on the outstanding rewards owed to a position.\n *\n * @category Quotes\n * @param param A collection of fetched Whirlpool accounts to faciliate the quote.\n * @returns A quote object containing the rewards owed for each reward in the pool.\n */\nexport function collectRewardsQuote(param: CollectRewardsQuoteParam): CollectRewardsQuote {\n  const { whirlpool, position, tickLower, tickUpper } = param;\n\n  const { tickCurrentIndex, rewardInfos: whirlpoolRewardsInfos } = whirlpool;\n  const { tickLowerIndex, tickUpperIndex, liquidity, rewardInfos } = position;\n\n  // Calculate the reward growths inside the position\n\n  const range = [...Array(NUM_REWARDS).keys()];\n  const rewardGrowthsBelowX64: BN[] = range.map(() => new BN(0));\n  const rewardGrowthsAboveX64: BN[] = range.map(() => new BN(0));\n\n  for (const i of range) {\n    const rewardInfo = whirlpoolRewardsInfos[i];\n    invariant(!!rewardInfo, \"whirlpoolRewardsInfos cannot be undefined\");\n\n    const growthGlobalX64 = rewardInfo.growthGlobalX64;\n    const lowerRewardGrowthsOutside = tickLower.rewardGrowthsOutside[i];\n    const upperRewardGrowthsOutside = tickUpper.rewardGrowthsOutside[i];\n    invariant(!!lowerRewardGrowthsOutside, \"lowerRewardGrowthsOutside cannot be undefined\");\n    invariant(!!upperRewardGrowthsOutside, \"upperRewardGrowthsOutside cannot be undefined\");\n\n    if (tickCurrentIndex < tickLowerIndex) {\n      rewardGrowthsBelowX64[i] = MathUtil.subUnderflowU128(\n        growthGlobalX64,\n        lowerRewardGrowthsOutside\n      );\n    } else {\n      rewardGrowthsBelowX64[i] = lowerRewardGrowthsOutside;\n    }\n\n    if (tickCurrentIndex < tickUpperIndex) {\n      rewardGrowthsAboveX64[i] = upperRewardGrowthsOutside;\n    } else {\n      rewardGrowthsAboveX64[i] = MathUtil.subUnderflowU128(\n        growthGlobalX64,\n        upperRewardGrowthsOutside\n      );\n    }\n  }\n\n  const rewardGrowthsInsideX64: [BN, boolean][] = range.map(() => [new BN(0), false]);\n\n  for (const i of range) {\n    const rewardInfo = whirlpoolRewardsInfos[i];\n    invariant(!!rewardInfo, \"whirlpoolRewardsInfos cannot be undefined\");\n\n    const isRewardInitialized = PoolUtil.isRewardInitialized(rewardInfo);\n\n    if (isRewardInitialized) {\n      const growthBelowX64 = rewardGrowthsBelowX64[i];\n      const growthAboveX64 = rewardGrowthsAboveX64[i];\n      invariant(!!growthBelowX64, \"growthBelowX64 cannot be undefined\");\n      invariant(!!growthAboveX64, \"growthAboveX64 cannot be undefined\");\n\n      const growthInsde = MathUtil.subUnderflowU128(\n        MathUtil.subUnderflowU128(rewardInfo.growthGlobalX64, growthBelowX64),\n        growthAboveX64\n      );\n      rewardGrowthsInsideX64[i] = [growthInsde, true];\n    }\n  }\n\n  // Calculate the updated rewards owed\n\n  const updatedRewardInfosX64: BN[] = range.map(() => new BN(0));\n\n  for (const i of range) {\n    const growthInsideX64 = rewardGrowthsInsideX64[i];\n    invariant(!!growthInsideX64, \"growthInsideX64 cannot be undefined\");\n\n    const [rewardGrowthInsideX64, isRewardInitialized] = growthInsideX64;\n\n    if (isRewardInitialized) {\n      const rewardInfo = rewardInfos[i];\n      invariant(!!rewardInfo, \"rewardInfo cannot be undefined\");\n\n      const amountOwedX64 = rewardInfo.amountOwed.shln(64);\n      const growthInsideCheckpointX64 = rewardInfo.growthInsideCheckpoint;\n      updatedRewardInfosX64[i] = amountOwedX64.add(\n        MathUtil.subUnderflowU128(rewardGrowthInsideX64, growthInsideCheckpointX64).mul(liquidity)\n      );\n    }\n  }\n\n  invariant(rewardGrowthsInsideX64.length >= 3, \"rewards length is less than 3\");\n\n  const rewardExistsA = rewardGrowthsInsideX64[0]?.[1];\n  const rewardExistsB = rewardGrowthsInsideX64[1]?.[1];\n  const rewardExistsC = rewardGrowthsInsideX64[2]?.[1];\n\n  const rewardOwedA = rewardExistsA ? updatedRewardInfosX64[0]?.shrn(64) : undefined;\n  const rewardOwedB = rewardExistsB ? updatedRewardInfosX64[1]?.shrn(64) : undefined;\n  const rewardOwedC = rewardExistsC ? updatedRewardInfosX64[2]?.shrn(64) : undefined;\n\n  return [rewardOwedA, rewardOwedB, rewardOwedC];\n}\n","import { AddressUtil, Percentage } from \"@orca-so/common-sdk\";\nimport { Address, BN } from \"@project-serum/anchor\";\nimport { u64 } from \"@solana/spl-token\";\nimport invariant from \"tiny-invariant\";\nimport { SwapInput } from \"../../instructions\";\nimport { AccountFetcher } from \"../../network/public\";\nimport { TickArray, WhirlpoolData } from \"../../types/public\";\nimport { PoolUtil, TokenType } from \"../../utils/public\";\nimport { SwapUtils } from \"../../utils/public/swap-utils\";\nimport { Whirlpool } from \"../../whirlpool-client\";\nimport { simulateSwap } from \"../swap/swap-quote-impl\";\nimport { DevFeeSwapQuote } from \"./dev-fee-swap-quote\";\n\n/**\n * @category Quotes\n *\n * @param tokenAmount - The amount of input or output token to swap from (depending on amountSpecifiedIsInput).\n * @param otherAmountThreshold - The maximum/minimum of input/output token to swap into (depending on amountSpecifiedIsInput).\n * @param sqrtPriceLimit - The maximum/minimum price the swap will swap to.\n * @param aToB - The direction of the swap. True if swapping from A to B. False if swapping from B to A.\n * @param amountSpecifiedIsInput - Specifies the token the parameter `amount`represents. If true, the amount represents\n *                                 the input token of the swap.\n * @param tickArrays - An sequential array of tick-array objects in the direction of the trade to swap on\n */\nexport type SwapQuoteParam = {\n  whirlpoolData: WhirlpoolData;\n  tokenAmount: u64;\n  otherAmountThreshold: u64;\n  sqrtPriceLimit: BN;\n  aToB: boolean;\n  amountSpecifiedIsInput: boolean;\n  tickArrays: TickArray[];\n};\n\n/**\n * A collection of estimated values from quoting a swap.\n * @category Quotes\n * @link {BaseSwapQuote}\n * @link {DevFeeSwapQuote}\n */\nexport type SwapQuote = NormalSwapQuote | DevFeeSwapQuote;\n\n/**\n * A collection of estimated values from quoting a swap.\n * @category Quotes\n * @param estimatedAmountIn - Approximate number of input token swapped in the swap\n * @param estimatedAmountOut - Approximate number of output token swapped in the swap\n * @param estimatedEndTickIndex - Approximate tick-index the Whirlpool will land on after this swap\n * @param estimatedEndSqrtPrice - Approximate sqrtPrice the Whirlpool will land on after this swap\n * @param estimatedFeeAmount - Approximate feeAmount (all fees) charged on this swap\n */\nexport type NormalSwapQuote = {\n  estimatedAmountIn: u64;\n  estimatedAmountOut: u64;\n  estimatedEndTickIndex: number;\n  estimatedEndSqrtPrice: BN;\n  estimatedFeeAmount: u64;\n} & SwapInput;\n\n/**\n * Get an estimated swap quote using input token amount.\n *\n * @category Quotes\n * @param whirlpool - Whirlpool to perform the swap on\n * @param inputTokenMint - PublicKey for the input token mint to swap with\n * @param tokenAmount - The amount of input token to swap from\n * @param slippageTolerance - The amount of slippage to account for in this quote\n * @param programId - PublicKey for the Whirlpool ProgramId\n * @param fetcher - AccountFetcher object to fetch solana accounts\n * @param refresh - If true, fetcher would default to fetching the latest accounts\n * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states.\n */\nexport async function swapQuoteByInputToken(\n  whirlpool: Whirlpool,\n  inputTokenMint: Address,\n  tokenAmount: u64,\n  slippageTolerance: Percentage,\n  programId: Address,\n  fetcher: AccountFetcher,\n  refresh: boolean\n): Promise<SwapQuote> {\n  const params = await swapQuoteByToken(\n    whirlpool,\n    inputTokenMint,\n    tokenAmount,\n    TokenType.TokenA,\n    true,\n    programId,\n    fetcher,\n    refresh\n  );\n  return swapQuoteWithParams(params);\n}\n\n/**\n * Get an estimated swap quote using an output token amount.\n *\n * Use this quote to get an estimated amount of input token needed to receive\n * the defined output token amount.\n *\n * @category Quotes\n * @param whirlpool - Whirlpool to perform the swap on\n * @param outputTokenMint - PublicKey for the output token mint to swap into\n * @param tokenAmount - The maximum amount of output token to receive in this swap.\n * @param slippageTolerance - The amount of slippage to account for in this quote\n * @param programId - PublicKey for the Whirlpool ProgramId\n * @param fetcher - AccountFetcher object to fetch solana accounts\n * @param refresh - If true, fetcher would default to fetching the latest accounts\n * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states.\n */\nexport async function swapQuoteByOutputToken(\n  whirlpool: Whirlpool,\n  outputTokenMint: Address,\n  tokenAmount: u64,\n  slippageTolerance: Percentage,\n  programId: Address,\n  fetcher: AccountFetcher,\n  refresh: boolean\n): Promise<SwapQuote> {\n  const params = await swapQuoteByToken(\n    whirlpool,\n    outputTokenMint,\n    tokenAmount,\n    TokenType.TokenB,\n    false,\n    programId,\n    fetcher,\n    refresh\n  );\n  return swapQuoteWithParams(params);\n}\n\n/**\n * Perform a sync swap quote based on the basic swap instruction parameters.\n *\n * @category Quotes\n * @param params - SwapQuote parameters\n * @param slippageTolerance - The amount of slippage to account for when generating the final quote.\n * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states.\n */\nexport function swapQuoteWithParams(params: SwapQuoteParam): SwapQuote {\n  const quote = simulateSwap(params);\n\n  const slippageAdjustedQuote: SwapQuote = {\n    ...quote,\n    ...SwapUtils.calculateSwapAmountsFromQuote(quote.amount, quote.amountSpecifiedIsInput),\n  };\n\n  return slippageAdjustedQuote;\n}\n\nasync function swapQuoteByToken(\n  whirlpool: Whirlpool,\n  inputTokenMint: Address,\n  tokenAmount: u64,\n  amountSpecifiedTokenType: TokenType,\n  amountSpecifiedIsInput: boolean,\n  programId: Address,\n  fetcher: AccountFetcher,\n  refresh: boolean\n): Promise<SwapQuoteParam> {\n  const whirlpoolData = whirlpool.getData();\n  const swapMintKey = AddressUtil.toPubKey(inputTokenMint);\n  const swapTokenType = PoolUtil.getTokenType(whirlpoolData, swapMintKey);\n  invariant(!!swapTokenType, \"swapTokenMint does not match any tokens on this pool\");\n\n  const aToB = swapTokenType === amountSpecifiedTokenType;\n\n  const tickArrays = await SwapUtils.getTickArrays(\n    whirlpoolData.tickCurrentIndex,\n    whirlpoolData.tickSpacing,\n    aToB,\n    AddressUtil.toPubKey(programId),\n    whirlpool.getAddress(),\n    fetcher,\n    refresh\n  );\n\n  return {\n    whirlpoolData,\n    tokenAmount,\n    aToB,\n    amountSpecifiedIsInput,\n    sqrtPriceLimit: SwapUtils.getDefaultSqrtPriceLimit(aToB),\n    otherAmountThreshold: SwapUtils.getDefaultOtherAmountThreshold(amountSpecifiedIsInput),\n    tickArrays,\n  };\n}\n","import { ZERO } from \"@orca-so/common-sdk\";\nimport { SwapQuoteParam, SwapQuote } from \"../public\";\nimport { BN } from \"@project-serum/anchor\";\nimport { TickArraySequence } from \"./tick-array-sequence\";\nimport { computeSwap } from \"./swap-manager\";\nimport { MAX_SQRT_PRICE, MAX_SWAP_TICK_ARRAYS, MIN_SQRT_PRICE } from \"../../types/public\";\nimport { SwapErrorCode, WhirlpoolsError } from \"../../errors/errors\";\n\n/**\n * Figure out the quote parameters needed to successfully complete this trade on chain\n * @param param\n * @returns\n * @exceptions\n */\nexport function simulateSwap(params: SwapQuoteParam): SwapQuote {\n  const {\n    aToB,\n    whirlpoolData,\n    tickArrays,\n    tokenAmount,\n    sqrtPriceLimit,\n    otherAmountThreshold,\n    amountSpecifiedIsInput,\n  } = params;\n\n  if (sqrtPriceLimit.gt(new BN(MAX_SQRT_PRICE)) || sqrtPriceLimit.lt(new BN(MIN_SQRT_PRICE))) {\n    throw new WhirlpoolsError(\n      \"Provided SqrtPriceLimit is out of bounds.\",\n      SwapErrorCode.SqrtPriceOutOfBounds\n    );\n  }\n\n  if (\n    (aToB && sqrtPriceLimit.gt(whirlpoolData.sqrtPrice)) ||\n    (!aToB && sqrtPriceLimit.lt(whirlpoolData.sqrtPrice))\n  ) {\n    throw new WhirlpoolsError(\n      \"Provided SqrtPriceLimit is in the opposite direction of the trade.\",\n      SwapErrorCode.InvalidSqrtPriceLimitDirection\n    );\n  }\n\n  if (tokenAmount.eq(ZERO)) {\n    throw new WhirlpoolsError(\"Provided tokenAmount is zero.\", SwapErrorCode.ZeroTradableAmount);\n  }\n\n  const tickSequence = new TickArraySequence(tickArrays, whirlpoolData.tickSpacing, aToB);\n\n  // Ensure 1st search-index resides on the 1st array in the sequence to match smart contract expectation.\n  if (!tickSequence.isValidTickArray0(whirlpoolData.tickCurrentIndex)) {\n    throw new WhirlpoolsError(\n      \"TickArray at index 0 does not contain the Whirlpool current tick index.\",\n      SwapErrorCode.TickArraySequenceInvalid\n    );\n  }\n\n  const swapResults = computeSwap(\n    whirlpoolData,\n    tickSequence,\n    tokenAmount,\n    sqrtPriceLimit,\n    amountSpecifiedIsInput,\n    aToB\n  );\n\n  if (amountSpecifiedIsInput) {\n    if (\n      (aToB && otherAmountThreshold.gt(swapResults.amountB)) ||\n      (!aToB && otherAmountThreshold.gt(swapResults.amountA))\n    ) {\n      throw new WhirlpoolsError(\n        \"Quoted amount for the other token is below the otherAmountThreshold.\",\n        SwapErrorCode.AmountOutBelowMinimum\n      );\n    }\n  } else {\n    if (\n      (aToB && otherAmountThreshold.lt(swapResults.amountA)) ||\n      (!aToB && otherAmountThreshold.lt(swapResults.amountB))\n    ) {\n      throw new WhirlpoolsError(\n        \"Quoted amount for the other token is above the otherAmountThreshold.\",\n        SwapErrorCode.AmountInAboveMaximum\n      );\n    }\n  }\n\n  const { estimatedAmountIn, estimatedAmountOut } = remapAndAdjustTokens(\n    swapResults.amountA,\n    swapResults.amountB,\n    aToB\n  );\n\n  const numOfTickCrossings = tickSequence.getNumOfTouchedArrays();\n  if (numOfTickCrossings > MAX_SWAP_TICK_ARRAYS) {\n    throw new WhirlpoolsError(\n      `Input amount causes the quote to traverse more than the allowable amount of tick-arrays ${numOfTickCrossings}`,\n      SwapErrorCode.TickArrayCrossingAboveMax\n    );\n  }\n\n  const touchedArrays = tickSequence.getTouchedArrays(MAX_SWAP_TICK_ARRAYS);\n\n  return {\n    estimatedAmountIn,\n    estimatedAmountOut,\n    estimatedEndTickIndex: swapResults.nextTickIndex,\n    estimatedEndSqrtPrice: swapResults.nextSqrtPrice,\n    estimatedFeeAmount: swapResults.totalFeeAmount,\n    amount: tokenAmount,\n    amountSpecifiedIsInput,\n    aToB,\n    otherAmountThreshold,\n    sqrtPriceLimit,\n    tickArray0: touchedArrays[0],\n    tickArray1: touchedArrays[1],\n    tickArray2: touchedArrays[2],\n  };\n}\n\nfunction remapAndAdjustTokens(amountA: BN, amountB: BN, aToB: boolean) {\n  const estimatedAmountIn = aToB ? amountA : amountB;\n  const estimatedAmountOut = aToB ? amountB : amountA;\n  return {\n    estimatedAmountIn,\n    estimatedAmountOut,\n  };\n}\n","export enum MathErrorCode {\n  MultiplicationOverflow = `MultiplicationOverflow`,\n  MulDivOverflow = `MulDivOverflow`,\n  MultiplicationShiftRightOverflow = `MultiplicationShiftRightOverflow`,\n  DivideByZero = `DivideByZero`,\n}\n\nexport enum TokenErrorCode {\n  TokenMaxExceeded = `TokenMaxExceeded`,\n  TokenMinSubceeded = `TokenMinSubceeded`,\n}\n\nexport enum SwapErrorCode {\n  InvalidDevFeePercentage = `InvalidDevFeePercentage`,\n  InvalidSqrtPriceLimitDirection = `InvalidSqrtPriceLimitDirection`,\n  SqrtPriceOutOfBounds = `SqrtPriceOutOfBounds`,\n  ZeroTradableAmount = `ZeroTradableAmount`,\n  AmountOutBelowMinimum = `AmountOutBelowMinimum`,\n  AmountInAboveMaximum = `AmountInAboveMaximum`,\n  TickArrayCrossingAboveMax = `TickArrayCrossingAboveMax`,\n  TickArrayIndexNotInitialized = `TickArrayIndexNotInitialized`,\n  TickArraySequenceInvalid = `TickArraySequenceInvalid`,\n}\n\nexport type WhirlpoolsErrorCode = TokenErrorCode | SwapErrorCode | MathErrorCode;\n\nexport class WhirlpoolsError extends Error {\n  message: string;\n  errorCode?: WhirlpoolsErrorCode;\n  constructor(message: string, errorCode?: WhirlpoolsErrorCode) {\n    super(message);\n    this.message = message;\n    this.errorCode = errorCode;\n  }\n\n  public static isWhirlpoolsErrorCode(e: any, code: WhirlpoolsErrorCode): boolean {\n    return e instanceof WhirlpoolsError && e.errorCode === code;\n  }\n}\n","import { TICK_ARRAY_SIZE } from \"../../types/public\";\n\nexport class TickArrayIndex {\n  static fromTickIndex(index: number, tickSpacing: number) {\n    const arrayIndex = Math.floor(Math.floor(index / tickSpacing) / TICK_ARRAY_SIZE);\n    let offsetIndex = Math.floor((index % (tickSpacing * TICK_ARRAY_SIZE)) / tickSpacing);\n    if (offsetIndex < 0) {\n      offsetIndex = TICK_ARRAY_SIZE + offsetIndex;\n    }\n    return new TickArrayIndex(arrayIndex, offsetIndex, tickSpacing);\n  }\n\n  constructor(\n    readonly arrayIndex: number,\n    readonly offsetIndex: number,\n    readonly tickSpacing: number\n  ) {\n    if (offsetIndex >= TICK_ARRAY_SIZE) {\n      throw new Error(\"Invalid offsetIndex - value has to be smaller than TICK_ARRAY_SIZE\");\n    }\n    if (offsetIndex < 0) {\n      throw new Error(\"Invalid offsetIndex - value is smaller than 0\");\n    }\n\n    if (tickSpacing < 0) {\n      throw new Error(\"Invalid tickSpacing - value is less than 0\");\n    }\n  }\n\n  toTickIndex() {\n    return (\n      this.arrayIndex * TICK_ARRAY_SIZE * this.tickSpacing + this.offsetIndex * this.tickSpacing\n    );\n  }\n\n  toNextInitializableTickIndex() {\n    return TickArrayIndex.fromTickIndex(this.toTickIndex() + this.tickSpacing, this.tickSpacing);\n  }\n\n  toPrevInitializableTickIndex() {\n    return TickArrayIndex.fromTickIndex(this.toTickIndex() - this.tickSpacing, this.tickSpacing);\n  }\n}\n","import { SwapErrorCode, WhirlpoolsError } from \"../../errors/errors\";\nimport {\n  MAX_TICK_INDEX,\n  MIN_TICK_INDEX,\n  TickArray,\n  TickArrayData,\n  TickData,\n  TICK_ARRAY_SIZE,\n} from \"../../types/public\";\nimport { TickArrayIndex } from \"./tick-array-index\";\nimport { PublicKey } from \"@solana/web3.js\";\n\ntype InitializedTickArray = TickArray & {\n  // override\n  data: TickArrayData;\n};\n\n/**\n * NOTE: differs from contract method of having the swap manager keep track of array index.\n * This is due to the initial requirement to lazy load tick-arrays. This requirement is no longer necessary.\n */\nexport class TickArraySequence {\n  private sequence: InitializedTickArray[];\n  private touchedArrays: boolean[];\n  private startArrayIndex: number;\n\n  constructor(\n    tickArrays: Readonly<TickArray[]>,\n    readonly tickSpacing: number,\n    readonly aToB: boolean\n  ) {\n    if (!tickArrays[0] || !tickArrays[0].data) {\n      throw new Error(\"TickArray index 0 must be initialized\");\n    }\n\n    // If an uninitialized TickArray appears, truncate all TickArrays after it (inclusive).\n    this.sequence = [];\n    for (const tickArray of tickArrays) {\n      if (!tickArray || !tickArray.data) {\n        break;\n      }\n      this.sequence.push({\n        address: tickArray.address,\n        data: tickArray.data,\n      });\n    }\n\n    this.touchedArrays = [...Array<boolean>(this.sequence.length).fill(false)];\n    this.startArrayIndex = TickArrayIndex.fromTickIndex(\n      this.sequence[0].data.startTickIndex,\n      this.tickSpacing\n    ).arrayIndex;\n  }\n\n  isValidTickArray0(tickCurrentIndex: number) {\n    const shift = this.aToB ? 0 : this.tickSpacing;\n    const tickArray = this.sequence[0].data;\n    return this.checkIfIndexIsInTickArrayRange(tickArray.startTickIndex, tickCurrentIndex + shift);\n  }\n\n  getNumOfTouchedArrays() {\n    return this.touchedArrays.filter((val) => !!val).length;\n  }\n\n  getTouchedArrays(minArraySize: number): PublicKey[] {\n    let result = this.touchedArrays.reduce<PublicKey[]>((prev, curr, index) => {\n      if (curr) {\n        prev.push(this.sequence[index].address);\n      }\n      return prev;\n    }, []);\n\n    // Edge case: nothing was ever touched.\n    if (result.length === 0) {\n      return [];\n    }\n\n    // The quote object should contain the specified amount of tick arrays to be plugged\n    // directly into the swap instruction.\n    // If the result does not fit minArraySize, pad the rest with the last touched array\n    const sizeDiff = minArraySize - result.length;\n    if (sizeDiff > 0) {\n      result = result.concat(Array(sizeDiff).fill(result[result.length - 1]));\n    }\n\n    return result;\n  }\n\n  getTick(index: number): TickData {\n    const targetTaIndex = TickArrayIndex.fromTickIndex(index, this.tickSpacing);\n\n    if (!this.isArrayIndexInBounds(targetTaIndex, this.aToB)) {\n      throw new Error(\"Provided tick index is out of bounds for this sequence.\");\n    }\n\n    const localArrayIndex = this.getLocalArrayIndex(targetTaIndex.arrayIndex, this.aToB);\n    const tickArray = this.sequence[localArrayIndex].data;\n\n    this.touchedArrays[localArrayIndex] = true;\n\n    if (!tickArray) {\n      throw new WhirlpoolsError(\n        `TickArray at index ${localArrayIndex} is not initialized.`,\n        SwapErrorCode.TickArrayIndexNotInitialized\n      );\n    }\n\n    if (!this.checkIfIndexIsInTickArrayRange(tickArray.startTickIndex, index)) {\n      throw new WhirlpoolsError(\n        `TickArray at index ${localArrayIndex} is unexpected for this sequence.`,\n        SwapErrorCode.TickArraySequenceInvalid\n      );\n    }\n\n    return tickArray.ticks[targetTaIndex.offsetIndex];\n  }\n  /**\n   * if a->b, currIndex is included in the search\n   * if b->a, currIndex is always ignored\n   * @param currIndex\n   * @returns\n   */\n  findNextInitializedTickIndex(currIndex: number) {\n    const searchIndex = this.aToB ? currIndex : currIndex + this.tickSpacing;\n    let currTaIndex = TickArrayIndex.fromTickIndex(searchIndex, this.tickSpacing);\n\n    // Throw error if the search attempted to search for an index out of bounds\n    if (!this.isArrayIndexInBounds(currTaIndex, this.aToB)) {\n      throw new WhirlpoolsError(\n        `Swap input value traversed too many arrays. Out of bounds at attempt to traverse tick index - ${currTaIndex.toTickIndex()}.`,\n        SwapErrorCode.TickArraySequenceInvalid\n      );\n    }\n\n    while (this.isArrayIndexInBounds(currTaIndex, this.aToB)) {\n      const currTickData = this.getTick(currTaIndex.toTickIndex());\n      if (currTickData.initialized) {\n        return { nextIndex: currTaIndex.toTickIndex(), nextTickData: currTickData };\n      }\n      currTaIndex = this.aToB\n        ? currTaIndex.toPrevInitializableTickIndex()\n        : currTaIndex.toNextInitializableTickIndex();\n    }\n\n    const lastIndexInArray = Math.max(\n      Math.min(\n        this.aToB ? currTaIndex.toTickIndex() + this.tickSpacing : currTaIndex.toTickIndex() - 1,\n        MAX_TICK_INDEX\n      ),\n      MIN_TICK_INDEX\n    );\n\n    return { nextIndex: lastIndexInArray, nextTickData: null };\n  }\n\n  private getLocalArrayIndex(arrayIndex: number, aToB: boolean) {\n    return aToB ? this.startArrayIndex - arrayIndex : arrayIndex - this.startArrayIndex;\n  }\n\n  /**\n   * Check whether the array index potentially exists in this sequence.\n   * Note: assumes the sequence of tick-arrays are sequential\n   * @param index\n   */\n  private isArrayIndexInBounds(index: TickArrayIndex, aToB: boolean) {\n    // a+0...a+n-1 array index is ok\n    const localArrayIndex = this.getLocalArrayIndex(index.arrayIndex, aToB);\n    const seqLength = this.sequence.length;\n    return localArrayIndex >= 0 && localArrayIndex < seqLength;\n  }\n\n  private checkIfIndexIsInTickArrayRange(startTick: number, tickIndex: number) {\n    const upperBound = startTick + this.tickSpacing * TICK_ARRAY_SIZE;\n    return tickIndex >= startTick && tickIndex < upperBound;\n  }\n}\n","import { ZERO } from \"@orca-so/common-sdk\";\nimport { u64 } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\nimport { PROTOCOL_FEE_RATE_MUL_VALUE, WhirlpoolData } from \"../../types/public\";\nimport { PriceMath } from \"../../utils/public\";\nimport { TickArraySequence } from \"./tick-array-sequence\";\nimport { computeSwapStep } from \"../../utils/math/swap-math\";\n\nexport type SwapResult = {\n  amountA: BN;\n  amountB: BN;\n  nextTickIndex: number;\n  nextSqrtPrice: BN;\n  totalFeeAmount: BN;\n};\n\nexport function computeSwap(\n  whirlpoolData: WhirlpoolData,\n  tickSequence: TickArraySequence,\n  tokenAmount: u64,\n  sqrtPriceLimit: BN,\n  amountSpecifiedIsInput: boolean,\n  aToB: boolean\n): SwapResult {\n  let amountRemaining = tokenAmount;\n  let amountCalculated = ZERO;\n  let currSqrtPrice = whirlpoolData.sqrtPrice;\n  let currLiquidity = whirlpoolData.liquidity;\n  let currTickIndex = whirlpoolData.tickCurrentIndex;\n  let totalFeeAmount = ZERO;\n  const feeRate = whirlpoolData.feeRate;\n  const protocolFeeRate = whirlpoolData.protocolFeeRate;\n  let currProtocolFee = new u64(0);\n  let currFeeGrowthGlobalInput = aToB\n    ? whirlpoolData.feeGrowthGlobalA\n    : whirlpoolData.feeGrowthGlobalB;\n\n  while (amountRemaining.gt(ZERO) && !sqrtPriceLimit.eq(currSqrtPrice)) {\n    let { nextIndex: nextTickIndex } = tickSequence.findNextInitializedTickIndex(currTickIndex);\n\n    let { nextTickPrice, nextSqrtPriceLimit: targetSqrtPrice } = getNextSqrtPrices(\n      nextTickIndex,\n      sqrtPriceLimit,\n      aToB\n    );\n\n    const swapComputation = computeSwapStep(\n      amountRemaining,\n      feeRate,\n      currLiquidity,\n      currSqrtPrice,\n      targetSqrtPrice,\n      amountSpecifiedIsInput,\n      aToB\n    );\n\n    totalFeeAmount = totalFeeAmount.add(swapComputation.feeAmount);\n\n    if (amountSpecifiedIsInput) {\n      amountRemaining = amountRemaining.sub(swapComputation.amountIn);\n      amountRemaining = amountRemaining.sub(swapComputation.feeAmount);\n      amountCalculated = amountCalculated.add(swapComputation.amountOut);\n    } else {\n      amountRemaining = amountRemaining.sub(swapComputation.amountOut);\n      amountCalculated = amountCalculated.add(swapComputation.amountIn);\n      amountCalculated = amountCalculated.add(swapComputation.feeAmount);\n    }\n\n    let { nextProtocolFee, nextFeeGrowthGlobalInput } = calculateFees(\n      swapComputation.feeAmount,\n      protocolFeeRate,\n      currLiquidity,\n      currProtocolFee,\n      currFeeGrowthGlobalInput\n    );\n    currProtocolFee = nextProtocolFee;\n    currFeeGrowthGlobalInput = nextFeeGrowthGlobalInput;\n\n    if (swapComputation.nextPrice.eq(nextTickPrice)) {\n      const nextTick = tickSequence.getTick(nextTickIndex);\n      if (nextTick.initialized) {\n        currLiquidity = calculateNextLiquidity(nextTick.liquidityNet, currLiquidity, aToB);\n      }\n      currTickIndex = aToB ? nextTickIndex - 1 : nextTickIndex;\n    } else {\n      currTickIndex = PriceMath.sqrtPriceX64ToTickIndex(swapComputation.nextPrice);\n    }\n\n    currSqrtPrice = swapComputation.nextPrice;\n  }\n\n  let { amountA, amountB } = calculateEstTokens(\n    tokenAmount,\n    amountRemaining,\n    amountCalculated,\n    aToB,\n    amountSpecifiedIsInput\n  );\n\n  return {\n    amountA,\n    amountB,\n    nextTickIndex: currTickIndex,\n    nextSqrtPrice: currSqrtPrice,\n    totalFeeAmount,\n  };\n}\n\nfunction getNextSqrtPrices(nextTick: number, sqrtPriceLimit: BN, aToB: boolean) {\n  const nextTickPrice = PriceMath.tickIndexToSqrtPriceX64(nextTick);\n  const nextSqrtPriceLimit = aToB\n    ? BN.max(sqrtPriceLimit, nextTickPrice)\n    : BN.min(sqrtPriceLimit, nextTickPrice);\n  return { nextTickPrice, nextSqrtPriceLimit };\n}\n\nfunction calculateFees(\n  feeAmount: BN,\n  protocolFeeRate: number,\n  currLiquidity: BN,\n  currProtocolFee: BN,\n  currFeeGrowthGlobalInput: BN\n) {\n  let nextProtocolFee = currProtocolFee;\n  let nextFeeGrowthGlobalInput = currFeeGrowthGlobalInput;\n  let globalFee = feeAmount;\n\n  if (protocolFeeRate > 0) {\n    let delta = calculateProtocolFee(globalFee, protocolFeeRate);\n    globalFee = globalFee.sub(delta);\n    nextProtocolFee = nextProtocolFee.add(currProtocolFee);\n  }\n\n  if (currLiquidity.gt(ZERO)) {\n    const globalFeeIncrement = globalFee.shln(64).div(currLiquidity);\n    nextFeeGrowthGlobalInput = nextFeeGrowthGlobalInput.add(globalFeeIncrement);\n  }\n\n  return {\n    nextProtocolFee,\n    nextFeeGrowthGlobalInput,\n  };\n}\n\nfunction calculateProtocolFee(globalFee: BN, protocolFeeRate: number) {\n  return globalFee.mul(new u64(protocolFeeRate).div(PROTOCOL_FEE_RATE_MUL_VALUE));\n}\n\nfunction calculateEstTokens(\n  amount: BN,\n  amountRemaining: BN,\n  amountCalculated: BN,\n  aToB: boolean,\n  amountSpecifiedIsInput: boolean\n) {\n  return aToB === amountSpecifiedIsInput\n    ? {\n        amountA: amount.sub(amountRemaining),\n        amountB: amountCalculated,\n      }\n    : {\n        amountA: amountCalculated,\n        amountB: amount.sub(amountRemaining),\n      };\n}\n\nfunction calculateNextLiquidity(tickNetLiquidity: BN, currLiquidity: BN, aToB: boolean) {\n  return aToB ? currLiquidity.sub(tickNetLiquidity) : currLiquidity.add(tickNetLiquidity);\n}\n","import { u64 } from \"@solana/spl-token\";\nimport { BN } from \"@project-serum/anchor\";\nimport { getAmountDeltaA, getAmountDeltaB, getNextSqrtPrice } from \"./token-math\";\nimport { BitMath } from \"./bit-math\";\nimport { FEE_RATE_MUL_VALUE } from \"../../types/public\";\n\nexport type SwapStep = {\n  amountIn: BN;\n  amountOut: BN;\n  nextPrice: BN;\n  feeAmount: BN;\n};\n\nexport function computeSwapStep(\n  amountRemaining: u64,\n  feeRate: number,\n  currLiquidity: BN,\n  currSqrtPrice: BN,\n  targetSqrtPrice: BN,\n  amountSpecifiedIsInput: boolean,\n  aToB: boolean\n): SwapStep {\n  let amountFixedDelta = getAmountFixedDelta(\n    currSqrtPrice,\n    targetSqrtPrice,\n    currLiquidity,\n    amountSpecifiedIsInput,\n    aToB\n  );\n\n  let amountCalc = amountRemaining;\n  if (amountSpecifiedIsInput) {\n    const result = BitMath.mulDiv(\n      amountRemaining,\n      FEE_RATE_MUL_VALUE.sub(new BN(feeRate)),\n      FEE_RATE_MUL_VALUE,\n      128\n    );\n    amountCalc = result;\n  }\n\n  let nextSqrtPrice = amountCalc.gte(amountFixedDelta)\n    ? targetSqrtPrice\n    : getNextSqrtPrice(currSqrtPrice, currLiquidity, amountCalc, amountSpecifiedIsInput, aToB);\n\n  let isMaxSwap = nextSqrtPrice.eq(targetSqrtPrice);\n\n  let amountUnfixedDelta = getAmountUnfixedDelta(\n    currSqrtPrice,\n    nextSqrtPrice,\n    currLiquidity,\n    amountSpecifiedIsInput,\n    aToB\n  );\n\n  if (!isMaxSwap) {\n    amountFixedDelta = getAmountFixedDelta(\n      currSqrtPrice,\n      nextSqrtPrice,\n      currLiquidity,\n      amountSpecifiedIsInput,\n      aToB\n    );\n  }\n\n  let amountIn = amountSpecifiedIsInput ? amountFixedDelta : amountUnfixedDelta;\n  let amountOut = amountSpecifiedIsInput ? amountUnfixedDelta : amountFixedDelta;\n\n  if (!amountSpecifiedIsInput && amountOut.gt(amountRemaining)) {\n    amountOut = amountRemaining;\n  }\n\n  let feeAmount: BN;\n  if (amountSpecifiedIsInput && !isMaxSwap) {\n    feeAmount = amountRemaining.sub(amountIn);\n  } else {\n    const feeRateBN = new BN(feeRate);\n    feeAmount = BitMath.mulDivRoundUp(amountIn, feeRateBN, FEE_RATE_MUL_VALUE.sub(feeRateBN), 128);\n  }\n\n  return {\n    amountIn,\n    amountOut,\n    nextPrice: nextSqrtPrice,\n    feeAmount,\n  };\n}\n\nfunction getAmountFixedDelta(\n  currSqrtPrice: BN,\n  targetSqrtPrice: BN,\n  currLiquidity: BN,\n  amountSpecifiedIsInput: boolean,\n  aToB: boolean\n) {\n  if (aToB === amountSpecifiedIsInput) {\n    return getAmountDeltaA(currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput);\n  } else {\n    return getAmountDeltaB(currSqrtPrice, targetSqrtPrice, currLiquidity, amountSpecifiedIsInput);\n  }\n}\n\nfunction getAmountUnfixedDelta(\n  currSqrtPrice: BN,\n  targetSqrtPrice: BN,\n  currLiquidity: BN,\n  amountSpecifiedIsInput: boolean,\n  aToB: boolean\n) {\n  if (aToB === amountSpecifiedIsInput) {\n    return getAmountDeltaB(currSqrtPrice, targetSqrtPrice, currLiquidity, !amountSpecifiedIsInput);\n  } else {\n    return getAmountDeltaA(currSqrtPrice, targetSqrtPrice, currLiquidity, !amountSpecifiedIsInput);\n  }\n}\n","import { Percentage, U64_MAX, ZERO } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport { u64 } from \"@solana/spl-token\";\nimport { MathErrorCode, TokenErrorCode, WhirlpoolsError } from \"../../errors/errors\";\nimport { MAX_SQRT_PRICE, MIN_SQRT_PRICE } from \"../../types/public\";\nimport { BitMath } from \"./bit-math\";\n\nexport function getAmountDeltaA(\n  currSqrtPrice: BN,\n  targetSqrtPrice: BN,\n  currLiquidity: BN,\n  roundUp: boolean\n): BN {\n  let [sqrtPriceLower, sqrtPriceUpper] = toIncreasingPriceOrder(currSqrtPrice, targetSqrtPrice);\n  let sqrtPriceDiff = sqrtPriceUpper.sub(sqrtPriceLower);\n\n  let numerator = currLiquidity.mul(sqrtPriceDiff).shln(64);\n  let denominator = sqrtPriceLower.mul(sqrtPriceUpper);\n\n  let quotient = numerator.div(denominator);\n  let remainder = numerator.mod(denominator);\n\n  let result = roundUp && !remainder.eq(ZERO) ? quotient.add(new BN(1)) : quotient;\n\n  if (result.gt(U64_MAX)) {\n    throw new WhirlpoolsError(\"Results larger than U64\", TokenErrorCode.TokenMaxExceeded);\n  }\n\n  return result;\n}\n\nexport function getAmountDeltaB(\n  currSqrtPrice: BN,\n  targetSqrtPrice: BN,\n  currLiquidity: BN,\n  roundUp: boolean\n): BN {\n  let [sqrtPriceLower, sqrtPriceUpper] = toIncreasingPriceOrder(currSqrtPrice, targetSqrtPrice);\n  let sqrtPriceDiff = sqrtPriceUpper.sub(sqrtPriceLower);\n  return BitMath.checked_mul_shift_right_round_up_if(currLiquidity, sqrtPriceDiff, roundUp, 128);\n}\n\nexport function getNextSqrtPrice(\n  sqrtPrice: BN,\n  currLiquidity: BN,\n  amount: u64,\n  amountSpecifiedIsInput: boolean,\n  aToB: boolean\n) {\n  if (amountSpecifiedIsInput === aToB) {\n    return getNextSqrtPriceFromARoundUp(sqrtPrice, currLiquidity, amount, amountSpecifiedIsInput);\n  } else {\n    return getNextSqrtPriceFromBRoundDown(sqrtPrice, currLiquidity, amount, amountSpecifiedIsInput);\n  }\n}\n\nexport function adjustForSlippage(\n  n: BN,\n  { numerator, denominator }: Percentage,\n  adjustUp: boolean\n): BN {\n  if (adjustUp) {\n    return n.mul(denominator.add(numerator)).div(denominator);\n  } else {\n    return n.mul(denominator).div(denominator.add(numerator));\n  }\n}\n\nfunction toIncreasingPriceOrder(sqrtPrice0: BN, sqrtPrice1: BN) {\n  if (sqrtPrice0.gt(sqrtPrice1)) {\n    return [sqrtPrice1, sqrtPrice0];\n  } else {\n    return [sqrtPrice0, sqrtPrice1];\n  }\n}\n\nfunction getNextSqrtPriceFromARoundUp(\n  sqrtPrice: BN,\n  currLiquidity: BN,\n  amount: u64,\n  amountSpecifiedIsInput: boolean\n) {\n  if (amount.eq(ZERO)) {\n    return sqrtPrice;\n  }\n\n  let p = BitMath.mul(sqrtPrice, amount, 256);\n  let numerator = BitMath.mul(currLiquidity, sqrtPrice, 256).shln(64);\n  if (BitMath.isOverLimit(numerator, 256)) {\n    throw new WhirlpoolsError(\n      \"getNextSqrtPriceFromARoundUp - numerator overflow u256\",\n      MathErrorCode.MultiplicationOverflow\n    );\n  }\n\n  let currLiquidityShiftLeft = currLiquidity.shln(64);\n  if (!amountSpecifiedIsInput && currLiquidityShiftLeft.lte(p)) {\n    throw new WhirlpoolsError(\n      \"getNextSqrtPriceFromARoundUp - Unable to divide currLiquidityX64 by product\",\n      MathErrorCode.DivideByZero\n    );\n  }\n\n  let denominator = amountSpecifiedIsInput\n    ? currLiquidityShiftLeft.add(p)\n    : currLiquidityShiftLeft.sub(p);\n\n  let price = BitMath.divRoundUp(numerator, denominator);\n\n  if (price.lt(new BN(MIN_SQRT_PRICE))) {\n    throw new WhirlpoolsError(\n      \"getNextSqrtPriceFromARoundUp - price less than min sqrt price\",\n      TokenErrorCode.TokenMinSubceeded\n    );\n  } else if (price.gt(new BN(MAX_SQRT_PRICE))) {\n    throw new WhirlpoolsError(\n      \"getNextSqrtPriceFromARoundUp - price less than max sqrt price\",\n      TokenErrorCode.TokenMaxExceeded\n    );\n  }\n\n  return price;\n}\n\nfunction getNextSqrtPriceFromBRoundDown(\n  sqrtPrice: BN,\n  currLiquidity: BN,\n  amount: u64,\n  amountSpecifiedIsInput: boolean\n) {\n  let amountX64 = amount.shln(64);\n\n  let delta = BitMath.divRoundUpIf(amountX64, currLiquidity, !amountSpecifiedIsInput);\n\n  if (amountSpecifiedIsInput) {\n    sqrtPrice = sqrtPrice.add(delta);\n  } else {\n    sqrtPrice = sqrtPrice.sub(delta);\n  }\n\n  return sqrtPrice;\n}\n","import { ZERO, ONE, MathUtil, TWO, U64_MAX } from \"@orca-so/common-sdk\";\nimport { BN } from \"@project-serum/anchor\";\nimport { MathErrorCode, WhirlpoolsError } from \"../../errors/errors\";\n\nexport class BitMath {\n  static mul(n0: BN, n1: BN, limit: number): BN {\n    const result = n0.mul(n1);\n    if (this.isOverLimit(result, limit)) {\n      throw new WhirlpoolsError(\n        `Mul result higher than u${limit}`,\n        MathErrorCode.MultiplicationOverflow\n      );\n    }\n    return result;\n  }\n\n  static mulDiv(n0: BN, n1: BN, d: BN, limit: number): BN {\n    return this.mulDivRoundUpIf(n0, n1, d, false, limit);\n  }\n\n  static mulDivRoundUp(n0: BN, n1: BN, d: BN, limit: number): BN {\n    return this.mulDivRoundUpIf(n0, n1, d, true, limit);\n  }\n\n  static mulDivRoundUpIf(n0: BN, n1: BN, d: BN, roundUp: boolean, limit: number): BN {\n    if (d.eq(ZERO)) {\n      throw new WhirlpoolsError(\"mulDiv denominator is zero\", MathErrorCode.DivideByZero);\n    }\n\n    const p = this.mul(n0, n1, limit);\n    const n = p.div(d);\n\n    return roundUp && p.mod(d).gt(ZERO) ? n.add(ONE) : n;\n  }\n\n  static checked_mul_shift_right(n0: BN, n1: BN, limit: number) {\n    return this.checked_mul_shift_right_round_up_if(n0, n1, false, limit);\n  }\n\n  static checked_mul_shift_right_round_up_if(n0: BN, n1: BN, roundUp: boolean, limit: number) {\n    if (n0.eq(ZERO) || n1.eq(ZERO)) {\n      return ZERO;\n    }\n\n    const p = this.mul(n0, n1, limit);\n    if (this.isOverLimit(p, limit)) {\n      throw new WhirlpoolsError(\n        `MulShiftRight overflowed u${limit}.`,\n        MathErrorCode.MultiplicationShiftRightOverflow\n      );\n    }\n    const result = MathUtil.fromX64_BN(p);\n    const shouldRound = roundUp && result.and(U64_MAX).gt(ZERO);\n    if (shouldRound && result.eq(U64_MAX)) {\n      throw new WhirlpoolsError(\n        `MulShiftRight overflowed u${limit}.`,\n        MathErrorCode.MultiplicationOverflow\n      );\n    }\n\n    return shouldRound ? result.add(ONE) : result;\n  }\n\n  static isOverLimit(n0: BN, limit: number) {\n    const limitBN = TWO.pow(new BN(limit)).sub(ONE);\n    return n0.gt(limitBN);\n  }\n\n  static divRoundUp(n: BN, d: BN) {\n    return this.divRoundUpIf(n, d, true);\n  }\n\n  static divRoundUpIf(n: BN, d: BN, roundUp: boolean) {\n    if (d.eq(ZERO)) {\n      throw new WhirlpoolsError(\"divRoundUpIf - divide by zero\", MathErrorCode.DivideByZero);\n    }\n\n    let q = n.div(d);\n\n    return roundUp && n.mod(d).gt(ZERO) ? q.add(ONE) : q;\n  }\n}\n","import { Percentage } from \"@orca-so/common-sdk\";\nimport { Address } from \"@project-serum/anchor\";\nimport { u64 } from \"@solana/spl-token\";\nimport { AccountFetcher } from \"../..\";\nimport { SwapErrorCode, WhirlpoolsError } from \"../../errors/errors\";\nimport { Whirlpool } from \"../../whirlpool-client\";\nimport { NormalSwapQuote, swapQuoteByInputToken } from \"./swap-quote\";\n\n/**\n * A collection of estimated values from quoting a swap that collects a developer-fee.\n * @category Quotes\n * @param estimatedAmountIn - Approximate number of input token swapped in the swap\n * @param estimatedAmountOut - Approximate number of output token swapped in the swap\n * @param estimatedEndTickIndex - Approximate tick-index the Whirlpool will land on after this swap\n * @param estimatedEndSqrtPrice - Approximate sqrtPrice the Whirlpool will land on after this swap\n * @param estimatedFeeAmount - Approximate feeAmount (all fees) charged on this swap\n * @param estimatedSwapFeeAmount - Approximate feeAmount (LP + protocol fees) charged on this swap\n * @param devFeeAmount -  FeeAmount (developer fees) charged on this swap\n */\nexport type DevFeeSwapQuote = NormalSwapQuote & {\n  // NOTE: DevFeeSwaps supports input-token based swaps only as it is difficult\n  // to collect an exact % amount of dev-fees for output-token based swaps due to slippage.\n  // If there are third party requests in the future for this functionality, we can launch it\n  // but with the caveat that the % collected is only an estimate.\n  amountSpecifiedIsInput: true;\n  estimatedSwapFeeAmount: u64;\n  devFeeAmount: u64;\n};\n\n/**\n * Get an estimated swap quote using input token amount while collecting dev fees.\n *\n * @category Quotes\n * @param whirlpool - Whirlpool to perform the swap on\n * @param inputTokenMint - PublicKey for the input token mint to swap with\n * @param tokenAmount - The amount of input token to swap from\n * @param slippageTolerance - The amount of slippage to account for in this quote\n * @param programId - PublicKey for the Whirlpool ProgramId\n * @param fetcher - AccountFetcher object to fetch solana accounts\n * @param refresh - If true, fetcher would default to fetching the latest accounts\n * @param devFeePercentage - The percentage amount to send to developer wallet prior to the swap. Percentage num/dem values has to match token decimal.\n * @returns a SwapQuote object with slippage adjusted SwapInput parameters & estimates on token amounts, fee & end whirlpool states.\n */\nexport async function swapQuoteByInputTokenWithDevFees(\n  whirlpool: Whirlpool,\n  inputTokenMint: Address,\n  tokenAmount: u64,\n  slippageTolerance: Percentage,\n  programId: Address,\n  fetcher: AccountFetcher,\n  devFeePercentage: Percentage,\n  refresh: boolean\n): Promise<DevFeeSwapQuote> {\n  if (devFeePercentage.toDecimal().greaterThanOrEqualTo(1)) {\n    throw new WhirlpoolsError(\n      \"Provided devFeePercentage must be less than 100%\",\n      SwapErrorCode.InvalidDevFeePercentage\n    );\n  }\n\n  const devFeeAmount = tokenAmount\n    .mul(devFeePercentage.numerator)\n    .div(devFeePercentage.denominator);\n\n  const slippageAdjustedQuote = await swapQuoteByInputToken(\n    whirlpool,\n    inputTokenMint,\n    tokenAmount.sub(devFeeAmount),\n    slippageTolerance,\n    programId,\n    fetcher,\n    refresh\n  );\n\n  const devFeeAdjustedQuote: DevFeeSwapQuote = {\n    ...slippageAdjustedQuote,\n    amountSpecifiedIsInput: true,\n    estimatedAmountIn: slippageAdjustedQuote.estimatedAmountIn.add(devFeeAmount),\n    estimatedFeeAmount: slippageAdjustedQuote.estimatedFeeAmount.add(devFeeAmount),\n    estimatedSwapFeeAmount: slippageAdjustedQuote.estimatedFeeAmount,\n    devFeeAmount,\n  };\n\n  return devFeeAdjustedQuote;\n}\n","import { AddressUtil, TransactionBuilder } from \"@orca-so/common-sdk\";\nimport { Address } from \"@project-serum/anchor\";\nimport { Keypair, PublicKey } from \"@solana/web3.js\";\nimport invariant from \"tiny-invariant\";\nimport { WhirlpoolContext } from \"../context\";\nimport { initTickArrayIx } from \"../instructions\";\nimport { collectAllForPositionAddressesTxns } from \"../instructions/composites\";\nimport { WhirlpoolIx } from \"../ix\";\nimport { AccountFetcher } from \"../network/public\";\nimport { WhirlpoolData } from \"../types/public\";\nimport { getTickArrayDataForPosition } from \"../utils/builder/position-builder-util\";\nimport { PDAUtil, PoolUtil, PriceMath, TickUtil } from \"../utils/public\";\nimport { Position, Whirlpool, WhirlpoolClient } from \"../whirlpool-client\";\nimport { PositionImpl } from \"./position-impl\";\nimport { getRewardInfos, getTokenMintInfos, getTokenVaultAccountInfos } from \"./util\";\nimport { WhirlpoolImpl } from \"./whirlpool-impl\";\n\nexport class WhirlpoolClientImpl implements WhirlpoolClient {\n  constructor(readonly ctx: WhirlpoolContext) {}\n\n  public getContext(): WhirlpoolContext {\n    return this.ctx;\n  }\n\n  public getFetcher(): AccountFetcher {\n    return this.ctx.fetcher;\n  }\n\n  public async getPool(poolAddress: Address, refresh = false): Promise<Whirlpool> {\n    const account = await this.ctx.fetcher.getPool(poolAddress, refresh);\n    if (!account) {\n      throw new Error(`Unable to fetch Whirlpool at address at ${poolAddress}`);\n    }\n    const tokenInfos = await getTokenMintInfos(this.ctx.fetcher, account, refresh);\n    const vaultInfos = await getTokenVaultAccountInfos(this.ctx.fetcher, account, refresh);\n    const rewardInfos = await getRewardInfos(this.ctx.fetcher, account, refresh);\n    return new WhirlpoolImpl(\n      this.ctx,\n      AddressUtil.toPubKey(poolAddress),\n      tokenInfos[0],\n      tokenInfos[1],\n      vaultInfos[0],\n      vaultInfos[1],\n      rewardInfos,\n      account\n    );\n  }\n\n  public async getPools(poolAddresses: Address[], refresh = false): Promise<Whirlpool[]> {\n    const accounts = (await this.ctx.fetcher.listPools(poolAddresses, refresh)).filter(\n      (account): account is WhirlpoolData => !!account\n    );\n    if (accounts.length !== poolAddresses.length) {\n      throw new Error(`Unable to fetch all Whirlpools at addresses ${poolAddresses}`);\n    }\n    const tokenMints = new Set<string>();\n    const tokenAccounts = new Set<string>();\n    accounts.forEach((account) => {\n      tokenMints.add(account.tokenMintA.toBase58());\n      tokenMints.add(account.tokenMintB.toBase58());\n      tokenAccounts.add(account.tokenVaultA.toBase58());\n      tokenAccounts.add(account.tokenVaultB.toBase58());\n      account.rewardInfos.forEach((rewardInfo) => {\n        if (PoolUtil.isRewardInitialized(rewardInfo)) {\n          tokenAccounts.add(rewardInfo.vault.toBase58());\n        }\n      });\n    });\n    await this.ctx.fetcher.listMintInfos(Array.from(tokenMints), refresh);\n    await this.ctx.fetcher.listTokenInfos(Array.from(tokenAccounts), refresh);\n\n    const whirlpools: Whirlpool[] = [];\n    for (let i = 0; i < accounts.length; i++) {\n      const account = accounts[i];\n      const poolAddress = poolAddresses[i];\n      const tokenInfos = await getTokenMintInfos(this.ctx.fetcher, account, false);\n      const vaultInfos = await getTokenVaultAccountInfos(this.ctx.fetcher, account, false);\n      const rewardInfos = await getRewardInfos(this.ctx.fetcher, account, false);\n      whirlpools.push(\n        new WhirlpoolImpl(\n          this.ctx,\n          AddressUtil.toPubKey(poolAddress),\n          tokenInfos[0],\n          tokenInfos[1],\n          vaultInfos[0],\n          vaultInfos[1],\n          rewardInfos,\n          account\n        )\n      );\n    }\n    return whirlpools;\n  }\n\n  public async getPosition(positionAddress: Address, refresh = false): Promise<Position> {\n    const account = await this.ctx.fetcher.getPosition(positionAddress, refresh);\n    if (!account) {\n      throw new Error(`Unable to fetch Position at address at ${positionAddress}`);\n    }\n    const whirlAccount = await this.ctx.fetcher.getPool(account.whirlpool, refresh);\n    if (!whirlAccount) {\n      throw new Error(`Unable to fetch Whirlpool for Position at address at ${positionAddress}`);\n    }\n\n    const [lowerTickArray, upperTickArray] = await getTickArrayDataForPosition(\n      this.ctx,\n      account,\n      whirlAccount,\n      refresh\n    );\n    if (!lowerTickArray || !upperTickArray) {\n      throw new Error(`Unable to fetch TickArrays for Position at address at ${positionAddress}`);\n    }\n    return new PositionImpl(\n      this.ctx,\n      AddressUtil.toPubKey(positionAddress),\n      account,\n      whirlAccount,\n      lowerTickArray,\n      upperTickArray\n    );\n  }\n\n  public async getPositions(\n    positionAddresses: Address[],\n    refresh = false\n  ): Promise<Record<string, Position | null>> {\n    // TODO: Prefetch and use fetcher as a cache - Think of a cleaner way to prefetch\n    const positions = await this.ctx.fetcher.listPositions(positionAddresses, refresh);\n    const whirlpoolAddrs = positions\n      .map((position) => position?.whirlpool.toBase58())\n      .flatMap((x) => (!!x ? x : []));\n    await this.ctx.fetcher.listPools(whirlpoolAddrs, refresh);\n    const tickArrayAddresses: Set<PublicKey> = new Set();\n    await Promise.all(\n      positions.map(async (pos) => {\n        if (pos) {\n          const pool = await this.ctx.fetcher.getPool(pos.whirlpool, false);\n          if (pool) {\n            const lowerTickArrayPda = PDAUtil.getTickArrayFromTickIndex(\n              pos.tickLowerIndex,\n              pool.tickSpacing,\n              pos.whirlpool,\n              this.ctx.program.programId\n            ).publicKey;\n            const upperTickArrayPda = PDAUtil.getTickArrayFromTickIndex(\n              pos.tickUpperIndex,\n              pool.tickSpacing,\n              pos.whirlpool,\n              this.ctx.program.programId\n            ).publicKey;\n            tickArrayAddresses.add(lowerTickArrayPda);\n            tickArrayAddresses.add(upperTickArrayPda);\n          }\n        }\n      })\n    );\n    await this.ctx.fetcher.listTickArrays(Array.from(tickArrayAddresses), true);\n\n    // Use getPosition and the prefetched values to generate the Positions\n    const results = await Promise.all(\n      positionAddresses.map(async (pos) => {\n        try {\n          const position = await this.getPosition(pos, false);\n          return [pos, position];\n        } catch {\n          return [pos, null];\n        }\n      })\n    );\n    return Object.fromEntries(results);\n  }\n\n  public async createPool(\n    whirlpoolsConfig: Address,\n    tokenMintA: Address,\n    tokenMintB: Address,\n    tickSpacing: number,\n    initialTick: number,\n    funder: Address,\n    refresh = false\n  ): Promise<{ poolKey: PublicKey; tx: TransactionBuilder }> {\n    invariant(TickUtil.checkTickInBounds(initialTick), \"initialTick is out of bounds.\");\n    invariant(\n      TickUtil.isTickInitializable(initialTick, tickSpacing),\n      `initial tick ${initialTick} is not an initializable tick for tick-spacing ${tickSpacing}`\n    );\n\n    const correctTokenOrder = PoolUtil.orderMints(tokenMintA, tokenMintB).map((addr) =>\n      addr.toString()\n    );\n\n    invariant(\n      correctTokenOrder[0] === tokenMintA.toString(),\n      \"Token order needs to be flipped to match the canonical ordering (i.e. sorted on the byte repr. of the mint pubkeys)\"\n    );\n\n    whirlpoolsConfig = AddressUtil.toPubKey(whirlpoolsConfig);\n\n    const feeTierKey = PDAUtil.getFeeTier(\n      this.ctx.program.programId,\n      whirlpoolsConfig,\n      tickSpacing\n    ).publicKey;\n\n    const initSqrtPrice = PriceMath.tickIndexToSqrtPriceX64(initialTick);\n    const tokenVaultAKeypair = Keypair.generate();\n    const tokenVaultBKeypair = Keypair.generate();\n\n    const whirlpoolPda = PDAUtil.getWhirlpool(\n      this.ctx.program.programId,\n      whirlpoolsConfig,\n      new PublicKey(tokenMintA),\n      new PublicKey(tokenMintB),\n      tickSpacing\n    );\n\n    const feeTier = await this.ctx.fetcher.getFeeTier(feeTierKey, refresh);\n    invariant(!!feeTier, `Fee tier for ${tickSpacing} doesn't exist`);\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    const initPoolIx = WhirlpoolIx.initializePoolIx(this.ctx.program, {\n      initSqrtPrice,\n      whirlpoolsConfig,\n      whirlpoolPda,\n      tokenMintA: new PublicKey(tokenMintA),\n      tokenMintB: new PublicKey(tokenMintB),\n      tokenVaultAKeypair,\n      tokenVaultBKeypair,\n      feeTierKey,\n      tickSpacing,\n      funder: new PublicKey(funder),\n    });\n\n    const initialTickArrayStartTick = TickUtil.getStartTickIndex(initialTick, tickSpacing);\n    const initialTickArrayPda = PDAUtil.getTickArray(\n      this.ctx.program.programId,\n      whirlpoolPda.publicKey,\n      initialTickArrayStartTick\n    );\n\n    txBuilder.addInstruction(initPoolIx);\n    txBuilder.addInstruction(\n      initTickArrayIx(this.ctx.program, {\n        startTick: initialTickArrayStartTick,\n        tickArrayPda: initialTickArrayPda,\n        whirlpool: whirlpoolPda.publicKey,\n        funder: AddressUtil.toPubKey(funder),\n      })\n    );\n\n    return {\n      poolKey: whirlpoolPda.publicKey,\n      tx: txBuilder,\n    };\n  }\n\n  public async collectFeesAndRewardsForPositions(\n    positionAddresses: Address[],\n    refresh?: boolean | undefined\n  ): Promise<TransactionBuilder[]> {\n    const walletKey = this.ctx.wallet.publicKey;\n    return collectAllForPositionAddressesTxns(\n      this.ctx,\n      {\n        positions: positionAddresses,\n        receiver: walletKey,\n        positionAuthority: walletKey,\n        positionOwner: walletKey,\n        payer: walletKey,\n      },\n      refresh\n    );\n  }\n}\n","import BN from \"bn.js\";\nimport { AccountFetcher, PoolUtil, TokenInfo } from \"..\";\nimport {\n  WhirlpoolData,\n  WhirlpoolRewardInfo,\n  WhirlpoolRewardInfoData,\n  TokenAccountInfo,\n} from \"../types/public\";\n\nexport async function getTokenMintInfos(\n  fetcher: AccountFetcher,\n  data: WhirlpoolData,\n  refresh: boolean\n): Promise<TokenInfo[]> {\n  const mintA = data.tokenMintA;\n  const infoA = await fetcher.getMintInfo(mintA, refresh);\n  if (!infoA) {\n    throw new Error(`Unable to fetch MintInfo for mint - ${mintA}`);\n  }\n  const mintB = data.tokenMintB;\n  const infoB = await fetcher.getMintInfo(mintB, refresh);\n  if (!infoB) {\n    throw new Error(`Unable to fetch MintInfo for mint - ${mintB}`);\n  }\n  return [\n    { mint: mintA, ...infoA },\n    { mint: mintB, ...infoB },\n  ];\n}\n\nexport async function getRewardInfos(\n  fetcher: AccountFetcher,\n  data: WhirlpoolData,\n  refresh: boolean\n): Promise<WhirlpoolRewardInfo[]> {\n  const rewardInfos: WhirlpoolRewardInfo[] = [];\n  for (const rewardInfo of data.rewardInfos) {\n    rewardInfos.push(await getRewardInfo(fetcher, rewardInfo, refresh));\n  }\n  return rewardInfos;\n}\n\nasync function getRewardInfo(\n  fetcher: AccountFetcher,\n  data: WhirlpoolRewardInfoData,\n  refresh: boolean\n): Promise<WhirlpoolRewardInfo> {\n  const rewardInfo = { ...data, initialized: false, vaultAmount: new BN(0) };\n  if (PoolUtil.isRewardInitialized(data)) {\n    const vaultInfo = await fetcher.getTokenInfo(data.vault, refresh);\n    if (!vaultInfo) {\n      throw new Error(`Unable to fetch TokenAccountInfo for vault - ${data.vault}`);\n    }\n    rewardInfo.initialized = true;\n    rewardInfo.vaultAmount = vaultInfo.amount;\n  }\n  return rewardInfo;\n}\n\nexport async function getTokenVaultAccountInfos(\n  fetcher: AccountFetcher,\n  data: WhirlpoolData,\n  refresh: boolean\n): Promise<TokenAccountInfo[]> {\n  const vaultA = data.tokenVaultA;\n  const vaultInfoA = await fetcher.getTokenInfo(vaultA, refresh);\n  if (!vaultInfoA) {\n    throw new Error(`Unable to fetch TokenAccountInfo for vault - ${vaultA}`);\n  }\n  const vaultB = data.tokenVaultB;\n  const vaultInfoB = await fetcher.getTokenInfo(vaultB, refresh);\n  if (!vaultInfoB) {\n    throw new Error(`Unable to fetch TokenAccountInfo for vault - ${vaultB}`);\n  }\n  return [vaultInfoA, vaultInfoB];\n}\n","import {\n  AddressUtil,\n  deriveATA,\n  Percentage,\n  resolveOrCreateATAs,\n  TokenUtil,\n  TransactionBuilder,\n  ZERO,\n} from \"@orca-so/common-sdk\";\nimport { Address, BN, translateAddress } from \"@project-serum/anchor\";\nimport { NATIVE_MINT } from \"@solana/spl-token\";\nimport { Keypair, PublicKey } from \"@solana/web3.js\";\nimport invariant from \"tiny-invariant\";\nimport { WhirlpoolContext } from \"../context\";\nimport {\n  closePositionIx,\n  decreaseLiquidityIx,\n  DevFeeSwapInput,\n  IncreaseLiquidityInput,\n  increaseLiquidityIx,\n  initTickArrayIx,\n  openPositionIx,\n  openPositionWithMetadataIx,\n  SwapInput,\n  swapIx,\n} from \"../instructions\";\nimport {\n  collectFeesQuote,\n  collectRewardsQuote,\n  decreaseLiquidityQuoteByLiquidityWithParams,\n} from \"../quotes/public\";\nimport { TokenAccountInfo, TokenInfo, WhirlpoolData, WhirlpoolRewardInfo } from \"../types/public\";\nimport { getTickArrayDataForPosition } from \"../utils/builder/position-builder-util\";\nimport { PDAUtil, TickArrayUtil, TickUtil } from \"../utils/public\";\nimport { createWSOLAccountInstructions } from \"../utils/spl-token-utils\";\nimport {\n  getTokenMintsFromWhirlpools,\n  resolveAtaForMints,\n  TokenMintTypes,\n} from \"../utils/whirlpool-ata-utils\";\nimport { Whirlpool } from \"../whirlpool-client\";\nimport { PositionImpl } from \"./position-impl\";\nimport { getRewardInfos, getTokenVaultAccountInfos } from \"./util\";\n\nexport class WhirlpoolImpl implements Whirlpool {\n  private data: WhirlpoolData;\n  constructor(\n    readonly ctx: WhirlpoolContext,\n    readonly address: PublicKey,\n    readonly tokenAInfo: TokenInfo,\n    readonly tokenBInfo: TokenInfo,\n    private tokenVaultAInfo: TokenAccountInfo,\n    private tokenVaultBInfo: TokenAccountInfo,\n    private rewardInfos: WhirlpoolRewardInfo[],\n    data: WhirlpoolData\n  ) {\n    this.data = data;\n  }\n\n  getAddress(): PublicKey {\n    return this.address;\n  }\n\n  getData(): WhirlpoolData {\n    return this.data;\n  }\n\n  getTokenAInfo(): TokenInfo {\n    return this.tokenAInfo;\n  }\n\n  getTokenBInfo(): TokenInfo {\n    return this.tokenBInfo;\n  }\n\n  getTokenVaultAInfo(): TokenAccountInfo {\n    return this.tokenVaultAInfo;\n  }\n\n  getTokenVaultBInfo(): TokenAccountInfo {\n    return this.tokenVaultBInfo;\n  }\n\n  getRewardInfos(): WhirlpoolRewardInfo[] {\n    return this.rewardInfos;\n  }\n\n  async refreshData() {\n    await this.refresh();\n    return this.data;\n  }\n\n  async openPosition(\n    tickLower: number,\n    tickUpper: number,\n    liquidityInput: IncreaseLiquidityInput,\n    wallet?: Address,\n    funder?: Address\n  ) {\n    await this.refresh();\n    return this.getOpenPositionWithOptMetadataTx(\n      tickLower,\n      tickUpper,\n      liquidityInput,\n      !!wallet ? AddressUtil.toPubKey(wallet) : this.ctx.wallet.publicKey,\n      !!funder ? AddressUtil.toPubKey(funder) : this.ctx.wallet.publicKey\n    );\n  }\n\n  async openPositionWithMetadata(\n    tickLower: number,\n    tickUpper: number,\n    liquidityInput: IncreaseLiquidityInput,\n    sourceWallet?: Address,\n    positionWallet?: Address,\n    funder?: Address\n  ) {\n    await this.refresh();\n    return this.getOpenPositionWithOptMetadataTx(\n      tickLower,\n      tickUpper,\n      liquidityInput,\n      !!sourceWallet ? AddressUtil.toPubKey(sourceWallet) : this.ctx.wallet.publicKey,\n      !!funder ? AddressUtil.toPubKey(funder) : this.ctx.wallet.publicKey,\n      true\n    );\n  }\n\n  async initTickArrayForTicks(ticks: number[], funder?: Address, refresh = true) {\n    const initTickArrayStartPdas = await TickArrayUtil.getUninitializedArraysPDAs(\n      ticks,\n      this.ctx.program.programId,\n      this.address,\n      this.data.tickSpacing,\n      this.ctx.fetcher,\n      refresh\n    );\n\n    if (!initTickArrayStartPdas.length) {\n      return null;\n    }\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n    initTickArrayStartPdas.forEach((initTickArrayInfo) => {\n      txBuilder.addInstruction(\n        initTickArrayIx(this.ctx.program, {\n          startTick: initTickArrayInfo.startIndex,\n          tickArrayPda: initTickArrayInfo.pda,\n          whirlpool: this.address,\n          funder: !!funder ? AddressUtil.toPubKey(funder) : this.ctx.provider.wallet.publicKey,\n        })\n      );\n    });\n    return txBuilder;\n  }\n\n  async closePosition(\n    positionAddress: Address,\n    slippageTolerance: Percentage,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    payer?: Address\n  ) {\n    await this.refresh();\n    const positionWalletKey = positionWallet\n      ? AddressUtil.toPubKey(positionWallet)\n      : this.ctx.wallet.publicKey;\n    const destinationWalletKey = destinationWallet\n      ? AddressUtil.toPubKey(destinationWallet)\n      : this.ctx.wallet.publicKey;\n    const payerKey = payer ? AddressUtil.toPubKey(payer) : this.ctx.wallet.publicKey;\n    return this.getClosePositionIx(\n      AddressUtil.toPubKey(positionAddress),\n      slippageTolerance,\n      destinationWalletKey,\n      positionWalletKey,\n      payerKey\n    );\n  }\n\n  async swap(quote: SwapInput, sourceWallet?: Address) {\n    const sourceWalletKey = sourceWallet\n      ? AddressUtil.toPubKey(sourceWallet)\n      : this.ctx.wallet.publicKey;\n    return this.getSwapTx(quote, sourceWalletKey);\n  }\n\n  async swapWithDevFees(\n    quote: DevFeeSwapInput,\n    devFeeWallet: PublicKey,\n    wallet?: PublicKey | undefined,\n    payer?: PublicKey | undefined\n  ): Promise<TransactionBuilder> {\n    const sourceWalletKey = wallet ? AddressUtil.toPubKey(wallet) : this.ctx.wallet.publicKey;\n    const payerKey = payer ? AddressUtil.toPubKey(payer) : this.ctx.wallet.publicKey;\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    if (!quote.devFeeAmount.eq(ZERO)) {\n      const inputToken =\n        quote.aToB === quote.amountSpecifiedIsInput ? this.getTokenAInfo() : this.getTokenBInfo();\n\n      txBuilder.addInstruction(\n        await TokenUtil.createSendTokensToWalletInstruction(\n          this.ctx.connection,\n          sourceWalletKey,\n          devFeeWallet,\n          inputToken.mint,\n          inputToken.decimals,\n          quote.devFeeAmount,\n          () => this.ctx.fetcher.getAccountRentExempt(),\n          payerKey\n        )\n      );\n    }\n\n    return this.getSwapTx(quote, sourceWalletKey, txBuilder);\n  }\n\n  /**\n   * Construct a transaction for opening an new position with optional metadata\n   */\n  async getOpenPositionWithOptMetadataTx(\n    tickLower: number,\n    tickUpper: number,\n    liquidityInput: IncreaseLiquidityInput,\n    wallet: PublicKey,\n    funder: PublicKey,\n    withMetadata: boolean = false\n  ): Promise<{ positionMint: PublicKey; tx: TransactionBuilder }> {\n    invariant(TickUtil.checkTickInBounds(tickLower), \"tickLower is out of bounds.\");\n    invariant(TickUtil.checkTickInBounds(tickUpper), \"tickUpper is out of bounds.\");\n\n    const { liquidityAmount: liquidity, tokenMaxA, tokenMaxB } = liquidityInput;\n\n    invariant(liquidity.gt(new BN(0)), \"liquidity must be greater than zero\");\n\n    const whirlpool = await this.ctx.fetcher.getPool(this.address, false);\n    if (!whirlpool) {\n      throw new Error(`Whirlpool not found: ${translateAddress(this.address).toBase58()}`);\n    }\n\n    invariant(\n      TickUtil.isTickInitializable(tickLower, whirlpool.tickSpacing),\n      `lower tick ${tickLower} is not an initializable tick for tick-spacing ${whirlpool.tickSpacing}`\n    );\n    invariant(\n      TickUtil.isTickInitializable(tickUpper, whirlpool.tickSpacing),\n      `upper tick ${tickUpper} is not an initializable tick for tick-spacing ${whirlpool.tickSpacing}`\n    );\n\n    const positionMintKeypair = Keypair.generate();\n    const positionPda = PDAUtil.getPosition(\n      this.ctx.program.programId,\n      positionMintKeypair.publicKey\n    );\n    const metadataPda = PDAUtil.getPositionMetadata(positionMintKeypair.publicKey);\n    const positionTokenAccountAddress = await deriveATA(wallet, positionMintKeypair.publicKey);\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    const positionIx = (withMetadata ? openPositionWithMetadataIx : openPositionIx)(\n      this.ctx.program,\n      {\n        funder,\n        owner: wallet,\n        positionPda,\n        metadataPda,\n        positionMintAddress: positionMintKeypair.publicKey,\n        positionTokenAccount: positionTokenAccountAddress,\n        whirlpool: this.address,\n        tickLowerIndex: tickLower,\n        tickUpperIndex: tickUpper,\n      }\n    );\n    txBuilder.addInstruction(positionIx).addSigner(positionMintKeypair);\n\n    const [ataA, ataB] = await resolveOrCreateATAs(\n      this.ctx.connection,\n      wallet,\n      [\n        { tokenMint: whirlpool.tokenMintA, wrappedSolAmountIn: tokenMaxA },\n        { tokenMint: whirlpool.tokenMintB, wrappedSolAmountIn: tokenMaxB },\n      ],\n      () => this.ctx.fetcher.getAccountRentExempt(),\n      funder\n    );\n    const { address: tokenOwnerAccountA, ...tokenOwnerAccountAIx } = ataA;\n    const { address: tokenOwnerAccountB, ...tokenOwnerAccountBIx } = ataB;\n\n    txBuilder.addInstruction(tokenOwnerAccountAIx);\n    txBuilder.addInstruction(tokenOwnerAccountBIx);\n\n    const tickArrayLowerPda = PDAUtil.getTickArrayFromTickIndex(\n      tickLower,\n      this.data.tickSpacing,\n      this.address,\n      this.ctx.program.programId\n    );\n    const tickArrayUpperPda = PDAUtil.getTickArrayFromTickIndex(\n      tickUpper,\n      this.data.tickSpacing,\n      this.address,\n      this.ctx.program.programId\n    );\n\n    const liquidityIx = increaseLiquidityIx(this.ctx.program, {\n      liquidityAmount: liquidity,\n      tokenMaxA,\n      tokenMaxB,\n      whirlpool: this.address,\n      positionAuthority: wallet,\n      position: positionPda.publicKey,\n      positionTokenAccount: positionTokenAccountAddress,\n      tokenOwnerAccountA,\n      tokenOwnerAccountB,\n      tokenVaultA: whirlpool.tokenVaultA,\n      tokenVaultB: whirlpool.tokenVaultB,\n      tickArrayLower: tickArrayLowerPda.publicKey,\n      tickArrayUpper: tickArrayUpperPda.publicKey,\n    });\n    txBuilder.addInstruction(liquidityIx);\n\n    return {\n      positionMint: positionMintKeypair.publicKey,\n      tx: txBuilder,\n    };\n  }\n\n  async getClosePositionIx(\n    positionAddress: PublicKey,\n    slippageTolerance: Percentage,\n    destinationWallet: PublicKey,\n    positionWallet: PublicKey,\n    payerKey: PublicKey\n  ): Promise<TransactionBuilder[]> {\n    const positionData = await this.ctx.fetcher.getPosition(positionAddress, true);\n    if (!positionData) {\n      throw new Error(`Position not found: ${positionAddress.toBase58()}`);\n    }\n\n    const whirlpool = this.data;\n\n    invariant(\n      positionData.whirlpool.equals(this.address),\n      `Position ${positionAddress.toBase58()} is not a position for Whirlpool ${this.address.toBase58()}`\n    );\n\n    const positionTokenAccount = await deriveATA(positionWallet, positionData.positionMint);\n\n    const tokenAccountsTxBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    const accountExemption = await this.ctx.fetcher.getAccountRentExempt();\n\n    const txBuilder = new TransactionBuilder(\n      this.ctx.provider.connection,\n      this.ctx.provider.wallet\n    );\n\n    const tickArrayLower = PDAUtil.getTickArrayFromTickIndex(\n      positionData.tickLowerIndex,\n      whirlpool.tickSpacing,\n      positionData.whirlpool,\n      this.ctx.program.programId\n    ).publicKey;\n\n    const tickArrayUpper = PDAUtil.getTickArrayFromTickIndex(\n      positionData.tickUpperIndex,\n      whirlpool.tickSpacing,\n      positionData.whirlpool,\n      this.ctx.program.programId\n    ).publicKey;\n\n    const [tickArrayLowerData, tickArrayUpperData] = await getTickArrayDataForPosition(\n      this.ctx,\n      positionData,\n      whirlpool,\n      true\n    );\n\n    invariant(\n      !!tickArrayLowerData,\n      `Tick array ${tickArrayLower} expected to be initialized for whirlpool ${this.address}`\n    );\n\n    invariant(\n      !!tickArrayUpperData,\n      `Tick array ${tickArrayUpper} expected to be initialized for whirlpool ${this.address}`\n    );\n\n    const position = new PositionImpl(\n      this.ctx,\n      positionAddress,\n      positionData,\n      whirlpool,\n      tickArrayLowerData,\n      tickArrayUpperData\n    );\n\n    const tickLower = position.getLowerTickData();\n    const tickUpper = position.getUpperTickData();\n\n    const feesQuote = collectFeesQuote({\n      position: positionData,\n      whirlpool,\n      tickLower,\n      tickUpper,\n    });\n\n    const rewardsQuote = collectRewardsQuote({\n      position: positionData,\n      whirlpool,\n      tickLower,\n      tickUpper,\n    });\n\n    const shouldCollectFees = feesQuote.feeOwedA.gtn(0) || feesQuote.feeOwedB.gtn(0);\n    invariant(\n      this.data.rewardInfos.length === rewardsQuote.length,\n      \"Rewards quote does not match reward infos length\"\n    );\n\n    const shouldDecreaseLiquidity = positionData.liquidity.gtn(0);\n\n    const rewardsToCollect = this.data.rewardInfos\n      .filter((_, i) => (rewardsQuote[i] ?? ZERO).gtn(0))\n      .map((info) => info.mint);\n\n    const shouldCollectRewards = rewardsToCollect.length > 0;\n\n    let mintType = TokenMintTypes.ALL;\n    if ((shouldDecreaseLiquidity || shouldCollectFees) && !shouldCollectRewards) {\n      mintType = TokenMintTypes.POOL_ONLY;\n    } else if (!(shouldDecreaseLiquidity || shouldCollectFees) && shouldCollectRewards) {\n      mintType = TokenMintTypes.REWARD_ONLY;\n    }\n\n    const affiliatedMints = getTokenMintsFromWhirlpools([whirlpool], mintType);\n    const { ataTokenAddresses: walletTokenAccountsByMint, resolveAtaIxs } =\n      await resolveAtaForMints(this.ctx, {\n        mints: affiliatedMints.mintMap,\n        accountExemption,\n        receiver: destinationWallet,\n        payer: payerKey,\n      });\n\n    tokenAccountsTxBuilder.addInstructions(resolveAtaIxs);\n\n    // Handle native mint\n    if (affiliatedMints.hasNativeMint) {\n      let { address: wSOLAta, ...resolveWSolIx } = createWSOLAccountInstructions(\n        destinationWallet,\n        ZERO,\n        accountExemption,\n        payerKey,\n        destinationWallet\n      );\n      walletTokenAccountsByMint[NATIVE_MINT.toBase58()] = wSOLAta;\n      txBuilder.addInstruction(resolveWSolIx);\n    }\n\n    if (shouldDecreaseLiquidity) {\n      /* Remove all liquidity remaining in the position */\n      const tokenOwnerAccountA = walletTokenAccountsByMint[whirlpool.tokenMintA.toBase58()];\n      const tokenOwnerAccountB = walletTokenAccountsByMint[whirlpool.tokenMintB.toBase58()];\n\n      const decreaseLiqQuote = decreaseLiquidityQuoteByLiquidityWithParams({\n        liquidity: positionData.liquidity,\n        slippageTolerance,\n        sqrtPrice: whirlpool.sqrtPrice,\n        tickCurrentIndex: whirlpool.tickCurrentIndex,\n        tickLowerIndex: positionData.tickLowerIndex,\n        tickUpperIndex: positionData.tickUpperIndex,\n      });\n\n      const liquidityIx = decreaseLiquidityIx(this.ctx.program, {\n        liquidityAmount: decreaseLiqQuote.liquidityAmount,\n        tokenMinA: decreaseLiqQuote.tokenMinA,\n        tokenMinB: decreaseLiqQuote.tokenMinB,\n        whirlpool: positionData.whirlpool,\n        positionAuthority: positionWallet,\n        position: positionAddress,\n        positionTokenAccount,\n        tokenOwnerAccountA,\n        tokenOwnerAccountB,\n        tokenVaultA: whirlpool.tokenVaultA,\n        tokenVaultB: whirlpool.tokenVaultB,\n        tickArrayLower,\n        tickArrayUpper,\n      });\n\n      txBuilder.addInstruction(liquidityIx);\n    }\n\n    if (shouldCollectFees) {\n      const collectFeexTx = await position.collectFees(\n        false,\n        walletTokenAccountsByMint,\n        destinationWallet,\n        positionWallet,\n        payerKey,\n        true\n      );\n\n      txBuilder.addInstruction(collectFeexTx.compressIx(false));\n    }\n\n    if (shouldCollectRewards) {\n      const collectRewardsTx = await position.collectRewards(\n        rewardsToCollect,\n        false,\n        walletTokenAccountsByMint,\n        destinationWallet,\n        positionWallet,\n        payerKey\n      );\n\n      txBuilder.addInstruction(collectRewardsTx.compressIx(false));\n    }\n\n    /* Close position */\n    const positionIx = closePositionIx(this.ctx.program, {\n      positionAuthority: positionWallet,\n      receiver: destinationWallet,\n      positionTokenAccount,\n      position: positionAddress,\n      positionMint: positionData.positionMint,\n    });\n\n    txBuilder.addInstruction(positionIx);\n\n    const txBuilders: TransactionBuilder[] = [];\n\n    if (!tokenAccountsTxBuilder.isEmpty()) {\n      txBuilders.push(tokenAccountsTxBuilder);\n    }\n\n    txBuilders.push(txBuilder);\n\n    return txBuilders;\n  }\n\n  private async getSwapTx(\n    input: SwapInput,\n    wallet: PublicKey,\n    initTxBuilder?: TransactionBuilder\n  ): Promise<TransactionBuilder> {\n    invariant(input.amount.gt(ZERO), \"swap amount must be more than zero.\");\n\n    // Check if all the tick arrays have been initialized.\n    const tickArrayAddresses = [input.tickArray0, input.tickArray1, input.tickArray2];\n    const tickArrays = await this.ctx.fetcher.listTickArrays(tickArrayAddresses, true);\n    const uninitializedIndices = TickArrayUtil.getUninitializedArrays(tickArrays);\n    if (uninitializedIndices.length > 0) {\n      const uninitializedArrays = uninitializedIndices\n        .map((index) => tickArrayAddresses[index].toBase58())\n        .join(\", \");\n      throw new Error(`TickArray addresses - [${uninitializedArrays}] need to be initialized.`);\n    }\n\n    const { amount, aToB } = input;\n    const whirlpool = this.data;\n    const txBuilder =\n      initTxBuilder ??\n      new TransactionBuilder(this.ctx.provider.connection, this.ctx.provider.wallet);\n\n    const [ataA, ataB] = await resolveOrCreateATAs(\n      this.ctx.connection,\n      wallet,\n      [\n        { tokenMint: whirlpool.tokenMintA, wrappedSolAmountIn: aToB ? amount : ZERO },\n        { tokenMint: whirlpool.tokenMintB, wrappedSolAmountIn: !aToB ? amount : ZERO },\n      ],\n      () => this.ctx.fetcher.getAccountRentExempt()\n    );\n\n    const { address: tokenOwnerAccountA, ...tokenOwnerAccountAIx } = ataA;\n    const { address: tokenOwnerAccountB, ...tokenOwnerAccountBIx } = ataB;\n\n    txBuilder.addInstruction(tokenOwnerAccountAIx);\n    txBuilder.addInstruction(tokenOwnerAccountBIx);\n\n    const oraclePda = PDAUtil.getOracle(this.ctx.program.programId, this.address);\n\n    txBuilder.addInstruction(\n      swapIx(this.ctx.program, {\n        ...input,\n        whirlpool: this.address,\n        tokenAuthority: wallet,\n        tokenOwnerAccountA,\n        tokenVaultA: whirlpool.tokenVaultA,\n        tokenOwnerAccountB,\n        tokenVaultB: whirlpool.tokenVaultB,\n        oracle: oraclePda.publicKey,\n      })\n    );\n\n    return txBuilder;\n  }\n\n  private async refresh() {\n    const account = await this.ctx.fetcher.getPool(this.address, true);\n    if (!!account) {\n      const rewardInfos = await getRewardInfos(this.ctx.fetcher, account, true);\n      const [tokenVaultAInfo, tokenVaultBInfo] = await getTokenVaultAccountInfos(\n        this.ctx.fetcher,\n        account,\n        true\n      );\n      this.data = account;\n      this.tokenVaultAInfo = tokenVaultAInfo;\n      this.tokenVaultBInfo = tokenVaultBInfo;\n      this.rewardInfos = rewardInfos;\n    }\n  }\n}\n","import { Percentage, TransactionBuilder } from \"@orca-so/common-sdk\";\nimport { Address } from \"@project-serum/anchor\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { WhirlpoolContext } from \"./context\";\nimport { WhirlpoolClientImpl } from \"./impl/whirlpool-client-impl\";\nimport { DevFeeSwapInput, SwapInput } from \"./instructions\";\nimport { AccountFetcher } from \"./network/public\";\nimport {\n  DecreaseLiquidityInput,\n  IncreaseLiquidityInput,\n  PositionData,\n  TickData,\n  WhirlpoolData,\n} from \"./types/public\";\nimport { TokenAccountInfo, TokenInfo, WhirlpoolRewardInfo } from \"./types/public/client-types\";\n\n/**\n * Helper class to help interact with Whirlpool Accounts with a simpler interface.\n *\n * @category Core\n */\nexport interface WhirlpoolClient {\n  /**\n   * Get this client's WhirlpoolContext object\n   * @return a WhirlpoolContext object\n   */\n  getContext: () => WhirlpoolContext;\n\n  /**\n   * Get an AccountFetcher to fetch Whirlpool accounts\n   * @return an AccountFetcher instance\n   */\n  getFetcher: () => AccountFetcher;\n\n  /**\n   * Get a Whirlpool object to interact with the Whirlpool account at the given address.\n   * @param poolAddress the address of the Whirlpool account\n   * @param refresh true to always request newest data from chain with this request\n   * @return a Whirlpool object to interact with\n   */\n  getPool: (poolAddress: Address, refresh?: boolean) => Promise<Whirlpool>;\n\n  /**\n   * Get a list of Whirlpool objects matching the provided list of addresses.\n   * @param poolAddresses the addresses of the Whirlpool accounts\n   * @param refresh true to always request newest data from chain with this request\n   * @return a list of Whirlpool objects to interact with\n   */\n  getPools: (poolAddresses: Address[], refresh?: boolean) => Promise<Whirlpool[]>;\n\n  /**\n   * Get a Position object to interact with the Position account at the given address.\n   * @param positionAddress the address of the Position account\n   * @param refresh true to always request newest data from chain with this request\n   * @return a Position object to interact with.\n   * @throws error when address does not return a Position account.\n   */\n  getPosition: (positionAddress: Address, refresh?: boolean) => Promise<Position>;\n\n  /**\n   * Get a list of Position objects to interact with the Position account at the given addresses.\n   * @param positionAddress the addresses of the Position accounts\n   * @param refresh true to always request newest data from chain with this request\n   * @return a Record object between account address and Position. If an address is not a Position account, it will be null.\n   */\n  getPositions: (\n    positionAddresses: Address[],\n    refresh?: boolean\n  ) => Promise<Record<string, Position | null>>;\n\n  /**\n   * Collect all fees and rewards from a list of positions.\n   * @experimental\n   * @param positionAddress the addresses of the Position accounts to collect fee & rewards from.\n   * @param refresh true to always request newest data from chain with this request\n   * @returns A set of transaction-builders to resolve ATA for affliated tokens, collect fee & rewards for all positions.\n   *          The first transaction should always be processed as it contains all the resolve ATA instructions to receive tokens.\n   */\n  collectFeesAndRewardsForPositions: (\n    positionAddresses: Address[],\n    refresh?: boolean\n  ) => Promise<TransactionBuilder[]>;\n\n  /**\n   * Create a Whirlpool account for a group of token A, token B and tick spacing\n   * @param whirlpoolConfig the address of the whirlpool config\n   * @param tokenMintA the address of the token A\n   * @param tokenMintB the address of the token B\n   * @param tickSpacing the space between two ticks in the tick array\n   * @param initialTick the initial tick that the pool is set to (derived from initial price)\n   * @param funder the account to debit SOL from to fund the creation of the account(s)\n   * @return `poolKey`: The public key of the newly created whirlpool account. `tx`: The transaction containing instructions for the on-chain operations.\n   * @throws error when the tokens are not in the canonical byte-based ordering. To resolve this, invert the token order and the initialTick (see `TickUtil.invertTick()`, `PriceMath.invertSqrtPriceX64()`, or `PriceMath.invertPrice()`).\n   */\n  createPool: (\n    whirlpoolsConfig: Address,\n    tokenMintA: Address,\n    tokenMintB: Address,\n    tickSpacing: number,\n    initialTick: number,\n    funder: Address\n  ) => Promise<{ poolKey: PublicKey; tx: TransactionBuilder }>;\n}\n\n/**\n * Construct a WhirlpoolClient instance to help interact with Whirlpools accounts with.\n *\n * @category WhirlpoolClient\n * @param ctx - WhirlpoolContext object\n * @returns a WhirlpoolClient instance to help with interacting with Whirlpools accounts.\n */\nexport function buildWhirlpoolClient(ctx: WhirlpoolContext): WhirlpoolClient {\n  return new WhirlpoolClientImpl(ctx);\n}\n\n/**\n * Helper class to interact with a Whirlpool account and build complex transactions.\n * @category WhirlpoolClient\n */\nexport interface Whirlpool {\n  /**\n   * Return the address for this Whirlpool instance.\n   * @return the PublicKey for this Whirlpool instance.\n   */\n  getAddress: () => PublicKey;\n\n  /**\n   * Return the most recently fetched Whirlpool account data.\n   * @return most recently fetched WhirlpoolData for this address.\n   */\n  getData: () => WhirlpoolData;\n\n  /**\n   * Fetch and return the most recently fetched Whirlpool account data.\n   * @return the most up to date WhirlpoolData for this address.\n   */\n  refreshData: () => Promise<WhirlpoolData>;\n\n  /**\n   * Get the TokenInfo for token A of this pool.\n   * @return TokenInfo for token A\n   */\n  getTokenAInfo: () => TokenInfo;\n\n  /**\n   * Get the TokenInfo for token B of this pool.\n   * @return TokenInfo for token B\n   */\n  getTokenBInfo: () => TokenInfo;\n\n  /**\n   * Get the TokenAccountInfo for token vault A of this pool.\n   * @return TokenAccountInfo for token vault A\n   */\n  getTokenVaultAInfo: () => TokenAccountInfo;\n\n  /**\n   * Get the TokenAccountInfo for token vault B of this pool.\n   * @return TokenAccountInfo for token vault B\n   */\n  getTokenVaultBInfo: () => TokenAccountInfo;\n\n  /**\n   * Get the WhirlpoolRewardInfos for this pool.\n   * @return Array of 3 WhirlpoolRewardInfos. However, not all of them may be initialized. Use the initialized field on WhirlpoolRewardInfo to check if the reward is active.\n   */\n  getRewardInfos: () => WhirlpoolRewardInfo[];\n\n  /**\n   * Initialize a set of tick-arrays that encompasses the provided ticks.\n   *\n   * If `funder` is provided, the funder wallet has to sign this transaction.\n   *\n   * @param ticks - A group of ticks that define the desired tick-arrays to initialize. If the tick's array has been initialized, it will be ignored.\n   * @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.\n   * @param refresh - whether this operation will fetch for the latest accounts if a cache version is available.\n   * @return a transaction that will initialize the defined tick-arrays if executed. Return null if all of the tick's arrays are initialized.\n   */\n  initTickArrayForTicks: (\n    ticks: number[],\n    funder?: Address,\n    refresh?: boolean\n  ) => Promise<TransactionBuilder | null>;\n\n  /**\n   * Open and fund a position on this Whirlpool.\n   *\n   * User has to ensure the TickArray for tickLower and tickUpper has been initialized prior to calling this function.\n   *\n   * If `wallet` or `funder` is provided, those wallets have to sign this transaction.\n   *\n   * @param tickLower - the tick index for the lower bound of this position\n   * @param tickUpper - the tick index for the upper bound of this position\n   * @param liquidityInput - an InputLiquidityInput type to define the desired liquidity amount to deposit\n   * @param wallet - the wallet to withdraw tokens to deposit into the position and house the position token. If null, the WhirlpoolContext wallet is used.\n   * @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.\n   * @return `positionMint` - the position to be created. `tx` - The transaction containing the instructions to perform the operation on chain.\n   */\n  openPosition: (\n    tickLower: number,\n    tickUpper: number,\n    liquidityInput: IncreaseLiquidityInput,\n    wallet?: Address,\n    funder?: Address\n  ) => Promise<{ positionMint: PublicKey; tx: TransactionBuilder }>;\n\n  /**\n   * Open and fund a position with meta-data on this Whirlpool.\n   *\n   * User has to ensure the TickArray for tickLower and tickUpper has been initialized prior to calling this function.\n   *\n   * If `wallet` or `funder` is provided, the wallet owners have to sign this transaction.\n   *\n   * @param tickLower - the tick index for the lower bound of this position\n   * @param tickUpper - the tick index for the upper bound of this position\n   * @param liquidityInput - input that defines the desired liquidity amount and maximum tokens willing to be to deposited.\n   * @param wallet - the wallet to withdraw tokens to deposit into the position and house the position token. If null, the WhirlpoolContext wallet is used.\n   * @param funder - the wallet that will fund the cost needed to initialize the position. If null, the WhirlpoolContext wallet is used.\n   * @return `positionMint` - the position to be created. `tx` - The transaction containing the instructions to perform the operation on chain.\n   */\n  openPositionWithMetadata: (\n    tickLower: number,\n    tickUpper: number,\n    liquidityInput: IncreaseLiquidityInput,\n    wallet?: Address,\n    funder?: Address\n  ) => Promise<{ positionMint: PublicKey; tx: TransactionBuilder }>;\n\n  /**\n   * Withdraw all tokens from a position, close the account and burn the position token.\n   *\n   * Users have to collect all fees and rewards from this position prior to closing the account.\n   *\n   * If `positionWallet`, `payer` is provided, the wallet owner has to sign this transaction.\n   *\n   * @param positionAddress - The address of the position account.\n   * @param slippageTolerance - The amount of slippage the caller is willing to accept when withdrawing liquidity.\n   * @param destinationWallet - The wallet that the tokens withdrawn and rent lamports will be sent to. If null, the WhirlpoolContext wallet is used.\n   * @param positionWallet - The wallet that houses the position token that corresponds to this position address. If null, the WhirlpoolContext wallet is used.\n   * @param payer - the wallet that will fund the cost needed to initialize the token ATA accounts. If null, the WhirlpoolContext wallet is used.\n   */\n  closePosition: (\n    positionAddress: Address,\n    slippageTolerance: Percentage,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    payer?: Address\n  ) => Promise<TransactionBuilder[]>;\n\n  /**\n   * Perform a swap between tokenA and tokenB on this pool.\n   *\n   * @param input - A quote on the desired tokenIn and tokenOut for this swap. Use @link {swapQuote} to generate this object.\n   * @param wallet - The wallet that tokens will be withdrawn and deposit into. If null, the WhirlpoolContext wallet is used.\n   * @return a transaction that will perform the swap once executed.\n   */\n  swap: (input: SwapInput, wallet?: PublicKey) => Promise<TransactionBuilder>;\n\n  /**\n   * Collect a developer fee and perform a swap between tokenA and tokenB on this pool.\n   *\n   * @param input - A quote on the desired tokenIn and tokenOut for this swap. Use @link {swapQuote} to generate this object.\n   * @param devFeeWallet - The wallet that developer fees will be deposited into.\n   * @param wallet - The wallet that swap tokens will be withdrawn and deposit into. If null, the WhirlpoolContext wallet is used.\n   * @param payer - The wallet that will fund the cost needed to initialize the dev wallet token ATA accounts. If null, the WhirlpoolContext wallet is used.\n   * @return a transaction that will perform the swap once executed.\n   */\n  swapWithDevFees: (\n    input: DevFeeSwapInput,\n    devFeeWallet: PublicKey,\n    wallet?: PublicKey,\n    payer?: PublicKey\n  ) => Promise<TransactionBuilder>;\n}\n\n/**\n * Helper class to interact with a Position account and build complex transactions.\n * @category WhirlpoolClient\n */\nexport interface Position {\n  /**\n   * Return the address for this Whirlpool instance.\n   * @return the PublicKey for this Whirlpool instance.\n   */\n  getAddress: () => PublicKey;\n\n  /**\n   * Return the most recently fetched Position account data.\n   * @return most recently fetched PositionData for this address.\n   */\n  getData: () => PositionData;\n\n  /**\n   * Return the most recently fetched Whirlpool account data for this position.\n   * @return most recently fetched WhirlpoolData for this position.\n   */\n  getWhirlpoolData: () => WhirlpoolData;\n\n  /**\n   * Return the most recently fetched TickData account data for this position's lower tick.\n   * @return most recently fetched TickData for this position's lower tick.\n   */\n  getLowerTickData: () => TickData;\n\n  /**\n   * Return the most recently fetched TickData account data for this position's upper tick.\n   * @return most recently fetched TickData for this position's upper tick.\n   */\n  getUpperTickData: () => TickData;\n\n  /**\n   * Fetch and return the most recently fetched Position account data.\n   * @return the most up to date PositionData for this address.\n   */\n  refreshData: () => Promise<PositionData>;\n\n  /**\n   * Deposit additional tokens into this postiion.\n   * The wallet must contain the position token and the necessary token A & B to complete the deposit.\n   * If  `positionWallet` and `wallet` is provided, the wallet owners have to sign this transaction.\n   *\n   * @param liquidityInput - input that defines the desired liquidity amount and maximum tokens willing to be to deposited.\n   * @param resolveATA - if true, add instructions to create associated token accounts for tokenA,B for the destinationWallet if necessary. (RPC call required)\n   * @param wallet - to withdraw tokens to deposit into the position. If null, the WhirlpoolContext wallet is used.\n   * @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.\n   * @param ataPayer - wallet that will fund the creation of the new associated token accounts\n   * @return the transaction that will deposit the tokens into the position when executed.\n   */\n  increaseLiquidity: (\n    liquidityInput: IncreaseLiquidityInput,\n    resolveATA?: boolean,\n    wallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address\n  ) => Promise<TransactionBuilder>;\n\n  /**\n   * Withdraw liquidity from this position.\n   *\n   * If `positionWallet` is provided, the wallet owners have to sign this transaction.\n   *\n   * @param liquidityInput - input that defines the desired liquidity amount and minimum tokens willing to be to withdrawn from the position.\n   * @param resolveATA -  if true, add instructions to create associated token accounts for tokenA,B for the destinationWallet if necessary. (RPC call required)\n   * @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.\n   * @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.\n   * @param ataPayer - wallet that will fund the creation of the new associated token accounts\n   * @return the transaction that will deposit the tokens into the position when executed.\n   */\n  decreaseLiquidity: (\n    liquidityInput: DecreaseLiquidityInput,\n    resolveATA?: boolean,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address\n  ) => Promise<TransactionBuilder>;\n\n  /**\n   * Collect fees from this position\n   *\n   * If `positionWallet` is provided, the wallet owners have to sign this transaction.\n   *\n   * @param updateFeesAndRewards -  if true, add instructions to refresh the accumulated fees and rewards data (default to true unless you know that the collect fees quote and on-chain data match for the \"feeOwedA\" and \"feeOwedB\" fields in the Position account)\n   * @param ownerTokenAccountMap - A record that maps a given mint to the owner's token account for that mint (if an entry doesn't exist, it will be automatically resolved)\n   * @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.\n   * @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.\n   * @param ataPayer - wallet that will fund the creation of the new associated token accounts\n   * @param refresh - set to true to bypass cached on-chain data\n   * @return the transaction that will collect fees from the position\n   */\n  collectFees: (\n    updateFeesAndRewards?: boolean,\n    ownerTokenAccountMap?: Partial<Record<string, Address>>,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address,\n    refresh?: boolean\n  ) => Promise<TransactionBuilder>;\n\n  /**\n   * Collect rewards from this position\n   *\n   * If `positionWallet` is provided, the wallet owners have to sign this transaction.\n   *\n   * @param rewardsToCollect - reward mints to collect (omitting this parameter means all rewards will be collected)\n   * @param updateFeesAndRewards -  if true, add instructions to refresh the accumulated fees and rewards data (default to true unless you know that the collect fees quote and on-chain data match for the \"feeOwedA\" and \"feeOwedB\" fields in the Position account)\n   * @param ownerTokenAccountMap - A record that maps a given mint to the owner's token account for that mint (if an entry doesn't exist, it will be automatically resolved)\n   * @param destinationWallet - the wallet to deposit tokens into when withdrawing from the position. If null, the WhirlpoolContext wallet is used.\n   * @param positionWallet - the wallet to that houses the position token. If null, the WhirlpoolContext wallet is used.\n   * @param ataPayer - wallet that will fund the creation of the new associated token accounts\n   * @param refresh - set to true to bypass cached on-chain data\n   * @return the transaction that will collect fees from the position\n   */\n  collectRewards: (\n    rewardsToCollect?: Address[],\n    updateFeesAndRewards?: boolean,\n    ownerTokenAccountMap?: Partial<Record<string, Address>>,\n    destinationWallet?: Address,\n    positionWallet?: Address,\n    ataPayer?: Address,\n    refresh?: boolean\n  ) => Promise<TransactionBuilder>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,OAAOA,cAAa;;;ACApB,SAAS,gBAAqB,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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QAAQJ,aAAY,SAAS,MAAM;AAAA,MACrC,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,MACL,SAAS,aAAa;AAAA,MACtB,IAAI;AAAA,IACN;AAAA,EACF;AAAA,EAEA,MAAa,kCACX,mBACA,SAC+B;AAC/B,UAAM,YAAY,KAAK,IAAI,OAAO;AAClC,WAAO;AAAA,MACL,KAAK;AAAA,MACL;AAAA,QACE,WAAW;AAAA,QACX,UAAU;AAAA,QACV,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,OAAO;AAAA,MACT;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;;;AGvKO,SAAS,qBAAqB,KAAwC;AAC3E,SAAO,IAAI,oBAAoB,GAAG;AACpC;;;AhEtGA,SAAS,cAAAM,mBAAkB;AAM3BC,SAAQ,IAAI,EAAE,WAAW,IAAI,UAAU,IAAI,UAAU,KAAK,UAAU,EAAE,CAAC;","names":["Decimal","invariant","AccountLayout","u64","PublicKey","AccountName","TOKEN_PROGRAM_ID","TOKEN_PROGRAM_ID","TOKEN_PROGRAM_ID","TokenUtil","TransactionBuilder","ZERO","createWSOLAccountInstructions","NATIVE_MINT","PublicKey","BN","BN","BN","BN","AddressUtil","MathUtil","BN","PublicKey","Decimal","SwapDirection","TokenType","PublicKey","AddressUtil","Decimal","MathUtil","BN","BN","BN","TOKEN_PROGRAM_ID","PublicKey","TOKEN_PROGRAM_ID","PublicKey","TransactionBuilder","TokenUtil","NATIVE_MINT","PublicKey","createWSOLAccountInstructions","ZERO","TOKEN_PROGRAM_ID","TOKEN_PROGRAM_ID","SystemProgram","SystemProgram","SystemProgram","TOKEN_PROGRAM_ID","TOKEN_PROGRAM_ID","SystemProgram","anchor","PublicKey","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","anchor","SystemProgram","PublicKey","TOKEN_PROGRAM_ID","BorshAccountsCoder","TokenUtil","TokenUtil","PublicKey","u64","BorshAccountsCoder","AddressUtil","AccountLayout","accounts","invariant","WhirlpoolContext","AddressUtil","resolveOrCreateATAs","TransactionBuilder","ZERO","NATIVE_MINT","invariant","AddressUtil","TransactionBuilder","resolveOrCreateATAs","ZERO","NATIVE_MINT","invariant","AddressUtil","ZERO","invariant","MathUtil","MathUtil","MathUtil","MathUtil","AddressUtil","invariant","ZERO","ZERO","invariant","invariant","quotePositionBelowRange","quotePositionInRange","quotePositionAboveRange","ZERO","MathUtil","MathUtil","BN","invariant","BN","invariant","MathUtil","AddressUtil","invariant","ZERO","BN","ZERO","u64","BN","BN","U64_MAX","ZERO","BN","ZERO","MathUtil","U64_MAX","BN","ZERO","MathUtil","U64_MAX","BN","ZERO","BN","U64_MAX","ZERO","BN","BN","ZERO","u64","BN","BN","ZERO","AddressUtil","invariant","AddressUtil","TransactionBuilder","Keypair","PublicKey","invariant","BN","BN","AddressUtil","deriveATA","resolveOrCreateATAs","TokenUtil","TransactionBuilder","ZERO","BN","NATIVE_MINT","Keypair","invariant","AddressUtil","TransactionBuilder","ZERO","TokenUtil","invariant","BN","Keypair","deriveATA","resolveOrCreateATAs","NATIVE_MINT","AddressUtil","accounts","invariant","Keypair","PublicKey","TransactionBuilder","Percentage","Decimal"]}