{"version":3,"sources":["../../../src/raydium/cpmm/cpmm.ts","../../../src/common/bignumber.ts","../../../src/module/amount.ts","../../../src/common/logger.ts","../../../src/common/accountInfo.ts","../../../src/common/constant.ts","../../../src/raydium/token/constant.ts","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/module/currency.ts","../../../src/module/formatter.ts","../../../src/module/fraction.ts","../../../src/module/percent.ts","../../../src/module/price.ts","../../../src/common/lodash.ts","../../../src/common/pda.ts","../../../src/common/txTool/txUtils.ts","../../../src/common/txTool/txType.ts","../../../src/common/programId.ts","../../../src/common/transfer.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/txTool/txTool.ts","../../../src/common/utility.ts","../../../src/common/fee.ts","../../../src/raydium/cpmm/curve/calculator.ts","../../../src/raydium/cpmm/curve/constantProduct.ts","../../../src/raydium/cpmm/curve/fee.ts","../../../src/raydium/moduleBase.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/raydium/token/layout.ts","../../../src/raydium/token/utils.ts","../../../src/raydium/cpmm/instruction.ts","../../../src/raydium/cpmm/pda.ts","../../../src/raydium/clmm/clmm.ts","../../../src/raydium/clmm/instrument.ts","../../../src/raydium/clmm/utils/tick.ts","../../../src/raydium/clmm/utils/constants.ts","../../../src/raydium/clmm/utils/math.ts","../../../src/raydium/clmm/utils/pda.ts","../../../src/raydium/clmm/utils/pool.ts","../../../src/raydium/clmm/utils/position.ts","../../../src/raydium/clmm/utils/tickarrayBitmap.ts","../../../src/raydium/clmm/layout.ts","../../../src/raydium/cpmm/layout.ts"],"sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport { ApiV3PoolInfoStandardItemCpmm, CpmmKeys } from \"../../api/type\";\nimport { AccountLayout, NATIVE_MINT, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { BN_ZERO } from \"@/common/bignumber\";\nimport { getATAAddress } from \"@/common/pda\";\nimport { WSOLMint } from \"@/common/pubKey\";\nimport { MakeTxData } from \"@/common/txTool/txTool\";\nimport { InstructionType, TxVersion } from \"@/common/txTool/txType\";\nimport { Percent } from \"../../module\";\nimport { CurveCalculator } from \"./curve/calculator\";\n\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport {\n  fetchMultipleMintInfos,\n  getMultipleAccountsInfoWithCustomFlags,\n  getTransferAmountFeeV2,\n  LOCK_CPMM_AUTH,\n  LOCK_CPMM_PROGRAM,\n} from \"@/common\";\nimport { GetTransferAmountFee, ReturnTypeFetchMultipleMintInfos } from \"../../raydium/type\";\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport { toApiV3Token, toFeeConfig } from \"../token\";\nimport {\n  makeCreateCpmmPoolInInstruction,\n  makeDepositCpmmInInstruction,\n  makeSwapCpmmBaseInInstruction,\n  makeSwapCpmmBaseOutInstruction,\n  makeWithdrawCpmmInInstruction,\n  makeCpmmLockInstruction,\n  collectCpFeeInstruction,\n} from \"./instruction\";\nimport { CpmmConfigInfoLayout, CpmmPoolInfoLayout } from \"./layout\";\nimport { getCreatePoolKeys, getPdaObservationId, getPdaPoolAuthority } from \"./pda\";\nimport {\n  AddCpmmLiquidityParams,\n  ComputePairAmountParams,\n  CpmmComputeData,\n  CpmmLockExtInfo,\n  CpmmRpcData,\n  CpmmSwapParams,\n  CreateCpmmPoolAddress,\n  CreateCpmmPoolParam,\n  LockCpmmLpParams,\n  HarvestLockCpmmLpParams,\n  WithdrawCpmmLiquidityParams,\n} from \"./type\";\nimport { getCpLockPda } from \"./pda\";\n\nexport default class CpmmModule extends ModuleBase {\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  public async load(): Promise<void> {\n    this.checkDisabled();\n  }\n\n  public async getCpmmPoolKeys(poolId: string): Promise<CpmmKeys> {\n    return ((await this.scope.api.fetchPoolKeysById({ idList: [poolId] })) as CpmmKeys[])[0];\n  }\n\n  public async getRpcPoolInfo(poolId: string, fetchConfigInfo?: boolean): Promise<CpmmRpcData> {\n    return (await this.getRpcPoolInfos([poolId], fetchConfigInfo))[poolId];\n  }\n\n  public async getRpcPoolInfos(\n    poolIds: string[],\n    fetchConfigInfo?: boolean,\n  ): Promise<{\n    [poolId: string]: CpmmRpcData;\n  }> {\n    const accounts = await getMultipleAccountsInfoWithCustomFlags(\n      this.scope.connection,\n      poolIds.map((i) => ({ pubkey: new PublicKey(i) })),\n    );\n    const poolInfos: { [poolId: string]: ReturnType<typeof CpmmPoolInfoLayout.decode> & { programId: PublicKey } } = {};\n\n    const needFetchConfigId = new Set<string>();\n    const needFetchVaults: PublicKey[] = [];\n\n    for (let i = 0; i < poolIds.length; i++) {\n      const item = accounts[i];\n      if (item.accountInfo === null) throw Error(\"fetch pool info error: \" + String(poolIds[i]));\n      const rpc = CpmmPoolInfoLayout.decode(item.accountInfo.data);\n      poolInfos[String(poolIds[i])] = {\n        ...rpc,\n        programId: item.accountInfo.owner,\n      };\n      needFetchConfigId.add(String(rpc.configId));\n\n      needFetchVaults.push(rpc.vaultA, rpc.vaultB);\n    }\n\n    const configInfo: { [configId: string]: ReturnType<typeof CpmmConfigInfoLayout.decode> } = {};\n\n    if (fetchConfigInfo) {\n      const configIds = [...needFetchConfigId];\n      const configState = await getMultipleAccountsInfoWithCustomFlags(\n        this.scope.connection,\n        configIds.map((i) => ({ pubkey: new PublicKey(i) })),\n      );\n\n      for (let i = 0; i < configIds.length; i++) {\n        const configItemInfo = configState[i].accountInfo;\n        if (configItemInfo === null) throw Error(\"fetch pool config error: \" + configIds[i]);\n        configInfo[configIds[i]] = CpmmConfigInfoLayout.decode(configItemInfo.data);\n      }\n    }\n\n    const vaultInfo: { [vaultId: string]: BN } = {};\n\n    const vaultAccountInfo = await getMultipleAccountsInfoWithCustomFlags(\n      this.scope.connection,\n      needFetchVaults.map((i) => ({ pubkey: new PublicKey(i) })),\n    );\n\n    for (let i = 0; i < needFetchVaults.length; i++) {\n      const vaultItemInfo = vaultAccountInfo[i].accountInfo;\n      if (vaultItemInfo === null) throw Error(\"fetch vault info error: \" + needFetchVaults[i]);\n\n      vaultInfo[String(needFetchVaults[i])] = new BN(AccountLayout.decode(vaultItemInfo.data).amount.toString());\n    }\n\n    const returnData: { [poolId: string]: CpmmRpcData } = {};\n\n    for (const [id, info] of Object.entries(poolInfos)) {\n      const baseReserve = vaultInfo[info.vaultA.toString()].sub(info.protocolFeesMintA).sub(info.fundFeesMintA);\n      const quoteReserve = vaultInfo[info.vaultB.toString()].sub(info.protocolFeesMintB).sub(info.fundFeesMintB);\n      returnData[id] = {\n        ...info,\n        baseReserve,\n        quoteReserve,\n        vaultAAmount: vaultInfo[info.vaultA.toString()],\n        vaultBAmount: vaultInfo[info.vaultB.toString()],\n        configInfo: configInfo[info.configId.toString()],\n        poolPrice: new Decimal(quoteReserve.toString())\n          .div(new Decimal(10).pow(info.mintDecimalB))\n          .div(new Decimal(baseReserve.toString()).div(new Decimal(10).pow(info.mintDecimalA))),\n      };\n    }\n\n    return returnData;\n  }\n\n  public toComputePoolInfos({\n    pools,\n    mintInfos,\n  }: {\n    pools: Record<string, CpmmRpcData>;\n    mintInfos: ReturnTypeFetchMultipleMintInfos;\n  }): Record<string, CpmmComputeData> {\n    return Object.keys(pools).reduce((acc, cur) => {\n      const pool = pools[cur];\n      const [mintA, mintB] = [pool.mintA.toBase58(), pool.mintB.toBase58()];\n\n      return {\n        ...acc,\n        [cur]: {\n          ...pool,\n          id: new PublicKey(cur),\n          configInfo: pool.configInfo!,\n          version: 7 as const,\n          authority: getPdaPoolAuthority(pool.programId).publicKey,\n          mintA: toApiV3Token({\n            address: mintA,\n            decimals: pool.mintDecimalA,\n            programId: pool.mintProgramA.toBase58(),\n            extensions: {\n              feeConfig: mintInfos[mintA]?.feeConfig ? toFeeConfig(mintInfos[mintA]?.feeConfig) : undefined,\n            },\n          }),\n          mintB: toApiV3Token({\n            address: mintB,\n            decimals: pool.mintDecimalB,\n            programId: pool.mintProgramB.toBase58(),\n            extensions: {\n              feeConfig: mintInfos[mintB]?.feeConfig ? toFeeConfig(mintInfos[mintB]?.feeConfig) : undefined,\n            },\n          }),\n        },\n      };\n    }, {} as Record<string, CpmmComputeData>);\n  }\n\n  public async getPoolInfoFromRpc(poolId: string): Promise<{\n    poolInfo: ApiV3PoolInfoStandardItemCpmm;\n    poolKeys: CpmmKeys;\n    rpcData: CpmmRpcData;\n  }> {\n    const rpcData = await this.getRpcPoolInfo(poolId, true);\n    const mintInfos = await fetchMultipleMintInfos({\n      connection: this.scope.connection,\n      mints: [rpcData.mintA, rpcData.mintB],\n    });\n\n    const mintA = toApiV3Token({\n      address: rpcData.mintA.toBase58(),\n      decimals: rpcData.mintDecimalA,\n      programId: rpcData.mintProgramA.toBase58(),\n      extensions: {\n        feeConfig: mintInfos[rpcData.mintA.toBase58()].feeConfig\n          ? toFeeConfig(mintInfos[rpcData.mintA.toBase58()].feeConfig)\n          : undefined,\n      },\n    });\n    const mintB = toApiV3Token({\n      address: rpcData.mintB.toBase58(),\n      decimals: rpcData.mintDecimalB,\n      programId: rpcData.mintProgramB.toBase58(),\n      extensions: {\n        feeConfig: mintInfos[rpcData.mintB.toBase58()].feeConfig\n          ? toFeeConfig(mintInfos[rpcData.mintB.toBase58()].feeConfig)\n          : undefined,\n      },\n    });\n\n    const lpMint = toApiV3Token({\n      address: rpcData.mintLp.toBase58(),\n      decimals: rpcData.lpDecimals,\n      programId: TOKEN_PROGRAM_ID.toBase58(),\n    });\n\n    const configInfo = {\n      id: rpcData.configId.toBase58(),\n      index: rpcData.configInfo!.index,\n      protocolFeeRate: rpcData.configInfo!.protocolFeeRate.toNumber(),\n      tradeFeeRate: rpcData.configInfo!.tradeFeeRate.toNumber(),\n      fundFeeRate: rpcData.configInfo!.fundFeeRate.toNumber(),\n      createPoolFee: rpcData.configInfo!.createPoolFee.toString(),\n    };\n\n    const mockRewardData = {\n      volume: 0,\n      volumeQuote: 0,\n      volumeFee: 0,\n      apr: 0,\n      feeApr: 0,\n      priceMin: 0,\n      priceMax: 0,\n      rewardApr: [],\n    };\n\n    return {\n      poolInfo: {\n        programId: rpcData.programId.toBase58(),\n        id: poolId,\n        type: \"Standard\",\n        lpMint,\n        lpPrice: 0,\n        lpAmount: rpcData.lpAmount.toNumber(),\n        config: configInfo,\n        mintA,\n        mintB,\n        rewardDefaultInfos: [],\n        rewardDefaultPoolInfos: \"Ecosystem\",\n        price: rpcData.poolPrice.toNumber(),\n        mintAmountA: new Decimal(rpcData.vaultAAmount.toString()).div(10 ** mintA.decimals).toNumber(),\n        mintAmountB: new Decimal(rpcData.vaultBAmount.toString()).div(10 ** mintB.decimals).toNumber(),\n        feeRate: rpcData.configInfo!.tradeFeeRate.toNumber(),\n        openTime: rpcData.openTime.toString(),\n        tvl: 0,\n        burnPercent: 0,\n\n        day: mockRewardData,\n        week: mockRewardData,\n        month: mockRewardData,\n        pooltype: [],\n\n        farmUpcomingCount: 0,\n        farmOngoingCount: 0,\n        farmFinishedCount: 0,\n      },\n      poolKeys: {\n        programId: rpcData.programId.toBase58(),\n        id: poolId,\n        mintA,\n        mintB,\n        openTime: rpcData.openTime.toString(),\n        vault: { A: rpcData.vaultA.toBase58(), B: rpcData.vaultB.toBase58() },\n        authority: getPdaPoolAuthority(rpcData.programId).publicKey.toBase58(),\n        mintLp: lpMint,\n        config: configInfo,\n        observationId: getPdaObservationId(rpcData.programId, new PublicKey(poolId)).publicKey.toBase58(),\n      },\n      rpcData,\n    };\n  }\n\n  public async createPool<T extends TxVersion>({\n    poolId,\n    programId,\n    poolFeeAccount,\n    startTime,\n    ownerInfo,\n    associatedOnly = false,\n    checkCreateATAOwner = false,\n    txVersion,\n    feeConfig,\n    computeBudgetConfig,\n    txTipConfig,\n    feePayer,\n    ...params\n  }: CreateCpmmPoolParam<T>): Promise<MakeTxData<T, { address: CreateCpmmPoolAddress }>> {\n    const payer = ownerInfo.feePayer || this.scope.owner?.publicKey;\n    const isFront = new BN(new PublicKey(params.mintA.address).toBuffer()).lte(\n      new BN(new PublicKey(params.mintB.address).toBuffer()),\n    );\n\n    const [mintA, mintB] = isFront ? [params.mintA, params.mintB] : [params.mintB, params.mintA];\n    const [mintAAmount, mintBAmount] = isFront\n      ? [params.mintAAmount, params.mintBAmount]\n      : [params.mintBAmount, params.mintAAmount];\n\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && mintA.address === NATIVE_MINT.toBase58();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && mintB.address === NATIVE_MINT.toBase58();\n    const [mintAPubkey, mintBPubkey] = [new PublicKey(mintA.address), new PublicKey(mintB.address)];\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const { account: userVaultA, instructionParams: userVaultAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: mintAPubkey,\n        tokenProgram: mintA.programId,\n        owner: this.scope.ownerPubKey,\n        createInfo: mintAUseSOLBalance\n          ? {\n            payer: payer!,\n            amount: mintAAmount,\n          }\n          : undefined,\n        notUseTokenAccount: mintAUseSOLBalance,\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(userVaultAInstruction || {});\n    const { account: userVaultB, instructionParams: userVaultBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: new PublicKey(mintB.address),\n        tokenProgram: mintB.programId,\n        owner: this.scope.ownerPubKey,\n        createInfo: mintBUseSOLBalance\n          ? {\n            payer: payer!,\n            amount: mintBAmount,\n          }\n          : undefined,\n\n        notUseTokenAccount: mintBUseSOLBalance,\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(userVaultBInstruction || {});\n\n    if (userVaultA === undefined || userVaultB === undefined) throw Error(\"you don't has some token account\");\n\n    const poolKeys = getCreatePoolKeys({\n      poolId,\n      programId,\n      configId: new PublicKey(feeConfig.id),\n      mintA: mintAPubkey,\n      mintB: mintBPubkey,\n    });\n\n    txBuilder.addInstruction({\n      instructions: [\n        makeCreateCpmmPoolInInstruction(\n          programId,\n          this.scope.ownerPubKey,\n          new PublicKey(feeConfig.id),\n          poolKeys.authority,\n          poolKeys.poolId,\n          mintAPubkey,\n          mintBPubkey,\n          poolKeys.lpMint,\n          userVaultA,\n          userVaultB,\n          getATAAddress(this.scope.ownerPubKey, poolKeys.lpMint).publicKey,\n          poolKeys.vaultA,\n          poolKeys.vaultB,\n          poolFeeAccount,\n          new PublicKey(mintA.programId ?? TOKEN_PROGRAM_ID),\n          new PublicKey(mintB.programId ?? TOKEN_PROGRAM_ID),\n          poolKeys.observationId,\n          mintAAmount,\n          mintBAmount,\n          startTime,\n        ),\n      ],\n      instructionTypes: [InstructionType.CpmmCreatePool],\n    });\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({\n      txVersion,\n      extInfo: {\n        address: { ...poolKeys, mintA, mintB, programId, poolFeeAccount, feeConfig },\n      },\n    }) as Promise<MakeTxData<T, { address: CreateCpmmPoolAddress }>>;\n  }\n\n  public async addLiquidity<T extends TxVersion>(params: AddCpmmLiquidityParams<T>): Promise<MakeTxData<T>> {\n    const {\n      poolInfo,\n      poolKeys: propPoolKeys,\n      inputAmount,\n      baseIn,\n      slippage,\n      computeResult,\n      computeBudgetConfig,\n      txTipConfig,\n      config,\n      txVersion,\n      feePayer,\n    } = params;\n\n    if (this.scope.availability.addStandardPosition === false)\n      this.logAndCreateError(\"add liquidity feature disabled in your region\");\n\n    if (inputAmount.isZero())\n      this.logAndCreateError(\"amounts must greater than zero\", \"amountInA\", {\n        amountInA: inputAmount.toString(),\n      });\n    const { account } = this.scope;\n    const { bypassAssociatedCheck, checkCreateATAOwner } = {\n      // default\n      ...{ bypassAssociatedCheck: false, checkCreateATAOwner: false },\n      // custom\n      ...config,\n    };\n    const rpcPoolData = computeResult ? undefined : await this.getRpcPoolInfo(poolInfo.id);\n\n    const {\n      liquidity,\n      inputAmountFee,\n      anotherAmount: _anotherAmount,\n    } = computeResult ||\n      this.computePairAmount({\n        poolInfo: {\n          ...poolInfo,\n          lpAmount: new Decimal(rpcPoolData!.lpAmount.toString()).div(10 ** poolInfo.lpMint.decimals).toNumber(),\n        },\n        baseReserve: rpcPoolData!.baseReserve,\n        quoteReserve: rpcPoolData!.quoteReserve,\n        slippage: new Percent(0),\n        baseIn,\n        epochInfo: await this.scope.fetchEpochInfo(),\n        amount: new Decimal(inputAmount.toString()).div(\n          10 ** (baseIn ? poolInfo.mintA.decimals : poolInfo.mintB.decimals),\n        ),\n      });\n\n    const anotherAmount = _anotherAmount.amount;\n    const mintAUseSOLBalance = poolInfo.mintA.address === NATIVE_MINT.toString();\n    const mintBUseSOLBalance = poolInfo.mintB.address === NATIVE_MINT.toString();\n\n    const txBuilder = this.createTxBuilder(feePayer);\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n\n    const { account: tokenAccountA, instructionParams: _tokenAccountAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintAUseSOLBalance || (baseIn ? inputAmount : anotherAmount).isZero()\n            ? {\n              payer: this.scope.ownerPubKey,\n              amount: baseIn ? inputAmount : anotherAmount,\n            }\n            : undefined,\n        skipCloseAccount: !mintAUseSOLBalance,\n        notUseTokenAccount: mintAUseSOLBalance,\n        associatedOnly: false,\n        checkCreateATAOwner,\n      });\n\n    txBuilder.addInstruction(_tokenAccountAInstruction || {});\n\n    const { account: tokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintBUseSOLBalance || (baseIn ? anotherAmount : inputAmount).isZero()\n            ? {\n              payer: this.scope.ownerPubKey,\n              amount: baseIn ? anotherAmount : inputAmount,\n            }\n            : undefined,\n        skipCloseAccount: !mintBUseSOLBalance,\n        notUseTokenAccount: mintBUseSOLBalance,\n        associatedOnly: false,\n        checkCreateATAOwner,\n      });\n\n    txBuilder.addInstruction(_tokenAccountBInstruction || {});\n\n    if (!tokenAccountA && !tokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", account.tokenAccounts);\n    const lpTokenAccount = await account.getCreatedTokenAccount({\n      mint: new PublicKey(poolInfo.lpMint.address),\n    });\n    const { tokenAccount: _lpTokenAccount, ...lpInstruction } = await account.handleTokenAccount({\n      side: \"out\",\n      amount: 0,\n      mint: new PublicKey(poolInfo.lpMint.address),\n      tokenAccount: lpTokenAccount,\n      bypassAssociatedCheck,\n      checkCreateATAOwner,\n    });\n    txBuilder.addInstruction(lpInstruction);\n    const poolKeys = propPoolKeys ?? (await this.getCpmmPoolKeys(poolInfo.id));\n    const _slippage = new Percent(new BN(1)).sub(slippage);\n\n    txBuilder.addInstruction({\n      instructions: [\n        makeDepositCpmmInInstruction(\n          new PublicKey(poolInfo.programId),\n          this.scope.ownerPubKey,\n          new PublicKey(poolKeys.authority),\n          new PublicKey(poolInfo.id),\n          _lpTokenAccount!,\n          tokenAccountA!,\n          tokenAccountB!,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          mintA,\n          mintB,\n          new PublicKey(poolInfo.lpMint.address),\n\n          computeResult ? computeResult?.liquidity : _slippage.mul(liquidity).quotient,\n          baseIn ? inputAmountFee.amount : anotherAmount,\n          baseIn ? anotherAmount : inputAmountFee.amount,\n        ),\n      ],\n      instructionTypes: [InstructionType.CpmmAddLiquidity],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    });\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async withdrawLiquidity<T extends TxVersion>(params: WithdrawCpmmLiquidityParams<T>): Promise<MakeTxData<T>> {\n    const {\n      poolInfo,\n      poolKeys: propPoolKeys,\n      lpAmount,\n      slippage,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n      closeWsol = true,\n    } = params;\n\n    if (this.scope.availability.addStandardPosition === false)\n      this.logAndCreateError(\"add liquidity feature disabled in your region\");\n\n    const _slippage = new Percent(new BN(1)).sub(slippage);\n\n    const rpcPoolData = await this.getRpcPoolInfo(poolInfo.id);\n    const [amountMintA, amountMintB] = [\n      _slippage.mul(lpAmount.mul(rpcPoolData.baseReserve).div(rpcPoolData.lpAmount)).quotient,\n      _slippage.mul(lpAmount.mul(rpcPoolData.quoteReserve).div(rpcPoolData.lpAmount)).quotient,\n    ];\n\n    const epochInfo = await this.scope.fetchEpochInfo();\n    const [mintAAmountFee, mintBAmountFee] = [\n      getTransferAmountFeeV2(amountMintA, poolInfo.mintA.extensions.feeConfig, epochInfo, false),\n      getTransferAmountFeeV2(amountMintB, poolInfo.mintB.extensions.feeConfig, epochInfo, false),\n    ];\n\n    const { account } = this.scope;\n    const txBuilder = this.createTxBuilder(feePayer);\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n\n    const mintAUseSOLBalance = mintA.equals(WSOLMint);\n    const mintBUseSOLBalance = mintB.equals(WSOLMint);\n\n    let tokenAccountA: PublicKey | undefined = undefined;\n    let tokenAccountB: PublicKey | undefined = undefined;\n    const { account: _ownerTokenAccountA, instructionParams: accountAInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !(mintAUseSOLBalance && closeWsol),\n        associatedOnly: mintAUseSOLBalance ? false : true,\n        checkCreateATAOwner: false,\n      });\n    tokenAccountA = _ownerTokenAccountA;\n    accountAInstructions && txBuilder.addInstruction(accountAInstructions);\n\n    const { account: _ownerTokenAccountB, instructionParams: accountBInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !(mintBUseSOLBalance && closeWsol),\n        associatedOnly: mintBUseSOLBalance ? false : true,\n        checkCreateATAOwner: false,\n      });\n    tokenAccountB = _ownerTokenAccountB;\n    accountBInstructions && txBuilder.addInstruction(accountBInstructions);\n\n    if (!tokenAccountA || !tokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", account.tokenAccounts);\n\n    const lpTokenAccount = await account.getCreatedTokenAccount({\n      mint: new PublicKey(poolInfo.lpMint.address),\n    });\n\n    if (!lpTokenAccount)\n      this.logAndCreateError(\"cannot found lp token account\", \"tokenAccounts\", account.tokenAccounts);\n    const poolKeys = propPoolKeys ?? (await this.getCpmmPoolKeys(poolInfo.id));\n    txBuilder.addInstruction({\n      instructions: [\n        makeWithdrawCpmmInInstruction(\n          new PublicKey(poolInfo.programId),\n          this.scope.ownerPubKey,\n          new PublicKey(poolKeys.authority),\n          new PublicKey(poolInfo.id),\n          lpTokenAccount!,\n          tokenAccountA!,\n          tokenAccountB!,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          mintA,\n          mintB,\n          new PublicKey(poolInfo.lpMint.address),\n\n          lpAmount,\n          amountMintA.sub(mintAAmountFee.fee ?? new BN(0)),\n          amountMintB.sub(mintBAmountFee.fee ?? new BN(0)),\n        ),\n      ],\n      instructionTypes: [InstructionType.CpmmWithdrawLiquidity],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    });\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async swap<T extends TxVersion>(params: CpmmSwapParams<T>): Promise<MakeTxData<T>> {\n    const {\n      poolInfo,\n      poolKeys: propPoolKeys,\n      baseIn,\n      fixedOut,\n      inputAmount,\n      swapResult,\n      slippage = 0,\n      config,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n    } = params;\n\n    const { bypassAssociatedCheck, checkCreateATAOwner, associatedOnly } = {\n      // default\n      ...{ bypassAssociatedCheck: false, checkCreateATAOwner: false, associatedOnly: true },\n      // custom\n      ...config,\n    };\n\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n\n    if (!fixedOut) {\n      swapResult.destinationAmountSwapped = swapResult.destinationAmountSwapped\n        .mul(new BN((1 - slippage) * 10000))\n        .div(new BN(10000));\n    } else {\n      swapResult.sourceAmountSwapped = swapResult.sourceAmountSwapped\n        .mul(new BN((1 + slippage) * 10000))\n        .div(new BN(10000));\n    }\n\n    const mintAUseSOLBalance = poolInfo.mintA.address === WSOLMint.toBase58();\n    const mintBUseSOLBalance = poolInfo.mintB.address === WSOLMint.toBase58();\n    const { account: mintATokenAcc, instructionParams: mintATokenAccInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: mintA,\n        tokenProgram: new PublicKey(poolInfo.mintA.programId ?? TOKEN_PROGRAM_ID),\n        owner: this.scope.ownerPubKey,\n        createInfo:\n          mintAUseSOLBalance || !baseIn\n            ? {\n              payer: this.scope.ownerPubKey,\n              amount: baseIn ? swapResult.sourceAmountSwapped : 0,\n            }\n            : undefined,\n        notUseTokenAccount: mintAUseSOLBalance,\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    mintATokenAccInstruction && txBuilder.addInstruction(mintATokenAccInstruction);\n\n    const { account: mintBTokenAcc, instructionParams: mintBTokenAccInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: mintB,\n        tokenProgram: new PublicKey(poolInfo.mintB.programId ?? TOKEN_PROGRAM_ID),\n        owner: this.scope.ownerPubKey,\n        createInfo:\n          mintBUseSOLBalance || baseIn\n            ? {\n              payer: this.scope.ownerPubKey,\n              amount: baseIn ? 0 : swapResult.sourceAmountSwapped,\n            }\n            : undefined,\n        notUseTokenAccount: mintBUseSOLBalance,\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    mintBTokenAccInstruction && txBuilder.addInstruction(mintBTokenAccInstruction);\n\n    if (!mintATokenAcc || !mintBTokenAcc)\n      this.logAndCreateError(\"user do not have token account\", {\n        mintA: poolInfo.mintA.symbol || poolInfo.mintA.address,\n        mintB: poolInfo.mintB.symbol || poolInfo.mintB.address,\n        mintATokenAcc,\n        mintBTokenAcc,\n        mintAUseSOLBalance,\n        mintBUseSOLBalance,\n        associatedOnly,\n      });\n\n    const poolKeys = propPoolKeys ?? (await this.getCpmmPoolKeys(poolInfo.id));\n\n    txBuilder.addInstruction({\n      instructions: [\n        !fixedOut\n          ? makeSwapCpmmBaseInInstruction(\n            new PublicKey(poolInfo.programId),\n            this.scope.ownerPubKey,\n            new PublicKey(poolKeys.authority),\n            new PublicKey(poolKeys.config.id),\n            new PublicKey(poolInfo.id),\n            baseIn ? mintATokenAcc! : mintBTokenAcc!,\n            baseIn ? mintBTokenAcc! : mintATokenAcc!,\n            new PublicKey(poolKeys.vault[baseIn ? \"A\" : \"B\"]),\n            new PublicKey(poolKeys.vault[baseIn ? \"B\" : \"A\"]),\n            new PublicKey(poolInfo[baseIn ? \"mintA\" : \"mintB\"].programId ?? TOKEN_PROGRAM_ID),\n            new PublicKey(poolInfo[baseIn ? \"mintB\" : \"mintA\"].programId ?? TOKEN_PROGRAM_ID),\n            baseIn ? mintA : mintB,\n            baseIn ? mintB : mintA,\n            getPdaObservationId(new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)).publicKey,\n\n            inputAmount,\n            swapResult.destinationAmountSwapped,\n          )\n          : makeSwapCpmmBaseOutInstruction(\n            new PublicKey(poolInfo.programId),\n            this.scope.ownerPubKey,\n            new PublicKey(poolKeys.authority),\n            new PublicKey(poolKeys.config.id),\n            new PublicKey(poolInfo.id),\n\n            baseIn ? mintATokenAcc! : mintBTokenAcc!,\n            baseIn ? mintBTokenAcc! : mintATokenAcc!,\n\n            new PublicKey(poolKeys.vault[baseIn ? \"A\" : \"B\"]),\n            new PublicKey(poolKeys.vault[baseIn ? \"B\" : \"A\"]),\n            new PublicKey(poolInfo[baseIn ? \"mintA\" : \"mintB\"].programId ?? TOKEN_PROGRAM_ID),\n            new PublicKey(poolInfo[baseIn ? \"mintB\" : \"mintA\"].programId ?? TOKEN_PROGRAM_ID),\n            baseIn ? mintA : mintB,\n            baseIn ? mintB : mintA,\n\n            getPdaObservationId(new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)).publicKey,\n\n            swapResult.sourceAmountSwapped,\n            swapResult.destinationAmountSwapped,\n          ),\n      ],\n      instructionTypes: [fixedOut ? InstructionType.CpmmSwapBaseOut : InstructionType.ClmmSwapBaseIn],\n    });\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async lockLp<T extends TxVersion>(params: LockCpmmLpParams<T>): Promise<MakeTxData<CpmmLockExtInfo>> {\n    const { poolInfo, lpAmount, computeBudgetConfig, txTipConfig, txVersion, feePayer, feeNftOwner } = params;\n\n    if (lpAmount.isZero())\n      this.logAndCreateError(\"lpAmount must greater than zero\", {\n        lpAmount: lpAmount.toString(),\n      });\n\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const poolKeys = params.poolKeys ?? (await this.getCpmmPoolKeys(poolInfo.id));\n\n    const insData = await makeCpmmLockInstruction({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        feePayer: params.feePayer ?? this.scope.ownerPubKey,\n      },\n      feeNftOwner: feeNftOwner ?? this.scope.ownerPubKey,\n      lockProgram: params.programId ?? LOCK_CPMM_PROGRAM,\n      lockAuthProgram: params.authProgram ?? LOCK_CPMM_AUTH,\n      lpAmount,\n      withMetadata: params.withMetadata ?? true,\n      getEphemeralSigners: params.getEphemeralSigners,\n    });\n\n    txBuilder.addInstruction(insData);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion, extInfo: insData.address }) as Promise<MakeTxData<CpmmLockExtInfo>>;\n  }\n\n  public async harvestLockLp<T extends TxVersion>(params: HarvestLockCpmmLpParams<T>): Promise<MakeTxData> {\n    const {\n      poolInfo,\n      lpFeeAmount,\n      nftMint,\n      programId = LOCK_CPMM_PROGRAM,\n      authProgram = LOCK_CPMM_AUTH,\n      cpmmProgram,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      closeWsol = true,\n    } = params;\n\n    if (lpFeeAmount.isZero())\n      this.logAndCreateError(\"lpFeeAmount must greater than zero\", {\n        lpAmount: lpFeeAmount.toString(),\n      });\n\n    const feePayer = params.feePayer || this.scope.ownerPubKey;\n\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n\n    const mintAUseSOLBalance = mintA.equals(WSOLMint);\n    const mintBUseSOLBalance = mintB.equals(WSOLMint);\n\n    let tokenAccountA: PublicKey | undefined = undefined;\n    let tokenAccountB: PublicKey | undefined = undefined;\n    const { account: _ownerTokenAccountA, instructionParams: accountAInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !(mintAUseSOLBalance && closeWsol),\n        associatedOnly: mintAUseSOLBalance ? false : true,\n        checkCreateATAOwner: false,\n      });\n    tokenAccountA = _ownerTokenAccountA;\n    accountAInstructions && txBuilder.addInstruction(accountAInstructions);\n\n    const { account: _ownerTokenAccountB, instructionParams: accountBInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !(mintBUseSOLBalance && closeWsol),\n        associatedOnly: mintBUseSOLBalance ? false : true,\n        checkCreateATAOwner: false,\n      });\n    tokenAccountB = _ownerTokenAccountB;\n    accountBInstructions && txBuilder.addInstruction(accountBInstructions);\n\n    if (!tokenAccountA || !tokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", { tokenAccountA, tokenAccountB });\n\n    const poolKeys = params.poolKeys ?? (await this.getCpmmPoolKeys(poolInfo.id));\n\n    const { publicKey: nftAccount } = getATAAddress(feePayer, nftMint, TOKEN_PROGRAM_ID);\n    const { publicKey: lockPda } = getCpLockPda(programId, nftMint);\n    const { publicKey: lockLpVault } = getATAAddress(\n      authProgram,\n      new PublicKey(poolInfo.lpMint.address),\n      TOKEN_PROGRAM_ID,\n    );\n\n    txBuilder.addInstruction({\n      instructions: [\n        collectCpFeeInstruction({\n          programId: programId ?? LOCK_CPMM_PROGRAM,\n          nftOwner: this.scope.ownerPubKey,\n          auth: authProgram ?? LOCK_CPMM_AUTH,\n\n          nftMint,\n          nftAccount,\n\n          lockPda,\n          poolId: new PublicKey(poolInfo.id),\n          mintLp: new PublicKey(poolKeys.mintLp.address),\n\n          userVaultA: tokenAccountA!,\n          userVaultB: tokenAccountB!,\n          poolVaultA: new PublicKey(poolKeys.vault.A),\n          poolVaultB: new PublicKey(poolKeys.vault.B),\n\n          mintA,\n          mintB,\n          lockLpVault,\n          lpFeeAmount,\n\n          cpmmProgram: cpmmProgram?.programId,\n          cpmmAuthProgram: cpmmProgram?.authProgram,\n        }),\n      ],\n      instructionTypes: [InstructionType.CpmmCollectLockFee],\n    });\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData>;\n  }\n\n  public computeSwapAmount({\n    pool,\n    amountIn,\n    outputMint,\n    slippage,\n  }: {\n    pool: CpmmComputeData;\n    amountIn: BN;\n    outputMint: string | PublicKey;\n    slippage: number;\n  }): {\n    allTrade: boolean;\n    amountIn: BN;\n    amountOut: BN;\n    minAmountOut: BN;\n    fee: BN;\n    executionPrice: Decimal;\n    priceImpact: any;\n  } {\n    const isBaseIn = outputMint.toString() === pool.mintB.address;\n\n    const swapResult = CurveCalculator.swap(\n      amountIn,\n      isBaseIn ? pool.baseReserve : pool.quoteReserve,\n      isBaseIn ? pool.quoteReserve : pool.baseReserve,\n      pool.configInfo.tradeFeeRate,\n    );\n\n    const executionPrice = new Decimal(swapResult.destinationAmountSwapped.toString()).div(\n      swapResult.sourceAmountSwapped.toString(),\n    );\n\n    const minAmountOut = swapResult.destinationAmountSwapped.mul(new BN((1 - slippage) * 10000)).div(new BN(10000));\n\n    return {\n      allTrade: swapResult.sourceAmountSwapped.eq(amountIn),\n      amountIn,\n      amountOut: swapResult.destinationAmountSwapped,\n      minAmountOut,\n      executionPrice,\n      fee: swapResult.tradeFee,\n      priceImpact: pool.poolPrice.sub(executionPrice).div(pool.poolPrice),\n    };\n  }\n\n  public computePairAmount({\n    poolInfo,\n    baseReserve,\n    quoteReserve,\n    amount,\n    slippage,\n    epochInfo,\n    baseIn,\n  }: ComputePairAmountParams): {\n    inputAmountFee: GetTransferAmountFee;\n    anotherAmount: GetTransferAmountFee;\n    maxAnotherAmount: GetTransferAmountFee;\n    minAnotherAmount: GetTransferAmountFee;\n    liquidity: BN;\n  } {\n    const coefficient = 1 - Number(slippage.toSignificant()) / 100;\n    const inputAmount = new BN(\n      new Decimal(amount)\n        .mul(10 ** poolInfo[baseIn ? \"mintA\" : \"mintB\"].decimals)\n        .mul(coefficient)\n        .toFixed(0),\n    );\n    const inputAmountFee = getTransferAmountFeeV2(\n      inputAmount,\n      poolInfo[baseIn ? \"mintA\" : \"mintB\"].extensions.feeConfig,\n      epochInfo,\n      false,\n    );\n    const _inputAmountWithoutFee = inputAmount.sub(inputAmountFee.fee ?? new BN(0));\n\n    const lpAmount = new BN(\n      new Decimal(poolInfo.lpAmount).mul(10 ** poolInfo.lpMint.decimals).toFixed(0, Decimal.ROUND_DOWN),\n    );\n    this.logDebug(\"baseReserve:\", baseReserve.toString(), \"quoteReserve:\", quoteReserve.toString());\n\n    this.logDebug(\n      \"tokenIn:\",\n      baseIn ? poolInfo.mintA.symbol : poolInfo.mintB.symbol,\n      \"amountIn:\",\n      inputAmount.toString(),\n      \"amountInFee:\",\n      inputAmountFee.fee?.toString() ?? 0,\n      \"anotherToken:\",\n      baseIn ? poolInfo.mintB.symbol : poolInfo.mintA.symbol,\n      \"slippage:\",\n      `${slippage.toSignificant()}%`,\n    );\n\n    // input is fixed\n    const input = baseIn ? \"base\" : \"quote\";\n    this.logDebug(\"input side:\", input);\n\n    const liquidity = _inputAmountWithoutFee.mul(lpAmount).div(input === \"base\" ? baseReserve : quoteReserve);\n    let anotherAmountFee: GetTransferAmountFee = {\n      amount: BN_ZERO,\n      fee: undefined,\n      expirationTime: undefined,\n    };\n    if (!_inputAmountWithoutFee.isZero()) {\n      const lpAmountData = lpToAmount(liquidity, baseReserve, quoteReserve, lpAmount);\n      this.logDebug(\"lpAmountData:\", {\n        amountA: lpAmountData.amountA.toString(),\n        amountB: lpAmountData.amountB.toString(),\n      });\n      anotherAmountFee = getTransferAmountFeeV2(\n        lpAmountData[baseIn ? \"amountB\" : \"amountA\"],\n        poolInfo[baseIn ? \"mintB\" : \"mintA\"].extensions.feeConfig,\n        epochInfo,\n        true,\n      );\n    }\n\n    const _slippage = new Percent(new BN(1)).add(slippage);\n    const _slippageMin = new Percent(new BN(1)).sub(slippage);\n    const slippageAdjustedAmount = getTransferAmountFeeV2(\n      _slippage.mul(anotherAmountFee.amount.sub(anotherAmountFee.fee ?? new BN(0))).quotient,\n      poolInfo[baseIn ? \"mintB\" : \"mintA\"].extensions.feeConfig,\n      epochInfo,\n      true,\n    );\n    const slippageAdjustedMinAmount = getTransferAmountFeeV2(\n      _slippageMin.mul(anotherAmountFee.amount.sub(anotherAmountFee.fee ?? new BN(0))).quotient,\n      poolInfo[baseIn ? \"mintB\" : \"mintA\"].extensions.feeConfig,\n      epochInfo,\n      true,\n    );\n\n    this.logDebug(\n      \"anotherAmount:\",\n      anotherAmountFee.amount.toString(),\n      \"anotherAmountFee:\",\n      anotherAmountFee.fee?.toString() ?? 0,\n      \"maxAnotherAmount:\",\n      slippageAdjustedAmount.amount.toString(),\n      \"maxAnotherAmountFee:\",\n      slippageAdjustedAmount.fee?.toString() ?? 0,\n    );\n\n    return {\n      inputAmountFee,\n      anotherAmount: anotherAmountFee,\n      maxAnotherAmount: slippageAdjustedAmount,\n      minAnotherAmount: slippageAdjustedMinAmount,\n      liquidity,\n    };\n  }\n}\n\nfunction lpToAmount(lp: BN, poolAmountA: BN, poolAmountB: BN, supply: BN): { amountA: BN; amountB: BN } {\n  let amountA = lp.mul(poolAmountA).div(supply);\n  if (!amountA.isZero() && !lp.mul(poolAmountA).mod(supply).isZero()) amountA = amountA.add(new BN(1));\n  let amountB = lp.mul(poolAmountB).div(supply);\n  if (!amountB.isZero() && !lp.mul(poolAmountB).mod(supply).isZero()) amountB = amountB.add(new BN(1));\n\n  return {\n    amountA,\n    amountB,\n  };\n}\n","import BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { CurrencyAmount, TokenAmount } from \"../module/amount\";\nimport { Currency } from \"../module/currency\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { Price } from \"../module/price\";\nimport { Token } from \"../module/token\";\nimport { SplToken, TokenJson } from \"../raydium/token/type\";\nimport { ReplaceType } from \"../raydium/type\";\nimport { parseBigNumberish } from \"./constant\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\n\nexport const BN_ZERO = new BN(0);\nexport const BN_ONE = new BN(1);\nexport const BN_TWO = new BN(2);\nexport const BN_THREE = new BN(3);\nexport const BN_FIVE = new BN(5);\nexport const BN_TEN = new BN(10);\nexport const BN_100 = new BN(100);\nexport const BN_1000 = new BN(1000);\nexport const BN_10000 = new BN(10000);\nexport type BigNumberish = BN | string | number | bigint;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\nexport function tenExponential(shift: BigNumberish): BN {\n  return BN_TEN.pow(parseBigNumberish(shift));\n}\n\n/**\n *\n * @example\n * getIntInfo(0.34) => { numerator: '34', denominator: '100'}\n * getIntInfo('0.34') //=> { numerator: '34', denominator: '100'}\n */\nexport function parseNumberInfo(n: Numberish | undefined): {\n  denominator: string;\n  numerator: string;\n  sign?: string;\n  int?: string;\n  dec?: string;\n} {\n  if (n === undefined) return { denominator: \"1\", numerator: \"0\" };\n  if (n instanceof BN) {\n    return { numerator: n.toString(), denominator: \"1\" };\n  }\n\n  if (n instanceof Fraction) {\n    return { denominator: n.denominator.toString(), numerator: n.numerator.toString() };\n  }\n\n  const s = String(n);\n  const [, sign = \"\", int = \"\", dec = \"\"] = s.replace(\",\", \"\").match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n  const denominator = \"1\" + \"0\".repeat(dec.length);\n  const numerator = sign + (int === \"0\" ? \"\" : int) + dec || \"0\";\n  return { denominator, numerator, sign, int, dec };\n}\n\n// round up\nexport function divCeil(a: BN, b: BN): BN {\n  // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n  // @ts-ignore\n  const dm = a.divmod(b);\n\n  // Fast case - exact division\n  if (dm.mod.isZero()) return dm.div;\n\n  // Round up\n  return dm.div.isNeg() ? dm.div.isubn(1) : dm.div.iaddn(1);\n}\n\nexport function shakeFractionDecimal(n: Fraction): string {\n  const [, sign = \"\", int = \"\"] = n.toFixed(2).match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n  return `${sign}${int}`;\n}\n\nexport function toBN(n: Numberish, decimal: BigNumberish = 0): BN {\n  if (n instanceof BN) return n;\n  return new BN(shakeFractionDecimal(toFraction(n).mul(BN_TEN.pow(new BN(String(decimal))))));\n}\n\nexport function toFraction(value: Numberish): Fraction {\n  //  to complete math format(may have decimal), not int\n  if (value instanceof Percent) return new Fraction(value.numerator, value.denominator);\n\n  if (value instanceof Price) return value.adjusted;\n\n  // to complete math format(may have decimal), not BN\n  if (value instanceof TokenAmount)\n    try {\n      return toFraction(value.toExact());\n    } catch {\n      return new Fraction(BN_ZERO);\n    }\n\n  // do not ideal with other fraction value\n  if (value instanceof Fraction) return value;\n\n  // wrap to Fraction\n  const n = String(value);\n  const details = parseNumberInfo(n);\n  return new Fraction(details.numerator, details.denominator);\n}\n\nexport function ceilDiv(tokenAmount: BN, feeNumerator: BN, feeDenominator: BN): BN {\n  return tokenAmount.mul(feeNumerator).add(feeDenominator).sub(new BN(1)).div(feeDenominator);\n}\n\nexport function floorDiv(tokenAmount: BN, feeNumerator: BN, feeDenominator: BN): BN {\n  return tokenAmount.mul(feeNumerator).div(feeDenominator);\n}\n\n/**\n * @example\n * toPercent(3.14) // => Percent { 314.00% }\n * toPercent(3.14, { alreadyDecimaled: true }) // => Percent {3.14%}\n */\nexport function toPercent(\n  n: Numberish,\n  options?: { /* usually used for backend data */ alreadyDecimaled?: boolean },\n): Percent {\n  const { numerator, denominator } = parseNumberInfo(n);\n  return new Percent(new BN(numerator), new BN(denominator).mul(options?.alreadyDecimaled ? new BN(100) : new BN(1)));\n}\n\nexport function toTokenPrice(params: {\n  token: TokenJson | Token | SplToken;\n  numberPrice: Numberish;\n  decimalDone?: boolean;\n}): Price {\n  const { token, numberPrice, decimalDone } = params;\n  const usdCurrency = new Token({ mint: \"\", decimals: 6, symbol: \"usd\", name: \"usd\", skipMint: true });\n  const { numerator, denominator } = parseNumberInfo(numberPrice);\n  const parsedNumerator = decimalDone ? new BN(numerator).mul(BN_TEN.pow(new BN(token.decimals))) : numerator;\n  const parsedDenominator = new BN(denominator).mul(BN_TEN.pow(new BN(usdCurrency.decimals)));\n\n  return new Price({\n    baseToken: usdCurrency,\n    denominator: parsedDenominator.toString(),\n    quoteToken: new Token({ ...token, skipMint: true, mint: \"\" }),\n    numerator: parsedNumerator.toString(),\n  });\n}\n\nexport function toUsdCurrency(amount: Numberish): CurrencyAmount {\n  const usdCurrency = new Currency({ decimals: 6, symbol: \"usd\", name: \"usd\" });\n  const amountBigNumber = toBN(mul(amount, 10 ** usdCurrency.decimals)!);\n  return new CurrencyAmount(usdCurrency, amountBigNumber);\n}\n\nexport function toTotalPrice(amount: Numberish | undefined, price: Price | undefined): CurrencyAmount {\n  if (!price || !amount) return toUsdCurrency(0);\n  return toUsdCurrency(mul(amount, price)!);\n}\n\nexport function decimalToFraction(n: Decimal | undefined): Fraction | undefined {\n  if (n == null) return undefined;\n  const { numerator, denominator } = parseNumberInfo(n.toString());\n  return new Fraction(numerator, denominator);\n}\n\nexport function isDecimal(val: unknown): boolean {\n  return val instanceof Decimal;\n}\n\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n  // @ts-expect-error no need type for inner code\n  return isDecimal(info)\n    ? decimalToFraction(info as any)\n    : Array.isArray(info)\n    ? info.map((k) => recursivelyDecimalToFraction(k))\n    : notInnerObject(info)\n    ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)]))\n    : info;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN } from \"../common/bignumber\";\nimport { createLogger, Logger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common\";\nimport { Currency } from \"./currency\";\nimport toFormat, { WrappedBig } from \"./formatter\";\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Raydium_amount\");\n\nconst Big = toFormat(_Big);\ntype Big = WrappedBig;\n\nexport function splitNumber(num: string, decimals: number): [string, string] {\n  let integral = \"0\";\n  let fractional = \"0\";\n\n  if (num.includes(\".\")) {\n    const splited = num.split(\".\");\n    if (splited.length === 2) {\n      [integral, fractional] = splited;\n      fractional = fractional.padEnd(decimals, \"0\");\n    } else {\n      logger.logWithError(`invalid number string, num: ${num}`);\n    }\n  } else {\n    integral = num;\n  }\n\n  // fix decimals is 0\n  return [integral, fractional.slice(0, decimals) || fractional];\n}\n\nexport class TokenAmount extends Fraction {\n  public readonly token: Token;\n  protected logger: Logger;\n\n  public constructor(token: Token, amount: BigNumberish, isRaw = true, name?: string) {\n    let parsedAmount = new BN(0);\n    const multiplier = BN_TEN.pow(new BN(token.decimals));\n\n    if (isRaw) {\n      parsedAmount = parseBigNumberish(amount);\n    } else {\n      let integralAmount = new BN(0);\n      let fractionalAmount = new BN(0);\n\n      // parse fractional string\n      if (typeof amount === \"string\" || typeof amount === \"number\" || typeof amount === \"bigint\") {\n        const [integral, fractional] = splitNumber(amount.toString(), token.decimals);\n        integralAmount = parseBigNumberish(integral);\n        fractionalAmount = parseBigNumberish(fractional);\n      }\n\n      integralAmount = integralAmount.mul(multiplier);\n      parsedAmount = integralAmount.add(fractionalAmount);\n    }\n\n    super(parsedAmount, multiplier);\n    this.logger = createLogger(name || \"TokenAmount\");\n    this.token = token;\n  }\n\n  public get raw(): BN {\n    return this.numerator;\n  }\n  public isZero(): boolean {\n    return this.raw.isZero();\n  }\n  public gt(other: TokenAmount): boolean {\n    if (!this.token.equals(other.token)) this.logger.logWithError(\"gt token not equals\");\n    return this.raw.gt(other.raw);\n  }\n\n  /**\n   * a less than b\n   */\n  public lt(other: TokenAmount): boolean {\n    if (!this.token.equals(other.token)) this.logger.logWithError(\"lt token not equals\");\n    return this.raw.lt(other.raw);\n  }\n\n  public add(other: TokenAmount): TokenAmount {\n    if (!this.token.equals(other.token)) this.logger.logWithError(\"add token not equals\");\n    return new TokenAmount(this.token, this.raw.add(other.raw));\n  }\n\n  public subtract(other: TokenAmount): TokenAmount {\n    if (!this.token.equals(other.token)) this.logger.logWithError(\"sub token not equals\");\n    return new TokenAmount(this.token, this.raw.sub(other.raw));\n  }\n\n  public toSignificant(\n    significantDigits = this.token.decimals,\n    format?: object,\n    rounding: Rounding = Rounding.ROUND_DOWN,\n  ): string {\n    return super.toSignificant(significantDigits, format, rounding);\n  }\n\n  /**\n   * To fixed\n   *\n   * @example\n   * ```\n   * 1 -> 1.000000000\n   * 1.234 -> 1.234000000\n   * 1.123456789876543 -> 1.123456789\n   * ```\n   */\n  public toFixed(\n    decimalPlaces = this.token.decimals,\n    format?: object,\n    rounding: Rounding = Rounding.ROUND_DOWN,\n  ): string {\n    if (decimalPlaces > this.token.decimals) this.logger.logWithError(\"decimals overflow\");\n    return super.toFixed(decimalPlaces, format, rounding);\n  }\n\n  /**\n   * To exact\n   *\n   * @example\n   * ```\n   * 1 -> 1\n   * 1.234 -> 1.234\n   * 1.123456789876543 -> 1.123456789\n   * ```\n   */\n  public toExact(format: object = { groupSeparator: \"\" }): string {\n    Big.DP = this.token.decimals;\n    return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(format);\n  }\n}\n\nexport class CurrencyAmount extends Fraction {\n  public readonly currency: Currency;\n  protected logger: Logger;\n\n  public constructor(currency: Currency, amount: BigNumberish, isRaw = true, name?: string) {\n    let parsedAmount = new BN(0);\n    const multiplier = BN_TEN.pow(new BN(currency.decimals));\n\n    if (isRaw) {\n      parsedAmount = parseBigNumberish(amount);\n    } else {\n      let integralAmount = new BN(0);\n      let fractionalAmount = new BN(0);\n\n      // parse fractional string\n      if (typeof amount === \"string\" || typeof amount === \"number\" || typeof amount === \"bigint\") {\n        const [integral, fractional] = splitNumber(amount.toString(), currency.decimals);\n        integralAmount = parseBigNumberish(integral);\n        fractionalAmount = parseBigNumberish(fractional);\n      }\n\n      integralAmount = integralAmount.mul(multiplier);\n      parsedAmount = integralAmount.add(fractionalAmount);\n    }\n\n    super(parsedAmount, multiplier);\n    this.logger = createLogger(name || \"TokenAmount\");\n    this.currency = currency;\n  }\n\n  public get raw(): BN {\n    return this.numerator;\n  }\n\n  public isZero(): boolean {\n    return this.raw.isZero();\n  }\n\n  /**\n   * a greater than b\n   */\n  public gt(other: CurrencyAmount): boolean {\n    if (!this.currency.equals(other.currency)) this.logger.logWithError(\"gt currency not equals\");\n    return this.raw.gt(other.raw);\n  }\n\n  /**\n   * a less than b\n   */\n  public lt(other: CurrencyAmount): boolean {\n    if (!this.currency.equals(other.currency)) this.logger.logWithError(\"lt currency not equals\");\n    return this.raw.lt(other.raw);\n  }\n\n  public add(other: CurrencyAmount): CurrencyAmount {\n    if (!this.currency.equals(other.currency)) this.logger.logWithError(\"add currency not equals\");\n    return new CurrencyAmount(this.currency, this.raw.add(other.raw));\n  }\n\n  public sub(other: CurrencyAmount): CurrencyAmount {\n    if (!this.currency.equals(other.currency)) this.logger.logWithError(\"sub currency not equals\");\n    return new CurrencyAmount(this.currency, this.raw.sub(other.raw));\n  }\n\n  public toSignificant(\n    significantDigits = this.currency.decimals,\n    format?: object,\n    rounding: Rounding = Rounding.ROUND_DOWN,\n  ): string {\n    return super.toSignificant(significantDigits, format, rounding);\n  }\n\n  /**\n   * To fixed\n   *\n   * @example\n   * ```\n   * 1 -> 1.000000000\n   * 1.234 -> 1.234000000\n   * 1.123456789876543 -> 1.123456789\n   * ```\n   */\n  public toFixed(\n    decimalPlaces = this.currency.decimals,\n    format?: object,\n    rounding: Rounding = Rounding.ROUND_DOWN,\n  ): string {\n    if (decimalPlaces > this.currency.decimals) this.logger.logWithError(\"decimals overflow\");\n\n    return super.toFixed(decimalPlaces, format, rounding);\n  }\n\n  /**\n   * To exact\n   *\n   * @example\n   * ```\n   * 1 -> 1\n   * 1.234 -> 1.234\n   * 1.123456789876543 -> 1.123456789\n   * ```\n   */\n  public toExact(format: object = { groupSeparator: \"\" }): string {\n    Big.DP = this.currency.decimals;\n    return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(format);\n  }\n}\n","import { get, set } from \"lodash\";\n\nexport type ModuleName = \"Common.Api\";\n\nexport enum LogLevel {\n  Error,\n  Warning,\n  Info,\n  Debug,\n}\nexport class Logger {\n  private logLevel: LogLevel;\n  private name: string;\n  constructor(params: { name: string; logLevel?: LogLevel }) {\n    this.logLevel = params.logLevel !== undefined ? params.logLevel : LogLevel.Error;\n    this.name = params.name;\n  }\n\n  set level(logLevel: LogLevel) {\n    this.logLevel = logLevel;\n  }\n  get time(): string {\n    return Date.now().toString();\n  }\n  get moduleName(): string {\n    return this.name;\n  }\n\n  private isLogLevel(level: LogLevel): boolean {\n    return level <= this.logLevel;\n  }\n\n  public error(...props): Logger {\n    if (!this.isLogLevel(LogLevel.Error)) return this;\n    console.error(this.time, this.name, \"sdk logger error\", ...props);\n    return this;\n  }\n\n  public logWithError(...props): Logger {\n    // this.error(...props)\n    const msg = props.map((arg) => (typeof arg === \"object\" ? JSON.stringify(arg) : arg)).join(\", \");\n    throw new Error(msg);\n  }\n\n  public warning(...props): Logger {\n    if (!this.isLogLevel(LogLevel.Warning)) return this;\n    console.warn(this.time, this.name, \"sdk logger warning\", ...props);\n    return this;\n  }\n\n  public info(...props): Logger {\n    if (!this.isLogLevel(LogLevel.Info)) return this;\n    console.info(this.time, this.name, \"sdk logger info\", ...props);\n    return this;\n  }\n\n  public debug(...props): Logger {\n    if (!this.isLogLevel(LogLevel.Debug)) return this;\n    console.debug(this.time, this.name, \"sdk logger debug\", ...props);\n    return this;\n  }\n}\n\nconst moduleLoggers: { [key in ModuleName]?: Logger } = {};\nconst moduleLevels: { [key in ModuleName]?: LogLevel } = {};\n\nexport function createLogger(moduleName: string): Logger {\n  let logger = get(moduleLoggers, moduleName);\n  if (!logger) {\n    // default level is error\n    const logLevel = get(moduleLevels, moduleName);\n\n    logger = new Logger({ name: moduleName, logLevel });\n    set(moduleLoggers, moduleName, logger);\n  }\n\n  return logger;\n}\n\nexport function setLoggerLevel(moduleName: string, level: LogLevel): void {\n  set(moduleLevels, moduleName, level);\n\n  const logger = get(moduleLoggers, moduleName);\n  if (logger) logger.level = level;\n}\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../raydium/type\";\nimport { WSOLMint, chunkArray, solToWSol } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { MINT_SIZE, TOKEN_PROGRAM_ID, getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\n\ninterface MultipleAccountsJsonRpcResponse {\n  jsonrpc: string;\n  id: string;\n  error?: {\n    code: number;\n    message: string;\n  };\n  result: {\n    context: { slot: number };\n    value: { data: Array<string>; executable: boolean; lamports: number; owner: string; rentEpoch: number }[];\n  };\n}\n\nexport interface GetMultipleAccountsInfoConfig {\n  batchRequest?: boolean;\n  commitment?: Commitment;\n  chunkCount?: number;\n}\n\nconst logger = createLogger(\"Raydium_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n  connection: Connection,\n  publicKeys: PublicKey[],\n  config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n  const {\n    batchRequest,\n    commitment = \"confirmed\",\n    chunkCount = 100,\n  } = {\n    batchRequest: false,\n    ...config,\n  };\n\n  const chunkedKeys = chunkArray(publicKeys, chunkCount);\n  let results: (AccountInfo<Buffer> | null)[][] = new Array(chunkedKeys.length).fill([]);\n\n  if (batchRequest) {\n    const batch = chunkedKeys.map((keys) => {\n      const args = connection._buildArgs([keys.map((key) => key.toBase58())], commitment, \"base64\");\n      return {\n        methodName: \"getMultipleAccounts\",\n        args,\n      };\n    });\n\n    const _batch = chunkArray(batch, 10);\n\n    const unsafeResponse: MultipleAccountsJsonRpcResponse[] = await (\n      await Promise.all(_batch.map(async (i) => await (connection as any)._rpcBatchRequest(i)))\n    ).flat();\n    results = unsafeResponse.map((unsafeRes: MultipleAccountsJsonRpcResponse) => {\n      if (unsafeRes.error)\n        logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${unsafeRes.error.message}`);\n\n      return unsafeRes.result.value.map((accountInfo) => {\n        if (accountInfo) {\n          const { data, executable, lamports, owner, rentEpoch } = accountInfo;\n\n          if (data.length !== 2 && data[1] !== \"base64\") logger.logWithError(`info must be base64 encoded, RPC_ERROR`);\n\n          return {\n            data: Buffer.from(data[0], \"base64\"),\n            executable,\n            lamports,\n            owner: new PublicKey(owner),\n            rentEpoch,\n          };\n        }\n        return null;\n      });\n    });\n  } else {\n    try {\n      results = (await Promise.all(\n        chunkedKeys.map((keys) => connection.getMultipleAccountsInfo(keys, commitment)),\n      )) as (AccountInfo<Buffer> | null)[][];\n    } catch (error) {\n      if (error instanceof Error) {\n        logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${error.message}`);\n      }\n    }\n  }\n\n  return results.flat();\n}\n\nexport async function getMultipleAccountsInfoWithCustomFlags<T extends { pubkey: PublicKey }>(\n  connection: Connection,\n  publicKeysWithCustomFlag: T[],\n  config?: GetMultipleAccountsInfoConfig,\n): Promise<({ accountInfo: AccountInfo<Buffer> | null } & T)[]> {\n  const multipleAccountsInfo = await getMultipleAccountsInfo(\n    connection,\n    publicKeysWithCustomFlag.map((o) => o.pubkey),\n    config,\n  );\n\n  return publicKeysWithCustomFlag.map((o, idx) => ({ ...o, accountInfo: multipleAccountsInfo[idx] }));\n}\n\nexport enum AccountType {\n  Uninitialized,\n  Mint,\n  Account,\n}\nexport const ACCOUNT_TYPE_SIZE = 1;\n\nexport async function fetchMultipleMintInfos({\n  connection,\n  mints,\n  config,\n}: {\n  connection: Connection;\n  mints: PublicKey[];\n  config?: { batchRequest?: boolean };\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n  if (mints.length === 0) return {};\n  const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n    connection,\n    mints.map((i) => ({ pubkey: solToWSol(i) })),\n    config,\n  );\n\n  const mintK: ReturnTypeFetchMultipleMintInfos = {};\n  for (const i of mintInfos) {\n    if (!i.accountInfo || i.accountInfo.data.length < MINT_SIZE) {\n      console.log(\"invalid mint account\", i.pubkey.toBase58());\n      continue;\n    }\n    const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n    mintK[i.pubkey.toString()] = {\n      ...t,\n      programId: i.accountInfo?.owner || TOKEN_PROGRAM_ID,\n      feeConfig: getTransferFeeConfig(t) ?? undefined,\n    };\n  }\n  mintK[PublicKey.default.toBase58()] = mintK[WSOLMint.toBase58()];\n\n  return mintK;\n}\n","import BN from \"bn.js\";\nimport { BigNumberish } from \"./bignumber\";\nimport { createLogger } from \"./logger\";\n\nexport enum Rounding {\n  ROUND_DOWN,\n  ROUND_HALF_UP,\n  ROUND_UP,\n}\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n  const logger = createLogger(\"Raydium_parseBigNumberish\");\n  // BN\n  if (value instanceof BN) {\n    return value;\n  }\n\n  if (typeof value === \"string\") {\n    if (value.match(/^-?[0-9]+$/)) {\n      return new BN(value);\n    }\n    logger.logWithError(`invalid BigNumberish string: ${value}`);\n  }\n\n  if (typeof value === \"number\") {\n    if (value % 1) {\n      logger.logWithError(`BigNumberish number underflow: ${value}`);\n    }\n\n    if (value >= MAX_SAFE || value <= -MAX_SAFE) {\n      logger.logWithError(`BigNumberish number overflow: ${value}`);\n    }\n\n    return new BN(String(value));\n  }\n\n  if (typeof value === \"bigint\") {\n    return new BN(value.toString());\n  }\n  logger.error(`invalid BigNumberish value: ${value}`);\n  return new BN(0); // never reach, because logWithError will throw error\n}","import { PublicKey } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { TokenInfo } from \"./type\";\n\nexport const SOL_INFO: TokenInfo = {\n  chainId: 101,\n  address: PublicKey.default.toBase58(),\n  programId: TOKEN_PROGRAM_ID.toBase58(),\n  decimals: 9,\n  symbol: \"SOL\",\n  name: \"solana\",\n  logoURI: `https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n  tags: [],\n  priority: 2,\n  type: \"raydium\",\n  extensions: {\n    coingeckoId: \"solana\",\n  },\n};\n\nexport const TOKEN_WSOL: TokenInfo = {\n  chainId: 101,\n  address: \"So11111111111111111111111111111111111111112\",\n  programId: TOKEN_PROGRAM_ID.toBase58(),\n  decimals: 9,\n  symbol: \"WSOL\",\n  name: \"Wrapped SOL\",\n  logoURI: `https://img-v1.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n  tags: [],\n  priority: 2,\n  type: \"raydium\",\n  extensions: {\n    coingeckoId: \"solana\",\n  },\n};\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { PublicKeyish, SOLMint, validateAndParsePublicKey } from \"../common/pubKey\";\nimport { TOKEN_WSOL } from \"../raydium/token/constant\";\n\n/**\n * A token is any fungible financial instrument on Solana, including SOL and all SPL tokens.\n */\nexport interface TokenProps {\n  mint: PublicKeyish;\n  decimals: number;\n  symbol?: string;\n  name?: string;\n  skipMint?: boolean;\n  isToken2022?: boolean;\n}\n\nexport class Token {\n  public readonly symbol?: string;\n  public readonly name?: string;\n  public readonly decimals: number;\n  public readonly isToken2022: boolean;\n\n  public readonly mint: PublicKey;\n  public static readonly WSOL: Token = new Token({\n    ...TOKEN_WSOL,\n    mint: TOKEN_WSOL.address,\n  });\n\n  /**\n   *\n   * @param mint - pass \"sol\" as mint will auto generate wsol token config\n   */\n  public constructor({ mint, decimals, symbol, name, skipMint = false, isToken2022 = false }: TokenProps) {\n    if (mint === SOLMint.toBase58() || (mint instanceof PublicKey && SOLMint.equals(mint))) {\n      this.decimals = TOKEN_WSOL.decimals;\n      this.symbol = TOKEN_WSOL.symbol;\n      this.name = TOKEN_WSOL.name;\n      this.mint = new PublicKey(TOKEN_WSOL.address);\n      this.isToken2022 = false;\n      return;\n    }\n\n    this.decimals = decimals;\n    this.symbol = symbol || mint.toString().substring(0, 6);\n    this.name = name || mint.toString().substring(0, 6);\n    this.mint = skipMint ? PublicKey.default : validateAndParsePublicKey({ publicKey: mint });\n    this.isToken2022 = isToken2022;\n  }\n\n  public equals(other: Token): boolean {\n    // short circuit on reference equality\n    if (this === other) {\n      return true;\n    }\n    return this.mint.equals(other.mint);\n  }\n}\n","import { AccountMeta, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\ninterface AccountMetaProps {\n  pubkey: PublicKey;\n  isSigner?: boolean;\n  isWritable?: boolean;\n}\n\nexport function accountMeta({ pubkey, isSigner = false, isWritable = true }: AccountMetaProps): AccountMeta {\n  return {\n    pubkey,\n    isWritable,\n    isSigner,\n  };\n}\n\nexport const commonSystemAccountMeta = [\n  accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n  accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n  accountMeta({ pubkey: SYSVAR_RENT_PUBKEY, isWritable: false }),\n];\n\nexport type PublicKeyish = PublicKey | string;\n\nexport function validateAndParsePublicKey({\n  publicKey: orgPubKey,\n  transformSol,\n}: {\n  publicKey: PublicKeyish;\n  transformSol?: boolean;\n}): PublicKey {\n  const publicKey = tryParsePublicKey(orgPubKey.toString());\n\n  if (publicKey instanceof PublicKey) {\n    if (transformSol && publicKey.equals(SOLMint)) return WSOLMint;\n    return publicKey;\n  }\n\n  if (transformSol && publicKey.toString() === SOLMint.toBase58()) return WSOLMint;\n\n  if (typeof publicKey === \"string\") {\n    if (publicKey === PublicKey.default.toBase58()) return PublicKey.default;\n    try {\n      const key = new PublicKey(publicKey);\n      return key;\n    } catch {\n      throw new Error(\"invalid public key\");\n    }\n  }\n\n  throw new Error(\"invalid public key\");\n}\n\nexport function tryParsePublicKey(v: string): PublicKey | string {\n  try {\n    return new PublicKey(v);\n  } catch (e) {\n    return v;\n  }\n}\n\nexport const MEMO_PROGRAM_ID = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const MEMO_PROGRAM_ID2 = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const RENT_PROGRAM_ID = new PublicKey(\"SysvarRent111111111111111111111111111111111\");\nexport const CLOCK_PROGRAM_ID = new PublicKey(\"SysvarC1ock11111111111111111111111111111111\");\nexport const METADATA_PROGRAM_ID = new PublicKey(\"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s\");\nexport const INSTRUCTION_PROGRAM_ID = new PublicKey(\"Sysvar1nstructions1111111111111111111111111\");\nexport const SYSTEM_PROGRAM_ID = SystemProgram.programId;\n\nexport const RAYMint = new PublicKey(\"4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R\");\nexport const PAIMint = new PublicKey(\"Ea5SjE2Y6yvCeW5dYTn7PYMuW5ikXkvbGdcmSnXeaLjS\");\nexport const SRMMint = new PublicKey(\"SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt\");\nexport const USDCMint = new PublicKey(\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\");\nexport const USDTMint = new PublicKey(\"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB\");\nexport const mSOLMint = new PublicKey(\"mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So\");\nexport const stSOLMint = new PublicKey(\"7dHbWXmci3dT8UFYWYZweBLXgycu7Y3iL6trKn1Y7ARj\");\nexport const USDHMint = new PublicKey(\"USDH1SM1ojwWUga67PGrgFWUHibbjqMvuMaDkRJTgkX\");\nexport const NRVMint = new PublicKey(\"NRVwhjBQiUPYtfDT5zRBVJajzFQHaBUNtC7SNVvqRFa\");\nexport const ANAMint = new PublicKey(\"ANAxByE6G2WjFp7A4NqtWYXb3mgruyzZYg3spfxe6Lbo\");\nexport const ETHMint = new PublicKey(\"7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs\");\nexport const WSOLMint = new PublicKey(\"So11111111111111111111111111111111111111112\");\nexport const SOLMint = PublicKey.default;\n\nexport function solToWSol(mint: PublicKeyish): PublicKey {\n  return validateAndParsePublicKey({ publicKey: mint, transformSol: true });\n}\n","import { SOL_INFO } from \"../raydium/token/constant\";\n\nimport { Token } from \"./token\";\n\ninterface CurrencyProps {\n  decimals: number;\n  symbol?: string;\n  name?: string;\n}\n/**\n * A currency is any fungible financial instrument on Solana, including SOL and all SPL tokens.\n * The only instance of the base class `Currency` is SOL.\n */\nexport class Currency {\n  public readonly symbol?: string;\n  public readonly name?: string;\n  public readonly decimals: number;\n\n  /**\n   * The only instance of the base class `Currency`.\n   */\n  public static readonly SOL: Currency = new Currency(SOL_INFO);\n\n  /**\n   * Constructs an instance of the base class `Currency`. The only instance of the base class `Currency` is `Currency.SOL`.\n   * @param decimals - decimals of the currency\n   * @param symbol - symbol of the currency\n   * @param name - name of the currency\n   */\n  public constructor({ decimals, symbol = \"UNKNOWN\", name = \"UNKNOWN\" }: CurrencyProps) {\n    this.decimals = decimals;\n    this.symbol = symbol;\n    this.name = name;\n  }\n\n  public equals(other: Currency): boolean {\n    return this === other;\n  }\n}\n\n/**\n * Compares two currencies for equality\n */\nexport function currencyEquals(currencyA: Currency, currencyB: Currency): boolean {\n  if (currencyA instanceof Token && currencyB instanceof Token) {\n    return currencyA.equals(currencyB);\n  } else if (currencyA instanceof Token || currencyB instanceof Token) {\n    return false;\n  } else {\n    return currencyA === currencyB;\n  }\n}\n","import Big, { BigConstructor, BigSource, RoundingMode } from \"big.js\";\nimport Decimal, { Config, Numeric } from \"decimal.js-light\";\nimport _toFarmat from \"toformat\";\n\ntype TakeStatic<T> = { [P in keyof T]: T[P] };\ninterface FormatOptions {\n  decimalSeparator?: string;\n  groupSeparator?: string;\n  groupSize?: number;\n  fractionGroupSeparator?: string;\n  fractionGroupSize?: number;\n}\ninterface WrappedBigConstructor extends TakeStatic<BigConstructor> {\n  new (value: BigSource): WrappedBig;\n  (value: BigSource): WrappedBig;\n  (): WrappedBigConstructor;\n\n  format: FormatOptions;\n}\nexport interface WrappedBig extends Big {\n  add(n: BigSource): WrappedBig;\n  abs(): WrappedBig;\n  div(n: BigSource): WrappedBig;\n  minus(n: BigSource): WrappedBig;\n  mod(n: BigSource): WrappedBig;\n  mul(n: BigSource): WrappedBig;\n  plus(n: BigSource): WrappedBig;\n  pow(exp: number): WrappedBig;\n  round(dp?: number, rm?: RoundingMode): WrappedBig;\n  sqrt(): WrappedBig;\n  sub(n: BigSource): WrappedBig;\n  times(n: BigSource): WrappedBig;\n  toFormat(): string;\n  toFormat(options: FormatOptions): string;\n  toFormat(fractionLength: number): string;\n  toFormat(fractionLength: number, options: FormatOptions): string;\n  toFormat(fractionLength: number, missionUnknown: number): string;\n  toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\ntype DecimalConstructor = typeof Decimal;\ninterface WrappedDecimalConstructor extends TakeStatic<DecimalConstructor> {\n  new (value: Numeric): WrappedDecimal;\n  clone(config?: Config): WrappedDecimalConstructor;\n  config(config: Config): WrappedDecimal;\n  set(config: Config): WrappedDecimal;\n  format: FormatOptions;\n}\nexport interface WrappedDecimal extends Decimal {\n  absoluteValue(): WrappedDecimal;\n  abs(): WrappedDecimal;\n  dividedBy(y: Numeric): WrappedDecimal;\n  div(y: Numeric): WrappedDecimal;\n  dividedToIntegerBy(y: Numeric): WrappedDecimal;\n  idiv(y: Numeric): WrappedDecimal;\n  logarithm(base?: Numeric): WrappedDecimal;\n  log(base?: Numeric): WrappedDecimal;\n  minus(y: Numeric): WrappedDecimal;\n  sub(y: Numeric): WrappedDecimal;\n  modulo(y: Numeric): WrappedDecimal;\n  mod(y: Numeric): WrappedDecimal;\n  naturalExponetial(): WrappedDecimal;\n  exp(): WrappedDecimal;\n  naturalLogarithm(): WrappedDecimal;\n  ln(): WrappedDecimal;\n  negated(): WrappedDecimal;\n  neg(): WrappedDecimal;\n  plus(y: Numeric): WrappedDecimal;\n  add(y: Numeric): WrappedDecimal;\n  squareRoot(): WrappedDecimal;\n  sqrt(): WrappedDecimal;\n  times(y: Numeric): WrappedDecimal;\n  mul(y: Numeric): WrappedDecimal;\n  toWrappedDecimalPlaces(dp?: number, rm?: number): WrappedDecimal;\n  todp(dp?: number, rm?: number): WrappedDecimal;\n  toInteger(): WrappedDecimal;\n  toint(): WrappedDecimal;\n  toPower(y: Numeric): WrappedDecimal;\n  pow(y: Numeric): WrappedDecimal;\n  toSignificantDigits(sd?: number, rm?: number): WrappedDecimal;\n  tosd(sd?: number, rm?: number): WrappedDecimal;\n  toFormat(options: FormatOptions): string;\n  toFormat(fractionLength: number): string;\n  toFormat(fractionLength: number, options: FormatOptions): string;\n  toFormat(fractionLength: number, missionUnknown: number): string;\n  toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\nconst toFormat: {\n  (fn: BigConstructor): WrappedBigConstructor;\n  (fn: DecimalConstructor): WrappedDecimalConstructor;\n} = _toFarmat;\nexport default toFormat;\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common/constant\";\nimport toFormat, { WrappedBig } from \"./formatter\";\n\nconst logger = createLogger(\"module/fraction\");\n\nconst Big = toFormat(_Big);\ntype Big = WrappedBig;\n\nconst Decimal = toFormat(_Decimal);\n\nconst toSignificantRounding = {\n  [Rounding.ROUND_DOWN]: Decimal.ROUND_DOWN,\n  [Rounding.ROUND_HALF_UP]: Decimal.ROUND_HALF_UP,\n  [Rounding.ROUND_UP]: Decimal.ROUND_UP,\n};\n\nconst toFixedRounding = {\n  [Rounding.ROUND_DOWN]: _Big.roundDown,\n  [Rounding.ROUND_HALF_UP]: _Big.roundHalfUp,\n  [Rounding.ROUND_UP]: _Big.roundUp,\n};\n\nexport class Fraction {\n  public readonly numerator: BN;\n  public readonly denominator: BN;\n\n  public constructor(numerator: BigNumberish, denominator: BigNumberish = new BN(1)) {\n    this.numerator = parseBigNumberish(numerator);\n    this.denominator = parseBigNumberish(denominator);\n  }\n\n  public get quotient(): BN {\n    return this.numerator.div(this.denominator);\n  }\n\n  public invert(): Fraction {\n    return new Fraction(this.denominator, this.numerator);\n  }\n\n  public add(other: Fraction | BigNumberish): Fraction {\n    const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n    if (this.denominator.eq(otherParsed.denominator)) {\n      return new Fraction(this.numerator.add(otherParsed.numerator), this.denominator);\n    }\n\n    return new Fraction(\n      this.numerator.mul(otherParsed.denominator).add(otherParsed.numerator.mul(this.denominator)),\n      this.denominator.mul(otherParsed.denominator),\n    );\n  }\n\n  public sub(other: Fraction | BigNumberish): Fraction {\n    const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n    if (this.denominator.eq(otherParsed.denominator)) {\n      return new Fraction(this.numerator.sub(otherParsed.numerator), this.denominator);\n    }\n\n    return new Fraction(\n      this.numerator.mul(otherParsed.denominator).sub(otherParsed.numerator.mul(this.denominator)),\n      this.denominator.mul(otherParsed.denominator),\n    );\n  }\n\n  public mul(other: Fraction | BigNumberish): Fraction {\n    const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n    return new Fraction(this.numerator.mul(otherParsed.numerator), this.denominator.mul(otherParsed.denominator));\n  }\n\n  public div(other: Fraction | BigNumberish): Fraction {\n    const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n    return new Fraction(this.numerator.mul(otherParsed.denominator), this.denominator.mul(otherParsed.numerator));\n  }\n\n  public toSignificant(\n    significantDigits: number,\n    format: object = { groupSeparator: \"\" },\n    rounding: Rounding = Rounding.ROUND_HALF_UP,\n  ): string {\n    if (!Number.isInteger(significantDigits)) logger.logWithError(`${significantDigits} is not an integer.`);\n    if (significantDigits <= 0) logger.logWithError(`${significantDigits} is not positive.`);\n\n    Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] });\n    const quotient = new Decimal(this.numerator.toString())\n      .div(this.denominator.toString())\n      .toSignificantDigits(significantDigits);\n    return quotient.toFormat(quotient.decimalPlaces(), format);\n  }\n\n  public toFixed(\n    decimalPlaces: number,\n    format: object = { groupSeparator: \"\" },\n    rounding: Rounding = Rounding.ROUND_HALF_UP,\n  ): string {\n    if (!Number.isInteger(decimalPlaces)) logger.logWithError(`${decimalPlaces} is not an integer.`);\n    if (decimalPlaces < 0) logger.logWithError(`${decimalPlaces} is negative.`);\n\n    Big.DP = decimalPlaces;\n    Big.RM = toFixedRounding[rounding] || 1;\n    return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);\n  }\n\n  public isZero(): boolean {\n    return this.numerator.isZero();\n  }\n}\n","import BN from \"bn.js\";\nimport { Rounding } from \"../common\";\nimport { Fraction } from \"./fraction\";\n\nexport const _100_PERCENT = new Fraction(new BN(100));\n\nexport class Percent extends Fraction {\n  public toSignificant(significantDigits = 5, format?: object, rounding?: Rounding): string {\n    return this.mul(_100_PERCENT).toSignificant(significantDigits, format, rounding);\n  }\n\n  public toFixed(decimalPlaces = 2, format?: object, rounding?: Rounding): string {\n    return this.mul(_100_PERCENT).toFixed(decimalPlaces, format, rounding);\n  }\n}\n","import { Rounding } from \"../common\";\nimport { BigNumberish, tenExponential } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"Raydium_price\");\n\ninterface PriceProps {\n  baseToken: Token;\n  denominator: BigNumberish;\n  quoteToken: Token;\n  numerator: BigNumberish;\n}\n\nexport class Price extends Fraction {\n  public readonly baseToken: Token; // input i.e. denominator\n  public readonly quoteToken: Token; // output i.e. numerator\n  // used to adjust the raw fraction w/r/t the decimals of the {base,quote}Token\n  public readonly scalar: Fraction;\n\n  // denominator and numerator _must_ be raw, i.e. in the native representation\n  public constructor(params: PriceProps) {\n    const { baseToken, quoteToken, numerator, denominator } = params;\n    super(numerator, denominator);\n\n    this.baseToken = baseToken;\n    this.quoteToken = quoteToken;\n    this.scalar = new Fraction(tenExponential(baseToken.decimals), tenExponential(quoteToken.decimals));\n  }\n\n  public get raw(): Fraction {\n    return new Fraction(this.numerator, this.denominator);\n  }\n\n  public get adjusted(): Fraction {\n    return super.mul(this.scalar);\n  }\n\n  public invert(): Price {\n    return new Price({\n      baseToken: this.quoteToken,\n      quoteToken: this.baseToken,\n      denominator: this.numerator,\n      numerator: this.denominator,\n    });\n  }\n\n  public mul(other: Price): Price {\n    if (this.quoteToken !== other.baseToken) logger.logWithError(\"mul token not equals\");\n\n    const fraction = super.mul(other);\n    return new Price({\n      baseToken: this.baseToken,\n      quoteToken: other.quoteToken,\n      denominator: fraction.denominator,\n      numerator: fraction.numerator,\n    });\n  }\n\n  public toSignificant(significantDigits = this.quoteToken.decimals, format?: object, rounding?: Rounding): string {\n    return this.adjusted.toSignificant(significantDigits, format, rounding);\n  }\n\n  public toFixed(decimalPlaces = this.quoteToken.decimals, format?: object, rounding?: Rounding): string {\n    return this.adjusted.toFixed(decimalPlaces, format, rounding);\n  }\n}\n","/**\n * https://youmightnotneed.com/lodash/\n */\n\nexport function chunkArray<T>(arr: T[], chunkSize = 1, cache: T[][] = []): T[][] {\n  const tmp = [...arr];\n  if (chunkSize <= 0) return cache;\n  while (tmp.length) cache.push(tmp.splice(0, chunkSize));\n  return cache;\n}\n\nexport function intersection<T>(arr: T[], ...args: T[][]): T[] {\n  return arr.filter((item) => args.every((arr) => arr.includes(item)));\n}\n\nexport function xor<T>(arr: T[], ...args: T[][]): T[] {\n  return arr.filter((item) => args.every((arr) => !arr.includes(item)));\n}\n\nexport function uniq<T>(arr: T[]): T[] {\n  return [...new Set(arr)];\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { findProgramAddress } from \"./txTool/txUtils\";\n\nexport function getATAAddress(\n  owner: PublicKey,\n  mint: PublicKey,\n  programId?: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress(\n    [owner.toBuffer(), (programId ?? TOKEN_PROGRAM_ID).toBuffer(), mint.toBuffer()],\n    new PublicKey(\"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\"),\n  );\n}\n","import {\n  Commitment,\n  ComputeBudgetProgram,\n  Connection,\n  EpochInfo,\n  Keypair,\n  PublicKey,\n  SimulatedTransactionResponse,\n  Transaction,\n  TransactionInstruction,\n  TransactionMessage,\n  VersionedTransaction,\n} from \"@solana/web3.js\";\n\nimport { createLogger } from \"../logger\";\nimport { CacheLTA } from \"./lookupTable\";\nimport { InstructionType } from \"./txType\";\n\nimport { ComputeBudgetConfig } from \"../../raydium/type\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nconst logger = createLogger(\"Raydium_txUtil\");\n\nexport const MAX_BASE64_SIZE = 1644;\n\nexport function addComputeBudget(config: ComputeBudgetConfig): {\n  instructions: TransactionInstruction[];\n  instructionTypes: string[];\n} {\n  const ins: TransactionInstruction[] = [];\n  const insTypes: string[] = [];\n  if (config.microLamports) {\n    ins.push(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: config.microLamports }));\n    insTypes.push(InstructionType.SetComputeUnitPrice);\n  }\n  if (config.units) {\n    ins.push(ComputeBudgetProgram.setComputeUnitLimit({ units: config.units }));\n    insTypes.push(InstructionType.SetComputeUnitLimit);\n  }\n\n  return {\n    instructions: ins,\n    instructionTypes: insTypes,\n  };\n}\n\nexport async function getRecentBlockHash(connection: Connection, propsCommitment?: Commitment): Promise<string> {\n  const commitment = propsCommitment ?? \"confirmed\";\n  return (await connection.getLatestBlockhash?.({ commitment }))?.blockhash;\n}\n\nexport async function confirmTransaction(connection: Connection, txId: string): Promise<string> {\n  connection.getSignatureStatuses([txId]);\n  return new Promise((resolve, reject) => {\n    const id = setTimeout(reject, 60 * 1000);\n    connection.onSignature(\n      txId,\n      (signatureResult) => {\n        clearTimeout(id);\n        if (!signatureResult.err) {\n          resolve(\"\");\n          return;\n        }\n        reject(Object.assign(signatureResult.err, { txId }));\n      },\n      \"confirmed\",\n    );\n  });\n}\n\n/**\n * Forecast transaction size\n */\nexport function forecastTransactionSize(instructions: TransactionInstruction[], signers: PublicKey[]): boolean {\n  if (instructions.length < 1) logger.logWithError(`no instructions provided: ${instructions.toString()}`);\n  if (signers.length < 1) logger.logWithError(`no signers provided:, ${signers.toString()}`);\n\n  const transaction = new Transaction();\n  transaction.recentBlockhash = \"11111111111111111111111111111111\";\n  transaction.feePayer = signers[0];\n  transaction.add(...instructions);\n\n  try {\n    return Buffer.from(transaction.serialize({ verifySignatures: false })).toString(\"base64\").length < MAX_BASE64_SIZE;\n  } catch (error) {\n    return false;\n  }\n}\n\n/**\n * Simulates multiple instruction\n */\n/**\n * Simulates multiple instruction\n */\nexport async function simulateMultipleInstruction(\n  connection: Connection,\n  instructions: TransactionInstruction[],\n  keyword: string,\n  batchRequest = true,\n): Promise<string[]> {\n  const feePayer = new PublicKey(\"RaydiumSimuLateTransaction11111111111111111\");\n\n  const transactions: Transaction[] = [];\n\n  let transaction = new Transaction();\n  transaction.feePayer = feePayer;\n\n  for (const instruction of instructions) {\n    if (!forecastTransactionSize([...transaction.instructions, instruction], [feePayer])) {\n      transactions.push(transaction);\n      transaction = new Transaction();\n      transaction.feePayer = feePayer;\n    }\n    transaction.add(instruction);\n  }\n  if (transaction.instructions.length > 0) {\n    transactions.push(transaction);\n  }\n\n  let results: SimulatedTransactionResponse[] = [];\n\n  try {\n    results = await simulateTransaction(connection, transactions, batchRequest);\n    if (results.find((i) => i.err !== null)) throw Error(\"rpc simulateTransaction error\");\n  } catch (error) {\n    if (error instanceof Error) {\n      logger.logWithError(\"failed to simulate for instructions\", \"RPC_ERROR\", {\n        message: error.message,\n      });\n    }\n  }\n\n  const logs: string[] = [];\n  for (const result of results) {\n    logger.debug(\"simulate result:\", result);\n\n    if (result.logs) {\n      const filteredLog = result.logs.filter((log) => log && log.includes(keyword));\n      logger.debug(\"filteredLog:\", logs);\n      if (!filteredLog.length) logger.logWithError(\"simulate log not match keyword\", \"keyword\", keyword);\n      logs.push(...filteredLog);\n    }\n  }\n\n  return logs;\n}\n\nexport function parseSimulateLogToJson(log: string, keyword: string): any {\n  const results = log.match(/{[\"\\w:,]+}/g);\n  if (!results || results.length !== 1) {\n    return logger.logWithError(`simulate log fail to match json, keyword: ${keyword}`);\n  }\n\n  return results[0];\n}\n\nexport function parseSimulateValue(log: string, key: string): any {\n  const reg = new RegExp(`\"${key}\":(\\\\d+)`, \"g\");\n\n  const results = reg.exec(log);\n  if (!results || results.length !== 2) {\n    return logger.logWithError(`simulate log fail to match key\", key: ${key}`);\n  }\n\n  return results[1];\n}\n\nexport interface ProgramAddress {\n  publicKey: PublicKey;\n  nonce: number;\n}\nexport function findProgramAddress(\n  seeds: Array<Buffer | Uint8Array>,\n  programId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  const [publicKey, nonce] = PublicKey.findProgramAddressSync(seeds, programId);\n  return { publicKey, nonce };\n}\n\nexport async function simulateTransaction(\n  connection: Connection,\n  transactions: Transaction[],\n  batchRequest?: boolean,\n): Promise<any[]> {\n  let results: any[] = [];\n  if (batchRequest) {\n    const getLatestBlockhash = await connection.getLatestBlockhash();\n\n    const encodedTransactions: string[] = [];\n    for (const transaction of transactions) {\n      transaction.recentBlockhash = getLatestBlockhash.blockhash;\n      transaction.lastValidBlockHeight = getLatestBlockhash.lastValidBlockHeight;\n\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      const message = transaction._compile();\n      const signData = message.serialize();\n\n      // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n      // @ts-ignore\n      const wireTransaction = transaction._serialize(signData);\n      const encodedTransaction = wireTransaction.toString(\"base64\");\n\n      encodedTransactions.push(encodedTransaction);\n    }\n\n    const batch = encodedTransactions.map((keys) => {\n      const args = connection._buildArgs([keys], undefined, \"base64\");\n      return {\n        methodName: \"simulateTransaction\",\n        args,\n      };\n    });\n\n    const reqData: { methodName: string; args: any[] }[][] = [];\n    const itemReqIndex = 20;\n    for (let i = 0; i < Math.ceil(batch.length / itemReqIndex); i++) {\n      reqData.push(batch.slice(i * itemReqIndex, (i + 1) * itemReqIndex));\n    }\n    // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n    // @ts-ignore\n    results = await (\n      await Promise.all(\n        reqData.map(async (i) => (await (connection as any)._rpcBatchRequest(i)).map((ii) => ii.result.value)),\n      )\n    ).flat();\n  } else {\n    try {\n      results = await Promise.all(\n        transactions.map(async (transaction) => await (await connection.simulateTransaction(transaction)).value),\n      );\n    } catch (error) {\n      if (error instanceof Error) {\n        logger.logWithError(\"failed to get info for multiple accounts\", \"RPC_ERROR\", {\n          message: error.message,\n        });\n      }\n    }\n  }\n\n  return results;\n}\n\nexport function checkLegacyTxSize({\n  instructions,\n  payer,\n  signers,\n}: {\n  instructions: TransactionInstruction[];\n  payer: PublicKey;\n  signers: PublicKey[];\n}): boolean {\n  return forecastTransactionSize(instructions, [payer, ...signers]);\n}\n\nexport function checkV0TxSize({\n  instructions,\n  payer,\n  lookupTableAddressAccount,\n  recentBlockhash = Keypair.generate().publicKey.toString(),\n}: {\n  instructions: TransactionInstruction[];\n  payer: PublicKey;\n  lookupTableAddressAccount?: CacheLTA;\n  recentBlockhash?: string;\n}): boolean {\n  const transactionMessage = new TransactionMessage({\n    payerKey: payer,\n    recentBlockhash,\n    instructions,\n  });\n\n  const messageV0 = transactionMessage.compileToV0Message(Object.values(lookupTableAddressAccount ?? {}));\n  try {\n    const buildLength = Buffer.from(new VersionedTransaction(messageV0).serialize()).toString(\"base64\").length;\n    return buildLength < MAX_BASE64_SIZE;\n  } catch (error) {\n    return false;\n  }\n}\n\nlet epochInfoCache: { time: number; data?: EpochInfo } = {\n  time: 0,\n  data: undefined,\n};\n\nexport async function getEpochInfo(connection: Connection): Promise<EpochInfo> {\n  if (!epochInfoCache.data || (Date.now() - epochInfoCache.time) / 1000 > 30) {\n    const data = await connection.getEpochInfo();\n    epochInfoCache = {\n      time: Date.now(),\n      data,\n    };\n    return data;\n  } else {\n    return epochInfoCache.data;\n  }\n}\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {\n  if (Buffer.isBuffer(arr)) {\n    return arr;\n  } else if (arr instanceof Uint8Array) {\n    return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n  } else {\n    return Buffer.from(arr);\n  }\n};\n\nexport const txToBase64 = (transaction: Transaction | VersionedTransaction): string => {\n  let serialized = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });\n  if (transaction instanceof VersionedTransaction) serialized = toBuffer(serialized);\n  try {\n    return serialized instanceof Buffer ? serialized.toString(\"base64\") : Buffer.from(serialized).toString(\"base64\");\n  } catch {\n    return serialized.toString(\"base64\");\n  }\n};\n\nexport function printSimulate(transactions: Transaction[] | VersionedTransaction[]): string[] {\n  const allBase64: string[] = [];\n  transactions.forEach((transaction) => {\n    if (transaction instanceof Transaction) {\n      if (!transaction.recentBlockhash) transaction.recentBlockhash = TOKEN_PROGRAM_ID.toBase58();\n      if (!transaction.feePayer) transaction.feePayer = Keypair.generate().publicKey;\n    }\n    allBase64.push(txToBase64(transaction));\n  });\n  console.log(\"simulate tx string:\", allBase64);\n\n  return allBase64;\n}\n\nexport function transformTxToBase64(tx: Transaction | VersionedTransaction): string {\n  let serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });\n  if (tx instanceof VersionedTransaction) serialized = toBuffer(serialized);\n  return serialized.toString(\"base64\");\n}\n","export enum TxVersion {\n  \"V0\",\n  \"LEGACY\",\n}\n\nexport const InstructionType = {\n  CreateAccount: \"CreateAccount\",\n  InitAccount: \"InitAccount\",\n  CreateATA: \"CreateATA\",\n  CloseAccount: \"CloseAccount\",\n  TransferAmount: \"TransferAmount\",\n  InitMint: \"InitMint\",\n  MintTo: \"MintTo\",\n\n  InitMarket: \"InitMarket\", // create market main ins\n  Util1216OwnerClaim: \"Util1216OwnerClaim\", // owner claim token ins\n\n  SetComputeUnitPrice: \"SetComputeUnitPrice\",\n  SetComputeUnitLimit: \"SetComputeUnitLimit\",\n\n  // CLMM\n  ClmmCreatePool: \"ClmmCreatePool\",\n  ClmmOpenPosition: \"ClmmOpenPosition\",\n  ClmmIncreasePosition: \"ClmmIncreasePosition\",\n  ClmmDecreasePosition: \"ClmmDecreasePosition\",\n  ClmmClosePosition: \"ClmmClosePosition\",\n  ClmmSwapBaseIn: \"ClmmSwapBaseIn\",\n  ClmmSwapBaseOut: \"ClmmSwapBaseOut\",\n  ClmmInitReward: \"ClmmInitReward\",\n  ClmmSetReward: \"ClmmSetReward\",\n  ClmmCollectReward: \"ClmmCollectReward\",\n  ClmmLockPosition: \"ClmmLockPosition\",\n  ClmmHarvestLockPosition: \"ClmmHarvestLockPosition\",\n\n  AmmV4Swap: \"AmmV4Swap\",\n  AmmV4AddLiquidity: \"AmmV4AddLiquidity\",\n  AmmV4RemoveLiquidity: \"AmmV4RemoveLiquidity\",\n  AmmV4SimulatePoolInfo: \"AmmV4SimulatePoolInfo\",\n  AmmV4SwapBaseIn: \"AmmV4SwapBaseIn\",\n  AmmV4SwapBaseOut: \"AmmV4SwapBaseOut\",\n  AmmV4CreatePool: \"AmmV4CreatePool\",\n  AmmV4InitPool: \"AmmV4InitPool\",\n\n  AmmV5AddLiquidity: \"AmmV5AddLiquidity\",\n  AmmV5RemoveLiquidity: \"AmmV5RemoveLiquidity\",\n  AmmV5SimulatePoolInfo: \"AmmV5SimulatePoolInfo\",\n  AmmV5SwapBaseIn: \"AmmV5SwapBaseIn\",\n  AmmV5SwapBaseOut: \"AmmV5SwapBaseOut\",\n\n  RouteSwap: \"RouteSwap\",\n  RouteSwap1: \"RouteSwap1\",\n  RouteSwap2: \"RouteSwap2\",\n\n  FarmV3Deposit: \"FarmV3Deposit\",\n  FarmV3Withdraw: \"FarmV3Withdraw\",\n  FarmV3CreateLedger: \"FarmV3CreateLedger\",\n\n  FarmV4Withdraw: \"FarmV4Withdraw\",\n\n  FarmV5Deposit: \"FarmV5Deposit\",\n  FarmV5Withdraw: \"FarmV5Withdraw\",\n  FarmV5CreateLedger: \"FarmV5CreateLedger\",\n\n  FarmV6Deposit: \"FarmV6Deposit\",\n  FarmV6Withdraw: \"FarmV6Withdraw\",\n  FarmV6Create: \"FarmV6Create\",\n  FarmV6Restart: \"FarmV6Restart\",\n  FarmV6CreatorAddReward: \"FarmV6CreatorAddReward\",\n  FarmV6CreatorWithdraw: \"FarmV6CreatorWithdraw\",\n\n  CpmmCreatePool: \"CpmmCreatePool\",\n  CpmmAddLiquidity: \"CpmmAddLiquidity\",\n  CpmmWithdrawLiquidity: \"CpmmWithdrawLiquidity\",\n  CpmmSwapBaseIn: \"CpmmSwapBaseIn\",\n  CpmmSwapBaseOut: \"CpmmSwapBaseOut\",\n\n  CpmmLockLp: \"CpmmLockLp\",\n  CpmmCollectLockFee: \"CpmmCollectLockFee\",\n  TransferTip: \"TransferTip\",\n};\n","import { PublicKey } from \"@solana/web3.js\";\n\n// raydium\nexport const FARM_PROGRAM_ID_V3 = new PublicKey(\"EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q\");\n// temp fusion\nexport const FARM_PROGRAM_ID_V4 = new PublicKey(\"CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T\");\n// \"fusion\"\nexport const FARM_PROGRAM_ID_V5 = new PublicKey(\"9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z\");\n// echosystem\nexport const FARM_PROGRAM_ID_V6 = new PublicKey(\"FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG\");\n\nexport const UTIL1216 = new PublicKey(\"CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS\");\n\nexport const OPEN_BOOK_PROGRAM = new PublicKey(\"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\");\nexport const SERUM_PROGRAM_ID_V3 = new PublicKey(\"9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin\");\n\nexport const AMM_V4 = new PublicKey(\"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8\");\nexport const AMM_STABLE = new PublicKey(\"5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h\");\nexport const LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL = new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\");\nexport const CLMM_PROGRAM_ID = new PublicKey(\"CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK\");\nexport const CLMM_LOCK_PROGRAM_ID = new PublicKey(\"LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE\");\nexport const CLMM_LOCK_AUTH_ID = new PublicKey(\"kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy\");\n\nexport const Router = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\");\nexport const FEE_DESTINATION_ID = new PublicKey(\"7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5\");\n\nexport const IDO_PROGRAM_ID_V1 = new PublicKey(\"6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF\");\nexport const IDO_PROGRAM_ID_V2 = new PublicKey(\"CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH\");\nexport const IDO_PROGRAM_ID_V3 = new PublicKey(\"9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC\");\nexport const IDO_PROGRAM_ID_V4 = new PublicKey(\"DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi\");\n\nexport const CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"8dJuKxXufKDynREfeu5zkbSsVA69p7BpvHu62kUgwE3H\");\nexport const CREATE_CPMM_POOL_AUTH = new PublicKey(\"DDGbigvGH49guY7PaaSdaNd3FiF5fyMzywzkF35bjZz7\");\nexport const CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"DDGbigvGH49guY7PaaSdaNd3FiF5fyMzywzkF35bjZz7\");\n\nexport const DEV_CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW\");\nexport const DEV_CREATE_CPMM_POOL_AUTH = new PublicKey(\"7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw\");\nexport const DEV_CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2\");\n\nexport const LOCK_CPMM_PROGRAM = new PublicKey(\"LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE\");\nexport const DEV_LOCK_CPMM_PROGRAM = new PublicKey(\"DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC\");\n\nexport const LOCK_CPMM_AUTH = new PublicKey(\"3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH\");\nexport const DEV_LOCK_CPMM_AUTH = new PublicKey(\"7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix\");\n\nexport const LAUNCHPAD_PROGRAM = new PublicKey(\"LanMV9sAd7wArD4vJFi2qDdfnVhFxYSUg6eADduJ3uj\");\nexport const LAUNCHPAD_AUTH = new PublicKey(\"WLHv2UAZm6z4KyaaELi5pjdbJh6RESMva1Rnn8pJVVh\");\n\nexport const DEV_LAUNCHPAD_PROGRAM = new PublicKey(\"LanD8FpTBBvzZFXjTxsAoipkFsxPUCDB4qAqKxYDiNP\");\nexport const DEV_LAUNCHPAD_AUTH = new PublicKey(\"HYNHiyKJ3gGVFvyxJAurK7qr7P2o5J9THmvCGMdULtpW\");\n\nexport const IDO_ALL_PROGRAM = {\n  IDO_PROGRAM_ID_V1,\n  IDO_PROGRAM_ID_V2,\n  IDO_PROGRAM_ID_V3,\n  IDO_PROGRAM_ID_V4,\n};\n\nexport const ALL_PROGRAM_ID = {\n  AMM_V4,\n  AMM_STABLE,\n  CLMM_PROGRAM_ID,\n  CLMM_LOCK_PROGRAM_ID,\n  CLMM_LOCK_AUTH_ID,\n\n  FARM_PROGRAM_ID_V3,\n  FARM_PROGRAM_ID_V5,\n  FARM_PROGRAM_ID_V6,\n\n  OPEN_BOOK_PROGRAM,\n  SERUM_PROGRAM_ID_V3,\n\n  UTIL1216,\n\n  Router,\n\n  CREATE_CPMM_POOL_PROGRAM,\n  CREATE_CPMM_POOL_AUTH,\n  CREATE_CPMM_POOL_FEE_ACC,\n\n  LOCK_CPMM_PROGRAM,\n  LOCK_CPMM_AUTH,\n\n  LAUNCHPAD_PROGRAM,\n  LAUNCHPAD_AUTH,\n};\n\nexport type ProgramIdConfig = Partial<typeof ALL_PROGRAM_ID>;\n\nexport const DEVNET_PROGRAM_ID = {\n  SERUM_MARKET: PublicKey.default,\n  OPENBOOK_MARKET: new PublicKey(\"EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj\"),\n\n  UTIL1216: PublicKey.default,\n\n  FarmV3: new PublicKey(\"85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL\"),\n  FarmV5: new PublicKey(\"EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2\"),\n  FarmV6: new PublicKey(\"Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7\"),\n\n  AmmV4: new PublicKey(\"HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8\"),\n  AmmStable: new PublicKey(\"DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF\"),\n\n  CLMM: new PublicKey(\"devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH\"),\n  CLMM_LOCK_PROGRAM_ID: new PublicKey(\"DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC\"),\n  CLMM_LOCK_AUTH_ID: new PublicKey(\"8qmHNvu2Kr2C7U8mJL4Vz1vTDxMhVuXKREwU7TNoaVEo\"),\n\n  Router: new PublicKey(\"BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU\"),\n\n  CREATE_CPMM_POOL_PROGRAM: DEV_CREATE_CPMM_POOL_PROGRAM,\n  CREATE_CPMM_POOL_AUTH: DEV_CREATE_CPMM_POOL_AUTH,\n  CREATE_CPMM_POOL_FEE_ACC: DEV_CREATE_CPMM_POOL_FEE_ACC,\n\n  FEE_DESTINATION_ID: new PublicKey(\"3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR\"),\n\n  LOCK_CPMM_PROGRAM: DEV_LOCK_CPMM_PROGRAM,\n  LCOK_CPMM_AUTH: DEV_LOCK_CPMM_AUTH,\n\n  LAUNCHPAD_PROGRAM: DEV_LAUNCHPAD_PROGRAM,\n  LAUNCHPAD_AUTH: DEV_LAUNCHPAD_AUTH,\n};\n","import { EpochInfo } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { TransferFee, TransferFeeConfig } from \"@solana/spl-token\";\n\nimport { TransferFeeDataBaseType } from \"../api/type\";\nimport { GetTransferAmountFee } from \"../raydium/type\";\n\nconst POINT = 10_000;\nexport function getTransferAmountFee(\n  amount: BN,\n  feeConfig: TransferFeeConfig | undefined,\n  epochInfo: EpochInfo,\n  addFee: boolean,\n): GetTransferAmountFee {\n  if (feeConfig === undefined) {\n    return {\n      amount,\n      fee: undefined,\n      expirationTime: undefined,\n    };\n  }\n\n  const nowFeeConfig: TransferFee =\n    epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n  const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n  const expirationTime: number | undefined =\n    epochInfo.epoch < feeConfig.newerTransferFee.epoch\n      ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n      : undefined;\n\n  if (addFee) {\n    if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n      const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n      return {\n        amount: amount.add(nowMaxFee),\n        fee: nowMaxFee,\n        expirationTime,\n      };\n    } else {\n      const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n      const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n      const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n      const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n      const fee = _fee.gt(maxFee) ? maxFee : _fee;\n      return {\n        amount: TAmount,\n        fee,\n        expirationTime,\n      };\n    }\n  } else {\n    const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n    const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n    return {\n      amount,\n      fee,\n      expirationTime,\n    };\n  }\n}\n\nexport function getTransferAmountFeeV2(\n  amount: BN,\n  _feeConfig: TransferFeeDataBaseType | undefined,\n  epochInfo: EpochInfo,\n  addFee: boolean,\n): GetTransferAmountFee {\n  if (_feeConfig === undefined) {\n    return {\n      amount,\n      fee: undefined,\n      expirationTime: undefined,\n    };\n  }\n  const feeConfig = {\n    ..._feeConfig,\n    olderTransferFee: {\n      epoch: BigInt(_feeConfig.olderTransferFee.epoch),\n      maximumFee: BigInt(_feeConfig.olderTransferFee.maximumFee),\n      transferFeeBasisPoints: _feeConfig.olderTransferFee.transferFeeBasisPoints,\n    },\n    newerTransferFee: {\n      epoch: BigInt(_feeConfig.newerTransferFee.epoch),\n      maximumFee: BigInt(_feeConfig.newerTransferFee.maximumFee),\n      transferFeeBasisPoints: _feeConfig.newerTransferFee.transferFeeBasisPoints,\n    },\n  };\n\n  const nowFeeConfig: TransferFee =\n    epochInfo.epoch < feeConfig.newerTransferFee.epoch ? feeConfig.olderTransferFee : feeConfig.newerTransferFee;\n  const maxFee = new BN(nowFeeConfig.maximumFee.toString());\n  const expirationTime: number | undefined =\n    epochInfo.epoch < feeConfig.newerTransferFee.epoch\n      ? ((Number(feeConfig.newerTransferFee.epoch) * epochInfo.slotsInEpoch - epochInfo.absoluteSlot) * 400) / 1000\n      : undefined;\n\n  if (addFee) {\n    if (nowFeeConfig.transferFeeBasisPoints === POINT) {\n      const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n      return {\n        amount: amount.add(nowMaxFee),\n        fee: nowMaxFee,\n        expirationTime,\n      };\n    } else {\n      const _TAmount = BNDivCeil(amount.mul(new BN(POINT)), new BN(POINT - nowFeeConfig.transferFeeBasisPoints));\n\n      const nowMaxFee = new BN(nowFeeConfig.maximumFee.toString());\n      const TAmount = _TAmount.sub(amount).gt(nowMaxFee) ? amount.add(nowMaxFee) : _TAmount;\n\n      const _fee = BNDivCeil(TAmount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n      const fee = _fee.gt(maxFee) ? maxFee : _fee;\n      return {\n        amount: TAmount,\n        fee,\n        expirationTime,\n      };\n    }\n  } else {\n    const _fee = BNDivCeil(amount.mul(new BN(nowFeeConfig.transferFeeBasisPoints)), new BN(POINT));\n    const fee = _fee.gt(maxFee) ? maxFee : _fee;\n\n    return {\n      amount,\n      fee,\n      expirationTime,\n    };\n  }\n}\n\nexport function minExpirationTime(\n  expirationTime1: number | undefined,\n  expirationTime2: number | undefined,\n): number | undefined {\n  if (expirationTime1 === undefined) return expirationTime2;\n  if (expirationTime2 === undefined) return expirationTime1;\n\n  return Math.min(expirationTime1, expirationTime2);\n}\n\nexport function BNDivCeil(bn1: BN, bn2: BN): BN {\n  const { div, mod } = bn1.divmod(bn2);\n\n  if (mod.gt(new BN(0))) {\n    return div.add(new BN(1));\n  } else {\n    return div;\n  }\n}\n\nexport function ceilDivBN(amountA: BN, amountB: BN): BN {\n  if (amountA.isZero()) return new BN(0);\n\n  const quotient = amountA.div(amountB);\n\n  if (quotient.isZero()) return new BN(1);\n\n  const remainder = amountA.mod(amountB);\n  if (remainder.gt(new BN(0))) {\n    return quotient.add(new BN(1));\n  }\n  return quotient;\n}\n","import { Connection, PublicKey, AddressLookupTableAccount } from \"@solana/web3.js\";\nimport { getMultipleAccountsInfo } from \"../accountInfo\";\n\nexport interface CacheLTA {\n  [key: string]: AddressLookupTableAccount;\n}\n\nexport async function getMultipleLookupTableInfo({\n  connection,\n  address,\n}: {\n  connection: Connection;\n  address: PublicKey[];\n}): Promise<CacheLTA> {\n  const dataInfos = await getMultipleAccountsInfo(\n    connection,\n    [...new Set<string>(address.map((i) => i.toString()))].map((i) => new PublicKey(i)),\n  );\n\n  const outDict: CacheLTA = {};\n  for (let i = 0; i < address.length; i++) {\n    const info = dataInfos[i];\n    const key = address[i];\n    if (!info) continue;\n    const lookupAccount = new AddressLookupTableAccount({\n      key,\n      state: AddressLookupTableAccount.deserialize(info.data),\n    });\n    outDict[key.toString()] = lookupAccount;\n    LOOKUP_TABLE_CACHE[key.toString()] = lookupAccount;\n  }\n\n  return outDict;\n}\n\nexport const LOOKUP_TABLE_CACHE: CacheLTA = {\n  \"AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU\": new AddressLookupTableAccount({\n    key: new PublicKey(\"AcL1Vo8oy1ULiavEcjSUcwfBSForXMudcZvDZy5nzJkU\"),\n    state: AddressLookupTableAccount.deserialize(\n      Buffer.from(\n        'AQAAAP//////////I1rcEwAAAAAvAQYwun9CU6c5Ikm2pAj+D9IEnCOR45nK+SFTGSdpd6J6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbd9uHXZaGT2cvhRs7reawctIXtX1s3kTqM9YV+/wCpBt324e51j94YQl285GzN2rYa/E2DuQ0n/r35KNihi/wFSlNQ+F3IgtYUpVZyeIopbd8eq6vQpgZ4iEky9O72oAVKU1qZKSEGTSTocWDaOHx8NbXdvJK7geQfqEBBBUSNBqfVFxksXFEhjMlMPUrxf1ja7gibof1E49vZigAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZC3BlsePRfEU4nVJ/awTDzVi4bHMaoP21SbbRvAP4KUbIScv+6Yw2LHF/6K0ZjUPibbSWXCirYPGuuVl7zT789IUPLW4CpHr4JNCatp3ELXDLKMv6JJ+37le50lbBJ2LvBkX2T9y7AHdNGviJAqQNtlDUDCnauQRWybsLji6nPM8Qkw5asQRvCdB3MbX6IEBwytOrpM32l4jQygKG9TKgR0vZScQ2AsM/IHeQ7RajUkyhuZdc8SGiqQz/7H34torNR/Wir3sl0ruUrVxJWEZfUg+QLNAxxODdBi53/OP7Ioil1cqeBM9dtZC3FLov4yyxWRM/wcGStyJX/QfTnLBAHqkqWotPKVlShCVQqpP9W5W1rOao65IMk5QuQ2kMIOxzDMKAy2vjGSxQODgBz0QwGA+eP4ZjIjrIAQaXENv31QfLlOdXSRCkaybRniDHF4C8YcwhcvsqrOVuTP4B2Na+9wLdtrB31uz2rtlFI5kahdsn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qF+VkLm9hOzIT+6i/nIf6keR4GWKMOD4AvqfpjHoD4DuhBpz8P28+DxkGrDXXr/nr20x291VPvcTU/b+b+o2kC9G0kcXeTlLjU6a2TQXWlZ4gBUdBl1jgT7mObSTpLblNiXZsLkbmVXZwvFKXua5cUKlWed/w30skmEUraTuQqtqr5fHZPW9n57EmeTif6LjHL2YJFZkQU+TrJmFzqzmF4/b8OwrPQAprl8mX3q4LUIdAS/a+11B6DWD1Xk2++Sn94dLC4xjkO4Wtlw8c4XuzciVbepHOmnoWzVu/0y3KCrLCSfQxQ3br8DJCoVzhgtPsS2nZZjsBGIZgnU0QpMv+2MnRsnKwdp1VsrCX84j/qvaZn4WhKunippgTbN2EUs0tPTP55Qfgj+nKmjtWW5IYs72FrEwJKYoNfsmqaF4o5pf4v9zgPwVwY/5I4XJKUL2L25m9kAQcW/K+H1RTFEUoj8Z4ajpOmAB/dG0COmCphVMW2CCMvnxhcGiSgPnpDuWu6qiJ7NG7ye5kvHgefgqPLeicspNJ5EpL3XiRNLM2tmJLI1awAwOyd6iHv0dCkMYRKaa6rcaZeYwmKCkckm0kM2JNmnmmAaBQQ7mwmIM0IMxX4f5W6j9PqZWcJxF7r17T/lQBAmcjoupRiJifbnXCNUv9GhpRF19WcBdeKbivRJVlGop6I2RS6lGImJ9udcI1S/0aGlEXX1ZwF14puK9ElWUainojZFYVHLHD6dIP2ESjqBzg3ol1/wB7+/ylGwd9LS7wSZ2A630CJSVKwH47K9P4bB8PEQP8BwjMFa7xQHOqZFP1XqaQ==',\n        \"base64\",\n      ),\n    ),\n  }),\n};\n","import {\n  Commitment,\n  Connection,\n  PublicKey,\n  sendAndConfirmTransaction,\n  SignatureResult,\n  Signer,\n  SystemProgram,\n  Transaction,\n  TransactionInstruction,\n  TransactionMessage,\n  VersionedTransaction,\n} from \"@solana/web3.js\";\nimport axios from \"axios\";\n\nimport { Api } from \"../../api\";\nimport { ComputeBudgetConfig, SignAllTransactions, TxTipConfig } from \"../../raydium/type\";\nimport { Cluster } from \"../../solana\";\nimport { Owner } from \"../owner\";\nimport { CacheLTA, getMultipleLookupTableInfo, LOOKUP_TABLE_CACHE } from \"./lookupTable\";\nimport { InstructionType, TxVersion } from \"./txType\";\nimport {\n  addComputeBudget,\n  checkLegacyTxSize,\n  checkV0TxSize,\n  confirmTransaction,\n  getRecentBlockHash,\n  printSimulate,\n} from \"./txUtils\";\n\ninterface SolanaFeeInfo {\n  min: number;\n  max: number;\n  avg: number;\n  priorityTx: number;\n  nonVotes: number;\n  priorityRatio: number;\n  avgCuPerBlock: number;\n  blockspaceUsageRatio: number;\n}\ntype SolanaFeeInfoJson = {\n  \"1\": SolanaFeeInfo;\n  \"5\": SolanaFeeInfo;\n  \"15\": SolanaFeeInfo;\n};\n\ninterface ExecuteParams {\n  skipPreflight?: boolean;\n  recentBlockHash?: string;\n  sendAndConfirm?: boolean;\n  notSendToRpc?: boolean;\n}\n\ninterface TxBuilderInit {\n  connection: Connection;\n  feePayer: PublicKey;\n  cluster: Cluster;\n  owner?: Owner;\n  blockhashCommitment?: Commitment;\n  loopMultiTxStatus?: boolean;\n  api?: Api;\n  signAllTransactions?: SignAllTransactions;\n}\n\nexport interface AddInstructionParam {\n  addresses?: Record<string, PublicKey>;\n  instructions?: TransactionInstruction[];\n  endInstructions?: TransactionInstruction[];\n  lookupTableAddress?: string[];\n  signers?: Signer[];\n  instructionTypes?: string[];\n  endInstructionTypes?: string[];\n}\n\nexport interface TxBuildData<T = Record<string, any>> {\n  builder: TxBuilder;\n  transaction: Transaction;\n  instructionTypes: string[];\n  signers: Signer[];\n  execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: Transaction }>;\n  extInfo: T;\n}\n\nexport interface TxV0BuildData<T = Record<string, any>> extends Omit<TxBuildData<T>, \"transaction\" | \"execute\"> {\n  builder: TxBuilder;\n  transaction: VersionedTransaction;\n  buildProps?: {\n    lookupTableCache?: CacheLTA;\n    lookupTableAddress?: string[];\n  };\n  execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: VersionedTransaction }>;\n}\n\ntype TxUpdateParams = {\n  txId: string;\n  status: \"success\" | \"error\" | \"sent\";\n  signedTx: Transaction | VersionedTransaction;\n};\nexport interface MultiTxExecuteParam extends ExecuteParams {\n  sequentially: boolean;\n  skipTxCount?: number;\n  onTxUpdate?: (completeTxs: TxUpdateParams[]) => void;\n}\nexport interface MultiTxBuildData<T = Record<string, any>> {\n  builder: TxBuilder;\n  transactions: Transaction[];\n  instructionTypes: string[];\n  signers: Signer[][];\n  execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: Transaction[] }>;\n  extInfo: T;\n}\n\nexport interface MultiTxV0BuildData<T = Record<string, any>>\n  extends Omit<MultiTxBuildData<T>, \"transactions\" | \"execute\"> {\n  builder: TxBuilder;\n  transactions: VersionedTransaction[];\n  buildProps?: {\n    lookupTableCache?: CacheLTA;\n    lookupTableAddress?: string[];\n  };\n  execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: VersionedTransaction[] }>;\n}\n\nexport type MakeMultiTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n  ? MultiTxBuildData<O>\n  : MultiTxV0BuildData<O>;\n\nexport type MakeTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n  ? TxBuildData<O>\n  : TxV0BuildData<O>;\n\nconst LOOP_INTERVAL = 2000;\n\nexport class TxBuilder {\n  private connection: Connection;\n  private owner?: Owner;\n  private instructions: TransactionInstruction[] = [];\n  private endInstructions: TransactionInstruction[] = [];\n  private lookupTableAddress: string[] = [];\n  private signers: Signer[] = [];\n  private instructionTypes: string[] = [];\n  private endInstructionTypes: string[] = [];\n  private feePayer: PublicKey;\n  private cluster: Cluster;\n  private signAllTransactions?: SignAllTransactions;\n  private blockhashCommitment?: Commitment;\n  private loopMultiTxStatus: boolean;\n\n  constructor(params: TxBuilderInit) {\n    this.connection = params.connection;\n    this.feePayer = params.feePayer;\n    this.signAllTransactions = params.signAllTransactions;\n    this.owner = params.owner;\n    this.cluster = params.cluster;\n    this.blockhashCommitment = params.blockhashCommitment;\n    this.loopMultiTxStatus = !!params.loopMultiTxStatus;\n  }\n\n  get AllTxData(): {\n    instructions: TransactionInstruction[];\n    endInstructions: TransactionInstruction[];\n    signers: Signer[];\n    instructionTypes: string[];\n    endInstructionTypes: string[];\n    lookupTableAddress: string[];\n  } {\n    return {\n      instructions: this.instructions,\n      endInstructions: this.endInstructions,\n      signers: this.signers,\n      instructionTypes: this.instructionTypes,\n      endInstructionTypes: this.endInstructionTypes,\n      lookupTableAddress: this.lookupTableAddress,\n    };\n  }\n\n  get allInstructions(): TransactionInstruction[] {\n    return [...this.instructions, ...this.endInstructions];\n  }\n\n  public async getComputeBudgetConfig(): Promise<ComputeBudgetConfig | undefined> {\n    const json = (\n      await axios.get<SolanaFeeInfoJson>(`https://solanacompass.com/api/fees?cacheFreshTime=${5 * 60 * 1000}`)\n    ).data;\n    const { avg } = json?.[15] ?? {};\n    if (!avg) return undefined;\n    return {\n      units: 600000,\n      microLamports: Math.min(Math.ceil((avg * 1000000) / 600000), 25000),\n    };\n  }\n\n  public addCustomComputeBudget(config?: ComputeBudgetConfig): boolean {\n    if (config) {\n      const { instructions, instructionTypes } = addComputeBudget(config);\n      this.instructions.unshift(...instructions);\n      this.instructionTypes.unshift(...instructionTypes);\n      return true;\n    }\n    return false;\n  }\n\n  public addTipInstruction(tipConfig?: TxTipConfig): boolean {\n    if (tipConfig) {\n      this.endInstructions.push(\n        SystemProgram.transfer({\n          fromPubkey: tipConfig.feePayer ?? this.feePayer,\n          toPubkey: new PublicKey(tipConfig.address),\n          lamports: BigInt(tipConfig.amount.toString()),\n        }),\n      );\n      this.endInstructionTypes.push(InstructionType.TransferTip);\n      return true;\n    }\n    return false;\n  }\n\n  public async calComputeBudget({\n    config: propConfig,\n    defaultIns,\n  }: {\n    config?: ComputeBudgetConfig;\n    defaultIns?: TransactionInstruction[];\n  }): Promise<void> {\n    try {\n      const config = propConfig || (await this.getComputeBudgetConfig());\n      if (this.addCustomComputeBudget(config)) return;\n      defaultIns && this.instructions.unshift(...defaultIns);\n    } catch {\n      defaultIns && this.instructions.unshift(...defaultIns);\n    }\n  }\n\n  public addInstruction({\n    instructions = [],\n    endInstructions = [],\n    signers = [],\n    instructionTypes = [],\n    endInstructionTypes = [],\n    lookupTableAddress = [],\n  }: AddInstructionParam): TxBuilder {\n    this.instructions.push(...instructions);\n    this.endInstructions.push(...endInstructions);\n    this.signers.push(...signers);\n    this.instructionTypes.push(...instructionTypes);\n    this.endInstructionTypes.push(...endInstructionTypes);\n    this.lookupTableAddress.push(...lookupTableAddress.filter((address) => address !== PublicKey.default.toString()));\n    return this;\n  }\n\n  public async versionBuild<O = Record<string, any>>({\n    txVersion,\n    extInfo,\n  }: {\n    txVersion?: TxVersion;\n    extInfo?: O;\n  }): Promise<MakeTxData<TxVersion.LEGACY, O> | MakeTxData<TxVersion.V0, O>> {\n    if (txVersion === TxVersion.V0) return (await this.buildV0({ ...(extInfo || {}) })) as MakeTxData<TxVersion.V0, O>;\n    return this.build<O>(extInfo) as MakeTxData<TxVersion.LEGACY, O>;\n  }\n\n  public build<O = Record<string, any>>(extInfo?: O): MakeTxData<TxVersion.LEGACY, O> {\n    const transaction = new Transaction();\n    if (this.allInstructions.length) transaction.add(...this.allInstructions);\n    transaction.feePayer = this.feePayer;\n    if (this.owner?.signer && !this.signers.some((s) => s.publicKey.equals(this.owner!.publicKey)))\n      this.signers.push(this.owner.signer);\n\n    return {\n      builder: this,\n      transaction,\n      signers: this.signers,\n      instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n      execute: async (params) => {\n        const { recentBlockHash: propBlockHash, skipPreflight = true, sendAndConfirm, notSendToRpc } = params || {};\n        const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n        transaction.recentBlockhash = recentBlockHash;\n        if (this.signers.length) transaction.sign(...this.signers);\n\n        printSimulate([transaction]);\n        if (this.owner?.isKeyPair) {\n          const txId = sendAndConfirm\n            ? await sendAndConfirmTransaction(\n                this.connection,\n                transaction,\n                this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n                  ? this.signers\n                  : [...this.signers, this.owner.signer!],\n                { skipPreflight },\n              )\n            : await this.connection.sendRawTransaction(transaction.serialize(), { skipPreflight });\n\n          return {\n            txId,\n            signedTx: transaction,\n          };\n        }\n        if (this.signAllTransactions) {\n          const txs = await this.signAllTransactions([transaction]);\n          if (this.signers.length) {\n            for (const item of txs) {\n              try {\n                item.sign(...this.signers);\n              } catch (e) {\n                //\n              }\n            }\n          }\n          return {\n            txId: notSendToRpc ? \"\" : await this.connection.sendRawTransaction(txs[0].serialize(), { skipPreflight }),\n            signedTx: txs[0],\n          };\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: extInfo || ({} as O),\n    };\n  }\n\n  public buildMultiTx<T = Record<string, any>>(params: {\n    extraPreBuildData?: MakeTxData<TxVersion.LEGACY>[];\n    extInfo?: T;\n  }): MultiTxBuildData {\n    const { extraPreBuildData = [], extInfo } = params;\n    const { transaction } = this.build(extInfo);\n\n    const filterExtraBuildData = extraPreBuildData.filter((data) => data.transaction.instructions.length > 0);\n\n    const allTransactions: Transaction[] = [transaction, ...filterExtraBuildData.map((data) => data.transaction)];\n    const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n    const allInstructionTypes: string[] = [\n      ...this.instructionTypes,\n      ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n    ];\n\n    if (this.owner?.signer) {\n      allSigners.forEach((signers) => {\n        if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) this.signers.push(this.owner!.signer!);\n      });\n    }\n\n    return {\n      builder: this,\n      transactions: allTransactions,\n      signers: allSigners,\n      instructionTypes: allInstructionTypes,\n      execute: async (executeParams?: MultiTxExecuteParam) => {\n        const {\n          sequentially,\n          onTxUpdate,\n          skipTxCount = 0,\n          recentBlockHash: propBlockHash,\n          skipPreflight = true,\n        } = executeParams || {};\n        const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n        if (this.owner?.isKeyPair) {\n          if (sequentially) {\n            const txIds: string[] = [];\n            let i = 0;\n            for (const tx of allTransactions) {\n              ++i;\n              if (i <= skipTxCount) continue;\n              const txId = await sendAndConfirmTransaction(\n                this.connection,\n                tx,\n                this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n                  ? this.signers\n                  : [...this.signers, this.owner.signer!],\n                { skipPreflight },\n              );\n              txIds.push(txId);\n            }\n\n            return {\n              txIds,\n              signedTxs: allTransactions,\n            };\n          }\n          return {\n            txIds: await await Promise.all(\n              allTransactions.map(async (tx) => {\n                tx.recentBlockhash = recentBlockHash;\n                return await this.connection.sendRawTransaction(tx.serialize(), { skipPreflight });\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n\n        if (this.signAllTransactions) {\n          const partialSignedTxs = allTransactions.map((tx, idx) => {\n            tx.recentBlockhash = recentBlockHash;\n            if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n            return tx;\n          });\n          printSimulate(partialSignedTxs);\n          const signedTxs = await this.signAllTransactions(partialSignedTxs);\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: TxUpdateParams[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n              processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n              let confirmed = false;\n              // eslint-disable-next-line\n              let intervalId: NodeJS.Timer | null = null,\n                subSignatureId: number | null = null;\n              const cbk = (signatureResult: SignatureResult): void => {\n                intervalId !== null && clearInterval(intervalId);\n                subSignatureId !== null && this.connection.removeSignatureListener(subSignatureId);\n                const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                if (targetTxIdx > -1) {\n                  if (processedTxs[targetTxIdx].status === \"error\" || processedTxs[targetTxIdx].status === \"success\")\n                    return;\n                  processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                }\n                onTxUpdate?.([...processedTxs]);\n                if (!signatureResult.err) checkSendTx();\n              };\n\n              if (this.loopMultiTxStatus)\n                intervalId = setInterval(async () => {\n                  if (confirmed) {\n                    clearInterval(intervalId!);\n                    return;\n                  }\n                  try {\n                    const r = await this.connection.getTransaction(txId, {\n                      commitment: \"confirmed\",\n                      maxSupportedTransactionVersion: TxVersion.V0,\n                    });\n                    if (r) {\n                      confirmed = true;\n                      clearInterval(intervalId!);\n                      cbk({ err: r.meta?.err || null });\n                      console.log(\"tx status from getTransaction:\", txId);\n                    }\n                  } catch (e) {\n                    confirmed = true;\n                    clearInterval(intervalId!);\n                    console.error(\"getTransaction timeout:\", e, txId);\n                  }\n                }, LOOP_INTERVAL);\n\n              subSignatureId = this.connection.onSignature(\n                txId,\n                (result) => {\n                  if (confirmed) {\n                    this.connection.removeSignatureListener(subSignatureId!);\n                    return;\n                  }\n                  confirmed = true;\n                  cbk(result);\n                },\n                \"confirmed\",\n              );\n              this.connection.getSignatureStatus(txId);\n            };\n            await checkSendTx();\n            return {\n              txIds: processedTxs.map((d) => d.txId),\n              signedTxs,\n            };\n          } else {\n            const txIds: string[] = [];\n            for (let i = 0; i < signedTxs.length; i += 1) {\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n              txIds.push(txId);\n            }\n            return {\n              txIds,\n              signedTxs,\n            };\n          }\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: extInfo || {},\n    };\n  }\n\n  public async versionMultiBuild<T extends TxVersion, O = Record<string, any>>({\n    extraPreBuildData,\n    txVersion,\n    extInfo,\n  }: {\n    extraPreBuildData?: MakeTxData<TxVersion.V0>[] | MakeTxData<TxVersion.LEGACY>[];\n    txVersion?: T;\n    extInfo?: O;\n  }): Promise<MakeMultiTxData<T, O>> {\n    if (txVersion === TxVersion.V0)\n      return (await this.buildV0MultiTx({\n        extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.V0>[],\n        buildProps: extInfo || {},\n      })) as MakeMultiTxData<T, O>;\n    return this.buildMultiTx<O>({\n      extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.LEGACY>[],\n      extInfo,\n    }) as MakeMultiTxData<T, O>;\n  }\n\n  public async buildV0<O = Record<string, any>>(\n    props?: O & {\n      lookupTableCache?: CacheLTA;\n      lookupTableAddress?: string[];\n      forerunCreate?: boolean;\n      recentBlockhash?: string;\n    },\n  ): Promise<MakeTxData<TxVersion.V0, O>> {\n    const {\n      lookupTableCache = {},\n      lookupTableAddress = [],\n      forerunCreate,\n      recentBlockhash: propRecentBlockhash,\n      ...extInfo\n    } = props || {};\n    const lookupTableAddressAccount = {\n      ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n      ...lookupTableCache,\n    };\n    const allLTA = Array.from(new Set<string>([...lookupTableAddress, ...this.lookupTableAddress]));\n    const needCacheLTA: PublicKey[] = [];\n    for (const item of allLTA) {\n      if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n    }\n    const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n    for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n    const recentBlockhash = forerunCreate\n      ? PublicKey.default.toBase58()\n      : propRecentBlockhash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n    const messageV0 = new TransactionMessage({\n      payerKey: this.feePayer,\n      recentBlockhash,\n      instructions: [...this.allInstructions],\n    }).compileToV0Message(Object.values(lookupTableAddressAccount));\n    if (this.owner?.signer && !this.signers.some((s) => s.publicKey.equals(this.owner!.publicKey)))\n      this.signers.push(this.owner.signer);\n    const transaction = new VersionedTransaction(messageV0);\n\n    transaction.sign(this.signers);\n\n    return {\n      builder: this,\n      transaction,\n      signers: this.signers,\n      instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n      execute: async (params) => {\n        const { skipPreflight = true, sendAndConfirm, notSendToRpc } = params || {};\n        printSimulate([transaction]);\n        if (this.owner?.isKeyPair) {\n          const txId = await this.connection.sendTransaction(transaction, { skipPreflight });\n          if (sendAndConfirm) {\n            await confirmTransaction(this.connection, txId);\n          }\n\n          return {\n            txId,\n            signedTx: transaction,\n          };\n        }\n        if (this.signAllTransactions) {\n          const txs = await this.signAllTransactions<VersionedTransaction>([transaction]);\n          if (this.signers.length) {\n            for (const item of txs) {\n              try {\n                item.sign(this.signers);\n              } catch (e) {\n                //\n              }\n            }\n          }\n          return {\n            txId: notSendToRpc ? \"\" : await this.connection.sendTransaction(txs[0], { skipPreflight }),\n            signedTx: txs[0],\n          };\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: (extInfo || {}) as O,\n    };\n  }\n\n  public async buildV0MultiTx<T = Record<string, any>>(params: {\n    extraPreBuildData?: MakeTxData<TxVersion.V0>[];\n    buildProps?: T & {\n      lookupTableCache?: CacheLTA;\n      lookupTableAddress?: string[];\n      forerunCreate?: boolean;\n      recentBlockhash?: string;\n    };\n  }): Promise<MultiTxV0BuildData> {\n    const { extraPreBuildData = [], buildProps } = params;\n    const { transaction } = await this.buildV0(buildProps);\n\n    const filterExtraBuildData = extraPreBuildData.filter((data) => data.builder.instructions.length > 0);\n\n    const allTransactions: VersionedTransaction[] = [\n      transaction,\n      ...filterExtraBuildData.map((data) => data.transaction),\n    ];\n    const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n    const allInstructionTypes: string[] = [\n      ...this.instructionTypes,\n      ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n    ];\n\n    if (this.owner?.signer) {\n      allSigners.forEach((signers) => {\n        if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) this.signers.push(this.owner!.signer!);\n      });\n    }\n\n    allTransactions.forEach(async (tx, idx) => {\n      tx.sign(allSigners[idx]);\n    });\n\n    return {\n      builder: this,\n      transactions: allTransactions,\n      signers: allSigners,\n      instructionTypes: allInstructionTypes,\n      buildProps,\n      execute: async (executeParams?: MultiTxExecuteParam) => {\n        const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n        if (propBlockHash) allTransactions.forEach((tx) => (tx.message.recentBlockhash = propBlockHash));\n        printSimulate(allTransactions);\n        if (this.owner?.isKeyPair) {\n          if (sequentially) {\n            const txIds: string[] = [];\n            for (const tx of allTransactions) {\n              const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n              await confirmTransaction(this.connection, txId);\n              txIds.push(txId);\n            }\n\n            return { txIds, signedTxs: allTransactions };\n          }\n\n          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx) => {\n                return await this.connection.sendTransaction(tx, { skipPreflight });\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n\n        if (this.signAllTransactions) {\n          const signedTxs = await this.signAllTransactions(allTransactions);\n\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: TxUpdateParams[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n              processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n\n              let confirmed = false;\n              // eslint-disable-next-line\n              let intervalId: NodeJS.Timer | null = null,\n                subSignatureId: number | null = null;\n              const cbk = (signatureResult: SignatureResult): void => {\n                intervalId !== null && clearInterval(intervalId);\n                subSignatureId !== null && this.connection.removeSignatureListener(subSignatureId);\n                const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                if (targetTxIdx > -1) {\n                  if (processedTxs[targetTxIdx].status === \"error\" || processedTxs[targetTxIdx].status === \"success\")\n                    return;\n                  processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                }\n                onTxUpdate?.([...processedTxs]);\n                if (!signatureResult.err) checkSendTx();\n              };\n\n              if (this.loopMultiTxStatus)\n                intervalId = setInterval(async () => {\n                  if (confirmed) {\n                    clearInterval(intervalId!);\n                    return;\n                  }\n                  try {\n                    const r = await this.connection.getTransaction(txId, {\n                      commitment: \"confirmed\",\n                      maxSupportedTransactionVersion: TxVersion.V0,\n                    });\n                    if (r) {\n                      confirmed = true;\n                      clearInterval(intervalId!);\n                      cbk({ err: r.meta?.err || null });\n                      console.log(\"tx status from getTransaction:\", txId);\n                    }\n                  } catch (e) {\n                    confirmed = true;\n                    clearInterval(intervalId!);\n                    console.error(\"getTransaction timeout:\", e, txId);\n                  }\n                }, LOOP_INTERVAL);\n\n              subSignatureId = this.connection.onSignature(\n                txId,\n                (result) => {\n                  if (confirmed) {\n                    this.connection.removeSignatureListener(subSignatureId!);\n                    return;\n                  }\n                  confirmed = true;\n                  cbk(result);\n                },\n                \"confirmed\",\n              );\n              this.connection.getSignatureStatus(txId);\n            };\n            checkSendTx();\n            return {\n              txIds: [],\n              signedTxs,\n            };\n          } else {\n            const txIds: string[] = [];\n            for (let i = 0; i < signedTxs.length; i += 1) {\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: buildProps || {},\n    };\n  }\n\n  public async sizeCheckBuild(\n    props?: Record<string, any> & { computeBudgetConfig?: ComputeBudgetConfig; splitIns?: TransactionInstruction[] },\n  ): Promise<MultiTxBuildData> {\n    const { splitIns = [], computeBudgetConfig, ...extInfo } = props || {};\n    const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n      computeBudgetConfig\n        ? addComputeBudget(computeBudgetConfig)\n        : {\n            instructions: [],\n            instructionTypes: [],\n          };\n\n    const signerKey: { [key: string]: Signer } = this.signers.reduce(\n      (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n      {},\n    );\n\n    const allTransactions: Transaction[] = [];\n    const allSigners: Signer[][] = [];\n\n    let instructionQueue: TransactionInstruction[] = [];\n    let splitInsIdx = 0;\n    this.allInstructions.forEach((item) => {\n      const _itemIns = [...instructionQueue, item];\n      const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n      const _signerStrs = new Set<string>(\n        _itemIns.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n      );\n      const _signer = [..._signerStrs.values()].map((i) => new PublicKey(i));\n\n      if (\n        item !== splitIns[splitInsIdx] &&\n        instructionQueue.length < 12 &&\n        (checkLegacyTxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, signers: _signer }) ||\n          checkLegacyTxSize({ instructions: _itemIns, payer: this.feePayer, signers: _signer }))\n      ) {\n        // current ins add to queue still not exceed tx size limit\n        instructionQueue.push(item);\n      } else {\n        if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n        splitInsIdx += item === splitIns[splitInsIdx] ? 1 : 0;\n        // if add computeBudget still not exceed tx size limit\n        if (\n          checkLegacyTxSize({\n            instructions: computeBudgetConfig\n              ? [...computeBudgetData.instructions, ...instructionQueue]\n              : [...instructionQueue],\n            payer: this.feePayer,\n            signers: _signer,\n          })\n        ) {\n          allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n        } else {\n          allTransactions.push(new Transaction().add(...instructionQueue));\n        }\n        allSigners.push(\n          Array.from(\n            new Set<string>(\n              instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n            ),\n          )\n            .map((i) => signerKey[i])\n            .filter((i) => i !== undefined),\n        );\n        instructionQueue = [item];\n      }\n    });\n\n    if (instructionQueue.length > 0) {\n      const _signerStrs = new Set<string>(\n        instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n      );\n      const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n      if (\n        checkLegacyTxSize({\n          instructions: computeBudgetConfig\n            ? [...computeBudgetData.instructions, ...instructionQueue]\n            : [...instructionQueue],\n          payer: this.feePayer,\n          signers: _signers.map((s) => s.publicKey),\n        })\n      ) {\n        allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n      } else {\n        allTransactions.push(new Transaction().add(...instructionQueue));\n      }\n      allSigners.push(_signers);\n    }\n    allTransactions.forEach((tx) => (tx.feePayer = this.feePayer));\n\n    if (this.owner?.signer) {\n      allSigners.forEach((signers) => {\n        if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) signers.push(this.owner!.signer!);\n      });\n    }\n\n    return {\n      builder: this,\n      transactions: allTransactions,\n      signers: allSigners,\n      instructionTypes: this.instructionTypes,\n      execute: async (executeParams?: MultiTxExecuteParam) => {\n        const {\n          sequentially,\n          onTxUpdate,\n          skipTxCount = 0,\n          recentBlockHash: propBlockHash,\n          skipPreflight = true,\n        } = executeParams || {};\n        const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n        allTransactions.forEach(async (tx, idx) => {\n          tx.recentBlockhash = recentBlockHash;\n          if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n        });\n        printSimulate(allTransactions);\n        if (this.owner?.isKeyPair) {\n          if (sequentially) {\n            let i = 0;\n            const txIds: string[] = [];\n            for (const tx of allTransactions) {\n              ++i;\n              if (i <= skipTxCount) {\n                txIds.push(\"tx skipped\");\n                continue;\n              }\n              const txId = await sendAndConfirmTransaction(\n                this.connection,\n                tx,\n                this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n                  ? this.signers\n                  : [...this.signers, this.owner.signer!],\n                { skipPreflight },\n              );\n              txIds.push(txId);\n            }\n\n            return {\n              txIds,\n              signedTxs: allTransactions,\n            };\n          }\n          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx) => {\n                return await this.connection.sendRawTransaction(tx.serialize(), { skipPreflight });\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n        if (this.signAllTransactions) {\n          const needSignedTx = await this.signAllTransactions(\n            allTransactions.slice(skipTxCount, allTransactions.length),\n          );\n          const signedTxs = [...allTransactions.slice(0, skipTxCount), ...needSignedTx];\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: TxUpdateParams[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              if (i < skipTxCount) {\n                // success before, do not send again\n                processedTxs.push({ txId: \"\", status: \"success\", signedTx: signedTxs[i] });\n                onTxUpdate?.([...processedTxs]);\n                i++;\n                checkSendTx();\n              }\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n              processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n\n              let confirmed = false;\n              // eslint-disable-next-line\n              let intervalId: NodeJS.Timer | null = null,\n                subSignatureId: number | null = null;\n              const cbk = (signatureResult: SignatureResult): void => {\n                intervalId !== null && clearInterval(intervalId);\n                subSignatureId !== null && this.connection.removeSignatureListener(subSignatureId);\n                const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                if (targetTxIdx > -1) {\n                  if (processedTxs[targetTxIdx].status === \"error\" || processedTxs[targetTxIdx].status === \"success\")\n                    return;\n                  processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                }\n                onTxUpdate?.([...processedTxs]);\n                if (!signatureResult.err) checkSendTx();\n              };\n\n              if (this.loopMultiTxStatus)\n                intervalId = setInterval(async () => {\n                  if (confirmed) {\n                    clearInterval(intervalId!);\n                    return;\n                  }\n                  try {\n                    const r = await this.connection.getTransaction(txId, {\n                      commitment: \"confirmed\",\n                      maxSupportedTransactionVersion: TxVersion.V0,\n                    });\n                    if (r) {\n                      confirmed = true;\n                      clearInterval(intervalId!);\n                      cbk({ err: r.meta?.err || null });\n                      console.log(\"tx status from getTransaction:\", txId);\n                    }\n                  } catch (e) {\n                    confirmed = true;\n                    clearInterval(intervalId!);\n                    console.error(\"getTransaction timeout:\", e, txId);\n                  }\n                }, LOOP_INTERVAL);\n\n              subSignatureId = this.connection.onSignature(\n                txId,\n                (result) => {\n                  if (confirmed) {\n                    this.connection.removeSignatureListener(subSignatureId!);\n                    return;\n                  }\n                  confirmed = true;\n                  cbk(result);\n                },\n                \"confirmed\",\n              );\n              this.connection.getSignatureStatus(txId);\n            };\n            await checkSendTx();\n            return {\n              txIds: processedTxs.map((d) => d.txId),\n              signedTxs,\n            };\n          } else {\n            const txIds: string[] = [];\n            for (let i = 0; i < signedTxs.length; i += 1) {\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: extInfo || {},\n    };\n  }\n\n  public async sizeCheckBuildV0(\n    props?: Record<string, any> & {\n      computeBudgetConfig?: ComputeBudgetConfig;\n      lookupTableCache?: CacheLTA;\n      lookupTableAddress?: string[];\n      splitIns?: TransactionInstruction[];\n    },\n  ): Promise<MultiTxV0BuildData> {\n    const {\n      computeBudgetConfig,\n      splitIns = [],\n      lookupTableCache = {},\n      lookupTableAddress = [],\n      ...extInfo\n    } = props || {};\n    const lookupTableAddressAccount = {\n      ...(this.cluster === \"devnet\" ? {} : LOOKUP_TABLE_CACHE),\n      ...lookupTableCache,\n    };\n    const allLTA = Array.from(new Set<string>([...this.lookupTableAddress, ...lookupTableAddress]));\n    const needCacheLTA: PublicKey[] = [];\n    for (const item of allLTA) {\n      if (lookupTableAddressAccount[item] === undefined) needCacheLTA.push(new PublicKey(item));\n    }\n    const newCacheLTA = await getMultipleLookupTableInfo({ connection: this.connection, address: needCacheLTA });\n    for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n    const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n      computeBudgetConfig\n        ? addComputeBudget(computeBudgetConfig)\n        : {\n            instructions: [],\n            instructionTypes: [],\n          };\n\n    const blockHash = await getRecentBlockHash(this.connection, this.blockhashCommitment);\n\n    const signerKey: { [key: string]: Signer } = this.signers.reduce(\n      (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n      {},\n    );\n    const allTransactions: VersionedTransaction[] = [];\n    const allSigners: Signer[][] = [];\n\n    let instructionQueue: TransactionInstruction[] = [];\n    let splitInsIdx = 0;\n    this.allInstructions.forEach((item) => {\n      const _itemIns = [...instructionQueue, item];\n      const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n      if (\n        item !== splitIns[splitInsIdx] &&\n        instructionQueue.length < 12 &&\n        (checkV0TxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, lookupTableAddressAccount }) ||\n          checkV0TxSize({ instructions: _itemIns, payer: this.feePayer, lookupTableAddressAccount }))\n      ) {\n        // current ins add to queue still not exceed tx size limit\n        instructionQueue.push(item);\n      } else {\n        if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n        splitInsIdx += item === splitIns[splitInsIdx] ? 1 : 0;\n        const lookupTableAddress: undefined | CacheLTA = {};\n        for (const item of [...new Set<string>(allLTA)]) {\n          if (lookupTableAddressAccount[item] !== undefined) lookupTableAddress[item] = lookupTableAddressAccount[item];\n        }\n        // if add computeBudget still not exceed tx size limit\n        if (\n          computeBudgetConfig &&\n          checkV0TxSize({\n            instructions: [...computeBudgetData.instructions, ...instructionQueue],\n            payer: this.feePayer,\n            lookupTableAddressAccount,\n            recentBlockhash: blockHash,\n          })\n        ) {\n          const messageV0 = new TransactionMessage({\n            payerKey: this.feePayer,\n            recentBlockhash: blockHash,\n\n            instructions: [...computeBudgetData.instructions, ...instructionQueue],\n          }).compileToV0Message(Object.values(lookupTableAddressAccount));\n          allTransactions.push(new VersionedTransaction(messageV0));\n        } else {\n          const messageV0 = new TransactionMessage({\n            payerKey: this.feePayer,\n            recentBlockhash: blockHash,\n            instructions: [...instructionQueue],\n          }).compileToV0Message(Object.values(lookupTableAddressAccount));\n          allTransactions.push(new VersionedTransaction(messageV0));\n        }\n        allSigners.push(\n          Array.from(\n            new Set<string>(\n              instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n            ),\n          )\n            .map((i) => signerKey[i])\n            .filter((i) => i !== undefined),\n        );\n        instructionQueue = [item];\n      }\n    });\n\n    if (instructionQueue.length > 0) {\n      const _signerStrs = new Set<string>(\n        instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n      );\n      const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n      if (\n        computeBudgetConfig &&\n        checkV0TxSize({\n          instructions: [...computeBudgetData.instructions, ...instructionQueue],\n          payer: this.feePayer,\n          lookupTableAddressAccount,\n          recentBlockhash: blockHash,\n        })\n      ) {\n        const messageV0 = new TransactionMessage({\n          payerKey: this.feePayer,\n          recentBlockhash: blockHash,\n          instructions: [...computeBudgetData.instructions, ...instructionQueue],\n        }).compileToV0Message(Object.values(lookupTableAddressAccount));\n        allTransactions.push(new VersionedTransaction(messageV0));\n      } else {\n        const messageV0 = new TransactionMessage({\n          payerKey: this.feePayer,\n          recentBlockhash: blockHash,\n          instructions: [...instructionQueue],\n        }).compileToV0Message(Object.values(lookupTableAddressAccount));\n        allTransactions.push(new VersionedTransaction(messageV0));\n      }\n\n      allSigners.push(_signers);\n    }\n\n    if (this.owner?.signer) {\n      allSigners.forEach((signers) => {\n        if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) signers.push(this.owner!.signer!);\n      });\n    }\n\n    allTransactions.forEach((tx, idx) => {\n      tx.sign(allSigners[idx]);\n    });\n\n    return {\n      builder: this,\n      transactions: allTransactions,\n      buildProps: props,\n      signers: allSigners,\n      instructionTypes: this.instructionTypes,\n      execute: async (executeParams?: MultiTxExecuteParam) => {\n        const {\n          sequentially,\n          onTxUpdate,\n          skipTxCount = 0,\n          recentBlockHash: propBlockHash,\n          skipPreflight = true,\n        } = executeParams || {};\n        allTransactions.map(async (tx, idx) => {\n          if (allSigners[idx].length) tx.sign(allSigners[idx]);\n          if (propBlockHash) tx.message.recentBlockhash = propBlockHash;\n        });\n        printSimulate(allTransactions);\n        if (this.owner?.isKeyPair) {\n          if (sequentially) {\n            let i = 0;\n            const txIds: string[] = [];\n            for (const tx of allTransactions) {\n              ++i;\n              if (i <= skipTxCount) {\n                console.log(\"skip tx: \", i);\n                txIds.push(\"tx skipped\");\n                continue;\n              }\n              const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n              await confirmTransaction(this.connection, txId);\n\n              txIds.push(txId);\n            }\n\n            return { txIds, signedTxs: allTransactions };\n          }\n\n          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx) => {\n                return await this.connection.sendTransaction(tx, { skipPreflight });\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n        if (this.signAllTransactions) {\n          const needSignedTx = await this.signAllTransactions(\n            allTransactions.slice(skipTxCount, allTransactions.length),\n          );\n          const signedTxs = [...allTransactions.slice(0, skipTxCount), ...needSignedTx];\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: TxUpdateParams[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              if (i < skipTxCount) {\n                // success before, do not send again\n                processedTxs.push({ txId: \"\", status: \"success\", signedTx: signedTxs[i] });\n                onTxUpdate?.([...processedTxs]);\n                i++;\n                checkSendTx();\n                return;\n              }\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n              processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n\n              let confirmed = false;\n              // eslint-disable-next-line\n              let intervalId: NodeJS.Timer | null = null,\n                subSignatureId: number | null = null;\n              const cbk = (signatureResult: SignatureResult): void => {\n                intervalId !== null && clearInterval(intervalId);\n                subSignatureId !== null && this.connection.removeSignatureListener(subSignatureId);\n                const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                if (targetTxIdx > -1) {\n                  if (processedTxs[targetTxIdx].status === \"error\" || processedTxs[targetTxIdx].status === \"success\")\n                    return;\n                  processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                }\n                onTxUpdate?.([...processedTxs]);\n                if (!signatureResult.err) checkSendTx();\n              };\n\n              if (this.loopMultiTxStatus)\n                intervalId = setInterval(async () => {\n                  if (confirmed) {\n                    clearInterval(intervalId!);\n                    return;\n                  }\n                  try {\n                    const r = await this.connection.getTransaction(txId, {\n                      commitment: \"confirmed\",\n                      maxSupportedTransactionVersion: TxVersion.V0,\n                    });\n                    if (r) {\n                      confirmed = true;\n                      clearInterval(intervalId!);\n                      cbk({ err: r.meta?.err || null });\n                      console.log(\"tx status from getTransaction:\", txId);\n                    }\n                  } catch (e) {\n                    confirmed = true;\n                    clearInterval(intervalId!);\n                    console.error(\"getTransaction timeout:\", e, txId);\n                  }\n                }, LOOP_INTERVAL);\n\n              subSignatureId = this.connection.onSignature(\n                txId,\n                (result) => {\n                  if (confirmed) {\n                    this.connection.removeSignatureListener(subSignatureId!);\n                    return;\n                  }\n                  confirmed = true;\n                  cbk(result);\n                },\n                \"confirmed\",\n              );\n              this.connection.getSignatureStatus(txId);\n            };\n            checkSendTx();\n            return {\n              txIds: [],\n              signedTxs,\n            };\n          } else {\n            const txIds: string[] = [];\n            for (let i = 0; i < signedTxs.length; i += 1) {\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n      },\n      extInfo: extInfo || {},\n    };\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { Fraction, Percent, Price, Token, TokenAmount } from \"../module\";\nimport { ReplaceType } from \"../raydium/type\";\n\nimport { tryParsePublicKey } from \"./pubKey\";\n\nexport async function sleep(ms: number): Promise<void> {\n  new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function getTimestamp(): number {\n  return new Date().getTime();\n}\n\nexport function notInnerObject(v: unknown): v is Record<string, any> {\n  return (\n    typeof v === \"object\" &&\n    v !== null &&\n    ![Token, TokenAmount, PublicKey, Fraction, BN, Price, Percent].some((o) => typeof o === \"object\" && v instanceof o)\n  );\n}\n\nexport function jsonInfo2PoolKeys<T>(jsonInfo: T): ReplaceType<T, string, PublicKey> {\n  // @ts-expect-error no need type for inner code\n  return typeof jsonInfo === \"string\"\n    ? tryParsePublicKey(jsonInfo)\n    : Array.isArray(jsonInfo)\n    ? jsonInfo.map((k) => jsonInfo2PoolKeys(k))\n    : notInnerObject(jsonInfo)\n    ? Object.fromEntries(Object.entries(jsonInfo).map(([k, v]) => [k, jsonInfo2PoolKeys(v)]))\n    : jsonInfo;\n}\n","import BN from \"bn.js\";\nexport const FEE_RATE_DENOMINATOR_VALUE = new BN(1_000_000);\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js-light\";\nimport { ApiV3Token } from \"../../../api/type\";\nimport { BNDivCeil } from \"../../../common\";\nimport { ConstantProductCurve } from \"./constantProduct\";\nimport { CpmmFee } from \"./fee\";\n\nexport enum RoundDirection {\n  Floor,\n  Ceiling,\n}\n\nexport type SwapWithoutFeesResult = { destinationAmountSwapped: BN };\n\nexport type TradingTokenResult = { tokenAmount0: BN; tokenAmount1: BN };\n\nexport type SwapResult = {\n  newSwapDestinationAmount: BN;\n  sourceAmountSwapped: BN;\n  destinationAmountSwapped: BN;\n  tradeFee: BN;\n};\n\nexport class CurveCalculator {\n  static validate_supply(tokenAmount0: BN, tokenAmount1: BN): void {\n    if (tokenAmount0.isZero()) throw Error(\"tokenAmount0 is zero\");\n    if (tokenAmount1.isZero()) throw Error(\"tokenAmount1 is zero\");\n  }\n\n  static swap(sourceAmount: BN, swapSourceAmount: BN, swapDestinationAmount: BN, tradeFeeRate: BN): SwapResult {\n    const tradeFee = CpmmFee.tradingFee(sourceAmount, tradeFeeRate);\n\n    const sourceAmountLessFees = sourceAmount.sub(tradeFee);\n\n    const { destinationAmountSwapped } = ConstantProductCurve.swapWithoutFees(\n      sourceAmountLessFees,\n      swapSourceAmount,\n      swapDestinationAmount,\n    );\n\n    return {\n      newSwapDestinationAmount: swapDestinationAmount.sub(destinationAmountSwapped),\n      sourceAmountSwapped: sourceAmount,\n      destinationAmountSwapped,\n      tradeFee,\n    };\n  }\n\n  static swapBaseOut({\n    poolMintA,\n    poolMintB,\n    tradeFeeRate,\n    baseReserve,\n    quoteReserve,\n    outputMint,\n    outputAmount,\n  }: {\n    poolMintA: ApiV3Token;\n    poolMintB: ApiV3Token;\n    tradeFeeRate: BN;\n    baseReserve: BN;\n    quoteReserve: BN;\n    outputMint: string | PublicKey;\n    outputAmount: BN;\n  }): {\n    amountRealOut: BN;\n\n    amountIn: BN;\n    amountInWithoutFee: BN;\n\n    tradeFee: BN;\n    priceImpact: number;\n  } {\n    const [reserveInAmount, reserveOutAmount, reserveInDecimals, reserveOutDecimals, inputMint] =\n      poolMintB.address === outputMint.toString()\n        ? [baseReserve, quoteReserve, poolMintA.decimals, poolMintB.decimals, poolMintA.address]\n        : [quoteReserve, baseReserve, poolMintB.decimals, poolMintA.decimals, poolMintB.address];\n    const currentPrice = new Decimal(reserveOutAmount.toString())\n      .div(10 ** reserveOutDecimals)\n      .div(new Decimal(reserveInAmount.toString()).div(10 ** reserveInDecimals));\n    const amountRealOut = outputAmount.gte(reserveOutAmount) ? reserveOutAmount.sub(new BN(1)) : outputAmount;\n\n    const denominator = reserveOutAmount.sub(amountRealOut);\n    const amountInWithoutFee = BNDivCeil(reserveInAmount.mul(amountRealOut), denominator);\n    const amountIn = BNDivCeil(amountInWithoutFee.mul(new BN(1_000_000)), new BN(1_000_000).sub(tradeFeeRate));\n    const fee = amountIn.sub(amountInWithoutFee);\n    const executionPrice = new Decimal(amountRealOut.toString())\n      .div(10 ** reserveOutDecimals)\n      .div(new Decimal(amountIn.toString()).div(10 ** reserveInDecimals));\n    const priceImpact = currentPrice.isZero() ? 0 : executionPrice.sub(currentPrice).div(currentPrice).abs().toNumber();\n\n    return {\n      amountRealOut,\n\n      amountIn,\n      amountInWithoutFee,\n\n      tradeFee: fee,\n      priceImpact,\n    };\n  }\n}\n","import BN from \"bn.js\";\nimport { RoundDirection, SwapWithoutFeesResult, TradingTokenResult } from \"./calculator\";\n\nfunction checkedRem(dividend: BN, divisor: BN): BN {\n  if (divisor.isZero()) throw Error(\"divisor is zero\");\n\n  const result = dividend.mod(divisor);\n  return result;\n}\n\nfunction checkedCeilDiv(dividend: BN, rhs: BN): BN[] {\n  if (rhs.isZero()) throw Error(\"rhs is zero\");\n\n  let quotient = dividend.div(rhs);\n\n  if (quotient.isZero()) throw Error(\"quotient is zero\");\n\n  let remainder = checkedRem(dividend, rhs);\n\n  if (remainder.gt(ZERO)) {\n    quotient = quotient.add(new BN(1));\n\n    rhs = dividend.div(quotient);\n    remainder = checkedRem(dividend, quotient);\n    if (remainder.gt(ZERO)) {\n      rhs = rhs.add(new BN(1));\n    }\n  }\n  return [quotient, rhs];\n}\n\nconst ZERO = new BN(0);\n\nexport class ConstantProductCurve {\n  static swapWithoutFees(sourceAmount: BN, swapSourceAmount: BN, swapDestinationAmount: BN): SwapWithoutFeesResult {\n    const invariant = swapSourceAmount.mul(swapDestinationAmount);\n\n    const newSwapSourceAmount = swapSourceAmount.add(sourceAmount);\n    const [newSwapDestinationAmount] = checkedCeilDiv(invariant, newSwapSourceAmount);\n\n    const destinationAmountSwapped = swapDestinationAmount.sub(newSwapDestinationAmount);\n    if (destinationAmountSwapped.isZero()) throw Error(\"destinationAmountSwapped is zero\");\n\n    return {\n      destinationAmountSwapped,\n    };\n  }\n\n  static lpTokensToTradingTokens(\n    lpTokenAmount: BN,\n    lpTokenSupply: BN,\n    swapTokenAmount0: BN,\n    swapTokenAmount1: BN,\n    roundDirection: RoundDirection,\n  ): TradingTokenResult {\n    let tokenAmount0 = lpTokenAmount.mul(swapTokenAmount0).div(lpTokenSupply);\n    let tokenAmount1 = lpTokenAmount.mul(swapTokenAmount1).div(lpTokenSupply);\n\n    if (roundDirection === RoundDirection.Floor) {\n      return { tokenAmount0, tokenAmount1 };\n    } else if (roundDirection === RoundDirection.Ceiling) {\n      const tokenRemainder0 = checkedRem(lpTokenAmount.mul(swapTokenAmount0), lpTokenSupply);\n\n      if (tokenRemainder0.gt(ZERO) && tokenAmount0.gt(ZERO)) {\n        tokenAmount0 = tokenAmount0.add(new BN(1));\n      }\n\n      const token1Remainder = checkedRem(lpTokenAmount.mul(swapTokenAmount1), lpTokenSupply);\n\n      if (token1Remainder.gt(ZERO) && tokenAmount1.gt(ZERO)) {\n        tokenAmount1 = tokenAmount1.add(new BN(1));\n      }\n\n      return { tokenAmount0, tokenAmount1 };\n    }\n    throw Error(\"roundDirection value error\");\n  }\n}\n","import BN from \"bn.js\";\nimport { ceilDiv, floorDiv } from \"@/common/bignumber\";\nimport { FEE_RATE_DENOMINATOR_VALUE } from \"@/common/fee\";\n\nexport class CpmmFee {\n  static tradingFee(amount: BN, tradeFeeRate: BN): BN {\n    return ceilDiv(amount, tradeFeeRate, FEE_RATE_DENOMINATOR_VALUE);\n  }\n  static protocolFee(amount: BN, protocolFeeRate: BN): BN {\n    return floorDiv(amount, protocolFeeRate, FEE_RATE_DENOMINATOR_VALUE);\n  }\n  static fundFee(amount: BN, fundFeeRate: BN): BN {\n    return floorDiv(amount, fundFeeRate, FEE_RATE_DENOMINATOR_VALUE);\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { createLogger, Logger } from \"../common/logger\";\nimport { TxBuilder } from \"../common/txTool/txTool\";\n\nimport { Raydium } from \"./\";\n\nexport interface ModuleBaseProps {\n  scope: Raydium;\n  moduleName: string;\n}\n\nconst joinMsg = (...args: (string | number | Record<string, any>)[]): string =>\n  args\n    .map((arg) => {\n      try {\n        return typeof arg === \"object\" ? JSON.stringify(arg) : arg;\n      } catch {\n        return arg;\n      }\n    })\n    .join(\", \");\nexport default class ModuleBase {\n  public scope: Raydium;\n  private disabled = false;\n  protected logger: Logger;\n\n  constructor({ scope, moduleName }: ModuleBaseProps) {\n    this.scope = scope;\n    this.logger = createLogger(moduleName);\n  }\n\n  protected createTxBuilder(feePayer?: PublicKey): TxBuilder {\n    this.scope.checkOwner();\n    return new TxBuilder({\n      connection: this.scope.connection,\n      feePayer: feePayer || this.scope.ownerPubKey,\n      cluster: this.scope.cluster,\n      owner: this.scope.owner,\n      blockhashCommitment: this.scope.blockhashCommitment,\n      loopMultiTxStatus: this.scope.loopMultiTxStatus,\n      api: this.scope.api,\n      signAllTransactions: this.scope.signAllTransactions,\n    });\n  }\n\n  public logDebug(...args: (string | number | Record<string, any>)[]): void {\n    this.logger.debug(joinMsg(args));\n  }\n\n  public logInfo(...args: (string | number | Record<string, any>)[]): void {\n    this.logger.info(joinMsg(args));\n  }\n\n  public logAndCreateError(...args: (string | number | Record<string, any>)[]): void {\n    const message = joinMsg(args);\n    throw new Error(message);\n  }\n\n  public checkDisabled(): void {\n    if (this.disabled || !this.scope) this.logAndCreateError(\"module not working\");\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN, { isBN } from \"bn.js\";\n\nimport {\n  bits,\n  blob,\n  Blob,\n  Layout,\n  offset as _offset,\n  seq as _seq,\n  Structure as _Structure,\n  u32 as _u32,\n  u8 as _u8,\n  UInt,\n  union as _union,\n  Union as _Union,\n} from \"./buffer-layout\";\n\nexport * from \"./buffer-layout\";\nexport { blob };\n\nexport class BNLayout<P extends string = \"\"> extends Layout<BN, P> {\n  blob: Layout<Buffer>;\n  signed: boolean;\n\n  constructor(span: number, signed: boolean, property?: P) {\n    //@ts-expect-error type wrong for super()'s type different from extends, but it desn't matter\n    super(span, property);\n    this.blob = blob(span);\n    this.signed = signed;\n  }\n\n  /** @override */\n  decode(b: Buffer, offset = 0): BN {\n    const num = new BN(this.blob.decode(b, offset), 10, \"le\");\n    if (this.signed) {\n      return num.fromTwos(this.span * 8).clone();\n    }\n    return num;\n  }\n\n  /** @override */\n  encode(src: BN, b: Buffer, offset = 0): number {\n    if (typeof src === \"number\") src = new BN(src); // src will pass a number accidently in union\n    if (this.signed) {\n      src = src.toTwos(this.span * 8);\n    }\n    return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n  }\n}\n\nexport class WideBits<P extends string = \"\"> extends Layout<Record<string, boolean>, P> {\n  _lower: any;\n  _upper: any;\n  // TODO: unknown\n  constructor(property?: P) {\n    //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n    super(8, property);\n    this._lower = bits(_u32(), false);\n    this._upper = bits(_u32(), false);\n  }\n\n  addBoolean(property: string): void {\n    if (this._lower.fields.length < 32) {\n      this._lower.addBoolean(property);\n    } else {\n      this._upper.addBoolean(property);\n    }\n  }\n\n  decode(b: Buffer, offset = 0): Record<string, boolean> {\n    const lowerDecoded = this._lower.decode(b, offset);\n    const upperDecoded = this._upper.decode(b, offset + this._lower.span);\n    return { ...lowerDecoded, ...upperDecoded };\n  }\n\n  encode(src: any /* TEMP */, b: Buffer, offset = 0): any {\n    return this._lower.encode(src, b, offset) + this._upper.encode(src, b, offset + this._lower.span);\n  }\n}\n\nexport function u8<P extends string = \"\">(property?: P): UInt<number, P> {\n  return new UInt(1, property);\n}\n\nexport function u32<P extends string = \"\">(property?: P): UInt<number, P> {\n  return new UInt(4, property);\n}\n\nexport function u64<P extends string = \"\">(property?: P): BNLayout<P> {\n  return new BNLayout(8, false, property);\n}\n\nexport function u128<P extends string = \"\">(property?: P): BNLayout<P> {\n  return new BNLayout(16, false, property);\n}\n\nexport function i8<P extends string = \"\">(property?: P): BNLayout<P> {\n  return new BNLayout(1, true, property);\n}\n\nexport function i64<P extends string = \"\">(property?: P): BNLayout<P> {\n  return new BNLayout(8, true, property);\n}\n\nexport function i128<P extends string = \"\">(property?: P): BNLayout<P> {\n  return new BNLayout(16, true, property);\n}\n\nexport class WrappedLayout<T, U, P extends string = \"\"> extends Layout<U, P> {\n  layout: Layout<T>;\n  decoder: (data: T) => U;\n  encoder: (src: U) => T;\n\n  constructor(layout: Layout<T>, decoder: (data: T) => U, encoder: (src: U) => T, property?: P) {\n    //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n    super(layout.span, property);\n    this.layout = layout;\n    this.decoder = decoder;\n    this.encoder = encoder;\n  }\n\n  decode(b: Buffer, offset?: number): U {\n    return this.decoder(this.layout.decode(b, offset));\n  }\n\n  encode(src: U, b: Buffer, offset?: number): number {\n    return this.layout.encode(this.encoder(src), b, offset);\n  }\n\n  getSpan(b: Buffer, offset?: number): number {\n    return this.layout.getSpan(b, offset);\n  }\n}\n\nexport function publicKey<P extends string = \"\">(property?: P): Layout<PublicKey, P> {\n  return new WrappedLayout(\n    blob(32),\n    (b: Buffer) => new PublicKey(b),\n    (key: PublicKey) => key.toBuffer(),\n    property,\n  );\n}\n\nexport class OptionLayout<T, P> extends Layout<T | null, P> {\n  layout: Layout<T>;\n  discriminator: Layout<number>;\n\n  constructor(layout: Layout<T>, property?: P) {\n    //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n    super(-1, property);\n    this.layout = layout;\n    this.discriminator = _u8();\n  }\n\n  encode(src: T | null, b: Buffer, offset = 0): number {\n    if (src === null || src === undefined) {\n      return this.discriminator.encode(0, b, offset);\n    }\n    this.discriminator.encode(1, b, offset);\n    return this.layout.encode(src, b, offset + 1) + 1;\n  }\n\n  decode(b: Buffer, offset = 0): T | null {\n    const discriminator = this.discriminator.decode(b, offset);\n    if (discriminator === 0) {\n      return null;\n    } else if (discriminator === 1) {\n      return this.layout.decode(b, offset + 1);\n    }\n    throw new Error(\"Invalid option \" + this.property);\n  }\n\n  getSpan(b: Buffer, offset = 0): number {\n    const discriminator = this.discriminator.decode(b, offset);\n    if (discriminator === 0) {\n      return 1;\n    } else if (discriminator === 1) {\n      return this.layout.getSpan(b, offset + 1) + 1;\n    }\n    throw new Error(\"Invalid option \" + this.property);\n  }\n}\n\nexport function option<T, P extends string = \"\">(layout: Layout<T>, property?: P): Layout<T | null, P> {\n  return new OptionLayout<T, P>(layout, property);\n}\n\nexport function bool<P extends string = \"\">(property?: P): Layout<boolean, P> {\n  return new WrappedLayout(_u8(), decodeBool, encodeBool, property);\n}\n\nexport function decodeBool(value: number): boolean {\n  if (value === 0) {\n    return false;\n  } else if (value === 1) {\n    return true;\n  }\n  throw new Error(\"Invalid bool: \" + value);\n}\n\nexport function encodeBool(value: boolean): number {\n  return value ? 1 : 0;\n}\n\nexport function vec<T, P extends string = \"\">(elementLayout: Layout<T>, property?: P): Layout<T[], P> {\n  const length = _u32(\"length\");\n  const layout: Layout<{ values: T[] }> = struct([\n    length,\n    seq(elementLayout, _offset(length, -length.span), \"values\"),\n  ]) as any; // Something I don't know\n  return new WrappedLayout(\n    layout,\n    ({ values }) => values,\n    (values) => ({ values }),\n    property,\n  );\n}\n\nexport function tagged<T, P extends string = \"\">(tag: BN, layout: Layout<T>, property?: P): Layout<T, P> {\n  const wrappedLayout: Layout<{ tag: BN; data: T }> = struct([u64(\"tag\"), layout.replicate(\"data\")]) as any; // Something I don't know\n\n  function decodeTag({ tag: receivedTag, data }: { tag: BN; data: T }): T {\n    if (!receivedTag.eq(tag)) {\n      throw new Error(\"Invalid tag, expected: \" + tag.toString(\"hex\") + \", got: \" + receivedTag.toString(\"hex\"));\n    }\n    return data;\n  }\n\n  return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\n\nexport function vecU8<P extends string = \"\">(property?: P): Layout<Buffer, P> {\n  const length = _u32(\"length\");\n  const layout: Layout<{ data: Buffer }> = struct([length, blob(_offset(length, -length.span), \"data\")]) as any; // Something I don't know\n  return new WrappedLayout(\n    layout,\n    ({ data }) => data,\n    (data) => ({ data }),\n    property,\n  );\n}\n\nexport function str<P extends string = \"\">(property?: P): Layout<string, P> {\n  return new WrappedLayout(\n    vecU8(),\n    (data) => data.toString(\"utf-8\"),\n    (s) => Buffer.from(s, \"utf-8\"),\n    property,\n  );\n}\n\nexport interface EnumLayout<T, P extends string = \"\"> extends Layout<T, P> {\n  registry: Record<string, Layout<any>>;\n}\n\nexport function rustEnum<T, P extends string = \"\">(variants: Layout<any>[], property?: P): EnumLayout<T, P> {\n  const unionLayout = _union(_u8(), property);\n  variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n  return unionLayout as any; // ?why use UnionLayout? This must be a fault\n}\n\nexport function array<T, P extends string = \"\">(\n  elementLayout: Layout<T>,\n  length: number,\n  property?: P,\n): Layout<T[], P> {\n  const layout = struct([seq(elementLayout, length, \"values\")]) as any as Layout<{ values: T[] }>; // Something I don't know\n  return new WrappedLayout(\n    layout,\n    ({ values }) => values,\n    (values) => ({ values }),\n    property,\n  );\n}\n\nexport class Structure<T, P, D extends { [key: string]: any; }> extends _Structure<T, P, D> {\n  /** @override */\n  decode(b: Buffer, offset?: number): D {\n    return super.decode(b, offset);\n  }\n}\n\nexport function struct<T, P extends string = \"\">(\n  fields: T,\n  property?: P,\n  decodePrefixes?: boolean,\n): T extends Layout<infer Value, infer Property>[]\n  ? Structure<\n    Value,\n    P,\n    {\n      [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n      ? V\n      : any;\n    }\n  >\n  : any {\n  //@ts-expect-error this type is not quite satisfied the define, but, never no need to worry about.\n  return new Structure(fields, property, decodePrefixes);\n}\n\nexport type GetLayoutSchemaFromStructure<T extends Structure<any, any, any>> = T extends Structure<any, any, infer S>\n  ? S\n  : any;\nexport type GetStructureFromLayoutSchema<S extends { [key: string]: any; }> = Structure<any, any, S>;\n\nexport class Union<Schema extends { [key: string]: any; }> extends _Union<Schema> {\n  encodeInstruction(instruction: any): Buffer {\n    const instructionMaxSpan = Math.max(...Object.values(this.registry).map((r) => r.span));\n    const b = Buffer.alloc(instructionMaxSpan);\n    return b.slice(0, this.encode(instruction, b));\n  }\n\n  decodeInstruction(instruction: any): Partial<Schema> {\n    return this.decode(instruction);\n  }\n}\nexport function union<UnionSchema extends { [key: string]: any } = any>(\n  discr: any,\n  defaultLayout?: any,\n  property?: string,\n): Union<UnionSchema> {\n  return new Union(discr, defaultLayout, property);\n}\n\nclass Zeros extends Blob {\n  decode(b: Buffer, offset: number): Buffer {\n    const slice = super.decode(b, offset);\n    if (!slice.every((v) => v === 0)) {\n      throw new Error(\"nonzero padding bytes\");\n    }\n    return slice;\n  }\n}\n\nexport function zeros(length: number): Zeros {\n  return new Zeros(length);\n}\n\nexport function seq<T, P extends string = \"\", AnotherP extends string = \"\">(\n  elementLayout: Layout<T, P>,\n  count: number | BN | Layout<BN | number, P>,\n  property?: AnotherP,\n): Layout<T[], AnotherP> {\n  let parsedCount: number;\n  const superCount =\n    typeof count === \"number\"\n      ? count\n      : isBN(count)\n        ? count.toNumber()\n        : new Proxy(count as unknown as Layout<number> /* pretend to be Layout<number> */, {\n          get(target, property): any {\n            if (!parsedCount) {\n              // get count in targetLayout. note that count may be BN\n              const countProperty = Reflect.get(target, \"count\");\n\n              // let targetLayout's  property:count be a number\n              parsedCount = isBN(countProperty) ? countProperty.toNumber() : countProperty;\n\n              // record the count\n              Reflect.set(target, \"count\", parsedCount);\n            }\n            return Reflect.get(target, property);\n          },\n          set(target, property, value): any {\n            if (property === \"count\") {\n              parsedCount = value;\n            }\n            return Reflect.set(target, property, value);\n          },\n        });\n\n  // @ts-expect-error force type\n  return _seq(elementLayout, superCount, property);\n}\n","import {\n  bits as _bits,\n  BitStructure as _BitStructure,\n  blob as _blob,\n  Blob as _Blob,\n  cstr as _cstr,\n  f32 as _f32,\n  f32be as _f32be,\n  f64 as _f64,\n  f64be as _f64be,\n  greedy as _greedy,\n  Layout as _Layout,\n  ns64 as _ns64,\n  ns64be as _ns64be,\n  nu64 as _nu64,\n  nu64be as _nu64be,\n  offset as _offset,\n  s16 as _s16,\n  s16be as _s16be,\n  s24 as _s24,\n  s24be as _s24be,\n  s32 as _s32,\n  s32be as _s32be,\n  s40 as _s40,\n  s40be as _s40be,\n  s48 as _s48,\n  s48be as _s48be,\n  s8 as _s8,\n  seq as _seq,\n  struct as _struct,\n  Structure as _Structure,\n  u16 as _u16,\n  u16be as _u16be,\n  u24 as _u24,\n  u24be as _u24be,\n  u32 as _u32,\n  u32be as _u32be,\n  u40 as _u40,\n  u40be as _u40be,\n  u48 as _u48,\n  u48be as _u48be,\n  u8 as _u8,\n  UInt as _UInt,\n  union as _union,\n  Union as _Union,\n  unionLayoutDiscriminator as _unionLayoutDiscriminator,\n  utf8 as _utf8,\n} from \"@solana/buffer-layout\";\n\n//#region ------------------- Layout -------------------\nexport interface Layout<T = any, P = \"\"> {\n  span: number;\n  property?: P;\n  decode(b: Buffer, offset?: number): T;\n  encode(src: T, b: Buffer, offset?: number): number;\n  getSpan(b: Buffer, offset?: number): number;\n  replicate<AP extends string>(name: AP): Layout<T, AP>;\n}\nexport interface LayoutConstructor {\n  new <T, P>(): Layout<T, P>; // for class extends syntex\n  new <T, P>(span?: T, property?: P): Layout<T, P>;\n  readonly prototype: Layout;\n}\nexport const Layout = _Layout as unknown as LayoutConstructor;\n//#endregion\n\n//#region ------------------- Structure -------------------\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface Structure<T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>\n  extends Layout<DecodeSchema, P> {\n  span: number;\n  decode(b: Buffer, offset?: number): DecodeSchema;\n  layoutFor<AP extends string>(property: AP): Layout<DecodeSchema[AP]>;\n  offsetOf<AP extends string>(property: AP): number;\n}\ninterface StructureConstructor {\n  new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(): Structure<T, P, DecodeSchema>;\n  new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(\n    fields: T,\n    property?: P,\n    decodePrefixes?: boolean,\n  ): Structure<T, P, DecodeSchema>;\n}\nexport const Structure = _Structure as unknown as StructureConstructor;\n//#endregion\n\n//#region ------------------- Union -------------------\nexport interface Union<UnionSchema extends { [key: string]: any } = any> extends Layout {\n  registry: object;\n  decode(b: Buffer, offset?: number): Partial<UnionSchema>;\n  addVariant(\n    variant: number,\n    layout: Structure<any, any, Partial<UnionSchema>> | Layout<any, keyof UnionSchema>,\n    property?: string,\n  ): any /* TEMP: code in Layout.js 1809 */;\n}\ninterface UnionConstructor {\n  new <UnionSchema extends { [key: string]: any } = any>(): Union<UnionSchema>;\n  new <UnionSchema extends { [key: string]: any } = any>(\n    discr: Layout<any, any>,\n    defaultLayout: Layout<any, any>,\n    property?: string,\n  ): Union<UnionSchema>;\n}\nexport const Union = _Union as unknown as UnionConstructor;\n//#endregion\n\n//#region ------------------- BitStructure -------------------\nexport type BitStructure<T = unknown /* TEMP */, P = \"\"> = Layout<T, P>;\ninterface BitStructureConstructor {\n  new (...params: any[]): BitStructure;\n}\nexport const BitStructure = _BitStructure as BitStructureConstructor;\n//#endregion\n\n//#region ------------------- UInt -------------------\nexport type UInt<T = any, P = \"\"> = Layout<T, P>;\ninterface UIntConstructor {\n  new <T, P>(span?: T, property?: P): UInt<T, P>;\n}\nexport const UInt = _UInt as UIntConstructor;\n//#endregion\n\n//#region ------------------- Blob -------------------\nexport type Blob<P extends string = \"\"> = Layout<Buffer, P>;\ninterface BlobConstructor {\n  new (...params: ConstructorParameters<LayoutConstructor>): Blob;\n}\nexport const Blob = _Blob as unknown as BlobConstructor;\n//#endregion\n\nexport const greedy = _greedy as <P extends string = \"\">(elementSpan?: number, property?: P) => Layout<number, P>;\nexport const u8 = _u8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16 = _u16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24 = _u24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32 = _u32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40 = _u40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48 = _u48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64 = _nu64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16be = _u16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24be = _u24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32be = _u32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40be = _u40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48be = _u48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64be = _nu64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s8 = _s8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16 = _s16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24 = _s24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32 = _s32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40 = _s40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48 = _s48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64 = _ns64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16be = _s16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24be = _s24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32be = _s32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40be = _s40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48be = _s48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64be = _ns64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32 = _f32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32be = _f32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64 = _f64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64be = _f64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\n\nexport const struct = _struct as <T, P extends string = \"\">(\n  fields: T,\n  property?: P,\n  decodePrefixes?: boolean,\n) => T extends Layout<infer Value, infer Property>[]\n  ? Structure<\n      Value,\n      P,\n      {\n        [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n          ? V\n          : any;\n      }\n    >\n  : any;\n\nexport const seq = _seq as unknown as <T, P>(\n  elementLayout: Layout<T, string>,\n  count: number | Layout<number, string>,\n  property?: P,\n) => Layout<T[]>;\nexport const union = _union as <UnionSchema extends { [key: string]: any } = any>(\n  discr: Layout<any, any>,\n  defaultLayout?: any,\n  property?: string,\n) => Union<UnionSchema>;\nexport const unionLayoutDiscriminator = _unionLayoutDiscriminator as <P extends string = \"\">(\n  layout: Layout<any, P>,\n  property?: P,\n) => any;\nexport const blob = _blob as unknown as <P extends string = \"\">(\n  length: number | Layout<number, P>,\n  property?: P,\n) => Blob<P>;\nexport const cstr = _cstr as <P extends string = \"\">(property?: P) => Layout<string, P>;\nexport const utf8 = _utf8 as <P extends string = \"\">(maxSpan: number, property?: P) => Layout<string, P>;\nexport const bits = _bits as unknown as <T, P extends string = \"\">(\n  word: Layout<T>,\n  msb?: boolean,\n  property?: P,\n) => BitStructure<T, P>; // TODO: not quite sure\nexport const offset = _offset as unknown as <T, P extends string = \"\">(\n  layout: Layout<T, P>,\n  offset?: number,\n  property?: P,\n) => Layout<T, P>;\n\nexport type GetStructureSchema<T extends Structure> = T extends Structure<any, any, infer S> ? S : unknown;\n","import { publicKey, struct, u32, u64, u8 } from \"../../marshmallow\";\n\nexport const SPL_MINT_LAYOUT = struct([\n  u32(\"mintAuthorityOption\"),\n  publicKey(\"mintAuthority\"),\n  u64(\"supply\"),\n  u8(\"decimals\"),\n  u8(\"isInitialized\"),\n  u32(\"freezeAuthorityOption\"),\n  publicKey(\"freezeAuthority\"),\n]);\n\nexport type SplMintLayout = typeof SPL_MINT_LAYOUT;\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport { MintLayout, RawMint, TOKEN_PROGRAM_ID, TransferFeeConfigLayout } from \"@solana/spl-token\";\nimport { BigNumberish } from \"@/common/bignumber\";\nimport { Token, TokenAmount } from \"../../module\";\nimport { SOL_INFO, TOKEN_WSOL } from \"./constant\";\nimport { TokenInfo } from \"./type\";\n\nimport { ApiV3Token } from \"../../api\";\nimport { solToWSol } from \"@/common\";\n\nexport const parseTokenInfo = async ({\n  connection,\n  mint,\n}: {\n  connection: Connection;\n  mint: PublicKey | string;\n}): Promise<RawMint | undefined> => {\n  const accountData = await connection.getAccountInfo(new PublicKey(mint));\n  if (!accountData || accountData.data.length !== MintLayout.span) return;\n  const tokenInfo = MintLayout.decode(accountData.data);\n  // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n  //@ts-ignore\n  return tokenInfo;\n};\n\nexport const toTokenInfo = ({\n  mint,\n  decimals,\n  programId = TOKEN_PROGRAM_ID,\n  logoURI = \"\",\n  priority = 3,\n}: {\n  mint: PublicKey;\n  decimals: number;\n  programId?: PublicKey | string;\n  priority?: number;\n  logoURI?: string;\n}): TokenInfo => {\n  const pubStr = mint.toBase58().substring(0, 6);\n  return {\n    address: mint.toBase58(),\n    decimals,\n    symbol: pubStr,\n    logoURI,\n    extensions: {},\n    chainId: 101,\n    programId: programId.toString(),\n    name: pubStr,\n    tags: [],\n    priority,\n  };\n};\n\nexport const toToken = (props: Omit<TokenInfo, \"priority\">): Token =>\n  new Token({\n    mint: props.address,\n    decimals: props.decimals,\n    symbol: props.symbol,\n    name: props.name,\n  });\n\nexport const toTokenAmount = ({\n  amount,\n  isRaw,\n  name,\n  ...props\n}: Omit<TokenInfo, \"priority\"> & {\n  amount: BigNumberish;\n  isRaw?: boolean;\n  name?: string;\n}): TokenAmount =>\n  new TokenAmount(\n    new Token({\n      mint: solToWSol(props.address).toBase58(),\n      decimals: props.decimals,\n      symbol: props.symbol,\n      name,\n    }),\n    amount,\n    isRaw,\n    name,\n  );\n\nexport function solToWSolToken<T extends ApiV3Token | TokenInfo>(token: T): T {\n  if (token.address === SOL_INFO.address) return TOKEN_WSOL as T;\n  return token;\n}\n\nexport function wSolToSolToken<T extends ApiV3Token | TokenInfo>(token: T): T {\n  if (token.address === TOKEN_WSOL.address) return SOL_INFO as T;\n  return token;\n}\n\nexport const toApiV3Token = ({\n  address,\n  programId,\n  decimals,\n  ...props\n}: {\n  address: string;\n  programId: string;\n  decimals: number;\n} & Partial<ApiV3Token>): ApiV3Token => ({\n  chainId: 101,\n  address: solToWSol(address).toBase58(),\n  programId,\n  logoURI: \"\",\n  symbol: \"\",\n  name: \"\",\n  decimals,\n  tags: [],\n  extensions: props.extensions || {},\n  ...props,\n});\n\nexport const toFeeConfig = (\n  config?: ReturnType<typeof TransferFeeConfigLayout.decode> | undefined | null,\n): ApiV3Token[\"extensions\"][\"feeConfig\"] | undefined =>\n  config\n    ? {\n        ...config,\n        transferFeeConfigAuthority: config.transferFeeConfigAuthority.toBase58(),\n        withdrawWithheldAuthority: config.withdrawWithheldAuthority.toBase58(),\n        withheldAmount: config.withheldAmount.toString(),\n        olderTransferFee: {\n          ...config.olderTransferFee,\n          epoch: config.olderTransferFee.epoch.toString(),\n          maximumFee: config.olderTransferFee.maximumFee.toString(),\n        },\n        newerTransferFee: {\n          ...config.newerTransferFee,\n          epoch: config.newerTransferFee.epoch.toString(),\n          maximumFee: config.newerTransferFee.maximumFee.toString(),\n        },\n      }\n    : undefined;\n","import BN from \"bn.js\";\n\nimport { AccountMeta, PublicKey, TransactionInstruction, Signer, Keypair, SystemProgram } from \"@solana/web3.js\";\nimport { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport {\n  MEMO_PROGRAM_ID2,\n  RENT_PROGRAM_ID,\n  SYSTEM_PROGRAM_ID,\n  METADATA_PROGRAM_ID,\n  createLogger,\n  CREATE_CPMM_POOL_PROGRAM,\n  CREATE_CPMM_POOL_AUTH,\n  InstructionType,\n} from \"@/common\";\nimport { getCpmmPdaPoolId, getCpLockPda } from \"./pda\";\n\nimport { struct, u64, bool } from \"@/marshmallow\";\nimport { ReturnTypeMakeInstructions } from \"@/raydium/type\";\nimport { ApiV3PoolInfoStandardItemCpmm, CpmmKeys } from \"@/api\";\nimport { getATAAddress } from \"@/common\";\nimport { getPdaMetadataKey } from \"../clmm\";\nimport { CpmmLockExtInfo } from \"./type\";\n\nconst logger = createLogger(\"Raydium_cpmm\");\nconst anchorDataBuf = {\n  initialize: [175, 175, 109, 31, 13, 152, 155, 237],\n  deposit: [242, 35, 198, 137, 82, 225, 242, 182],\n  withdraw: [183, 18, 70, 156, 148, 109, 161, 34],\n  swapBaseInput: [143, 190, 90, 218, 196, 30, 51, 222],\n  swapBaseOutput: [55, 217, 98, 86, 163, 74, 180, 173],\n  lockCpLiquidity: [216, 157, 29, 78, 38, 51, 31, 26],\n  collectCpFee: [8, 30, 51, 199, 209, 184, 247, 133],\n};\n\nexport function makeCreateCpmmPoolInInstruction(\n  programId: PublicKey,\n  creator: PublicKey,\n  configId: PublicKey,\n  authority: PublicKey,\n  poolId: PublicKey,\n  mintA: PublicKey,\n  mintB: PublicKey,\n  lpMint: PublicKey,\n  userVaultA: PublicKey,\n  userVaultB: PublicKey,\n  userLpAccount: PublicKey,\n  vaultA: PublicKey,\n  vaultB: PublicKey,\n  createPoolFeeAccount: PublicKey,\n  mintProgramA: PublicKey,\n  mintProgramB: PublicKey,\n  observationId: PublicKey,\n\n  amountMaxA: BN,\n  amountMaxB: BN,\n  openTime: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u64(\"amountMaxA\"), u64(\"amountMaxB\"), u64(\"openTime\")]);\n\n  const pdaPoolId = getCpmmPdaPoolId(programId, configId, mintA, mintB).publicKey;\n\n  const keys: Array<AccountMeta> = [\n    { pubkey: creator, isSigner: true, isWritable: false },\n    { pubkey: configId, isSigner: false, isWritable: false },\n    { pubkey: authority, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: !poolId.equals(pdaPoolId), isWritable: true },\n    { pubkey: mintA, isSigner: false, isWritable: false },\n    { pubkey: mintB, isSigner: false, isWritable: false },\n    { pubkey: lpMint, isSigner: false, isWritable: true },\n    { pubkey: userVaultA, isSigner: false, isWritable: true },\n    { pubkey: userVaultB, isSigner: false, isWritable: true },\n    { pubkey: userLpAccount, isSigner: false, isWritable: true },\n    { pubkey: vaultA, isSigner: false, isWritable: true },\n    { pubkey: vaultB, isSigner: false, isWritable: true },\n    { pubkey: createPoolFeeAccount, isSigner: false, isWritable: true },\n    { pubkey: observationId, isSigner: false, isWritable: true },\n\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: mintProgramA, isSigner: false, isWritable: false },\n    { pubkey: mintProgramB, isSigner: false, isWritable: false },\n    { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      amountMaxA,\n      amountMaxB,\n      openTime,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: Buffer.from([...anchorDataBuf.initialize, ...data]),\n  });\n}\n\nexport function makeDepositCpmmInInstruction(\n  programId: PublicKey,\n  owner: PublicKey,\n  authority: PublicKey,\n  poolId: PublicKey,\n  userLpAccount: PublicKey,\n  userVaultA: PublicKey,\n  userVaultB: PublicKey,\n  vaultA: PublicKey,\n  vaultB: PublicKey,\n  mintA: PublicKey,\n  mintB: PublicKey,\n  lpMint: PublicKey,\n\n  lpAmount: BN,\n  amountMaxA: BN,\n  amountMaxB: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u64(\"lpAmount\"), u64(\"amountMaxA\"), u64(\"amountMaxB\")]);\n\n  const keys: Array<AccountMeta> = [\n    { pubkey: owner, isSigner: true, isWritable: false },\n    { pubkey: authority, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: false, isWritable: true },\n    { pubkey: userLpAccount, isSigner: false, isWritable: true },\n    { pubkey: userVaultA, isSigner: false, isWritable: true },\n    { pubkey: userVaultB, isSigner: false, isWritable: true },\n    { pubkey: vaultA, isSigner: false, isWritable: true },\n    { pubkey: vaultB, isSigner: false, isWritable: true },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: mintA, isSigner: false, isWritable: false },\n    { pubkey: mintB, isSigner: false, isWritable: false },\n    { pubkey: lpMint, isSigner: false, isWritable: true },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  logger.debug(\"cpmm deposit data\", {\n    lpAmount: lpAmount.toString(),\n    amountMaxA: amountMaxA.toString(),\n    amountMaxB: amountMaxB.toString(),\n  });\n  dataLayout.encode(\n    {\n      lpAmount,\n      amountMaxA,\n      amountMaxB,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: Buffer.from([...anchorDataBuf.deposit, ...data]),\n  });\n}\n\nexport function makeWithdrawCpmmInInstruction(\n  programId: PublicKey,\n  owner: PublicKey,\n  authority: PublicKey,\n  poolId: PublicKey,\n  userLpAccount: PublicKey,\n  userVaultA: PublicKey,\n  userVaultB: PublicKey,\n  vaultA: PublicKey,\n  vaultB: PublicKey,\n  mintA: PublicKey,\n  mintB: PublicKey,\n  lpMint: PublicKey,\n\n  lpAmount: BN,\n  amountMinA: BN,\n  amountMinB: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u64(\"lpAmount\"), u64(\"amountMinA\"), u64(\"amountMinB\")]);\n\n  const keys: Array<AccountMeta> = [\n    { pubkey: owner, isSigner: true, isWritable: false },\n    { pubkey: authority, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: false, isWritable: true },\n    { pubkey: userLpAccount, isSigner: false, isWritable: true },\n    { pubkey: userVaultA, isSigner: false, isWritable: true },\n    { pubkey: userVaultB, isSigner: false, isWritable: true },\n    { pubkey: vaultA, isSigner: false, isWritable: true },\n    { pubkey: vaultB, isSigner: false, isWritable: true },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: mintA, isSigner: false, isWritable: false },\n    { pubkey: mintB, isSigner: false, isWritable: false },\n    { pubkey: lpMint, isSigner: false, isWritable: true },\n    { pubkey: MEMO_PROGRAM_ID2, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      lpAmount,\n      amountMinA,\n      amountMinB,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: Buffer.from([...anchorDataBuf.withdraw, ...data]),\n  });\n}\n\nexport function makeSwapCpmmBaseInInstruction(\n  programId: PublicKey,\n  payer: PublicKey,\n  authority: PublicKey,\n  configId: PublicKey,\n  poolId: PublicKey,\n  userInputAccount: PublicKey,\n  userOutputAccount: PublicKey,\n  inputVault: PublicKey,\n  outputVault: PublicKey,\n  inputTokenProgram: PublicKey,\n  outputTokenProgram: PublicKey,\n  inputMint: PublicKey,\n  outputMint: PublicKey,\n  observationId: PublicKey,\n\n  amountIn: BN,\n  amounOutMin: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u64(\"amountIn\"), u64(\"amounOutMin\")]);\n\n  const keys: Array<AccountMeta> = [\n    { pubkey: payer, isSigner: true, isWritable: false },\n    { pubkey: authority, isSigner: false, isWritable: false },\n    { pubkey: configId, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: false, isWritable: true },\n    { pubkey: userInputAccount, isSigner: false, isWritable: true },\n    { pubkey: userOutputAccount, isSigner: false, isWritable: true },\n    { pubkey: inputVault, isSigner: false, isWritable: true },\n    { pubkey: outputVault, isSigner: false, isWritable: true },\n    { pubkey: inputTokenProgram, isSigner: false, isWritable: false },\n    { pubkey: outputTokenProgram, isSigner: false, isWritable: false },\n    { pubkey: inputMint, isSigner: false, isWritable: false },\n    { pubkey: outputMint, isSigner: false, isWritable: false },\n    { pubkey: observationId, isSigner: false, isWritable: true },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      amountIn,\n      amounOutMin,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: Buffer.from([...anchorDataBuf.swapBaseInput, ...data]),\n  });\n}\nexport function makeSwapCpmmBaseOutInstruction(\n  programId: PublicKey,\n  payer: PublicKey,\n  authority: PublicKey,\n  configId: PublicKey,\n  poolId: PublicKey,\n  userInputAccount: PublicKey,\n  userOutputAccount: PublicKey,\n  inputVault: PublicKey,\n  outputVault: PublicKey,\n  inputTokenProgram: PublicKey,\n  outputTokenProgram: PublicKey,\n  inputMint: PublicKey,\n  outputMint: PublicKey,\n  observationId: PublicKey,\n\n  amountInMax: BN,\n  amountOut: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u64(\"amountInMax\"), u64(\"amountOut\")]);\n\n  const keys: Array<AccountMeta> = [\n    { pubkey: payer, isSigner: true, isWritable: false },\n    { pubkey: authority, isSigner: false, isWritable: false },\n    { pubkey: configId, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: false, isWritable: true },\n    { pubkey: userInputAccount, isSigner: false, isWritable: true },\n    { pubkey: userOutputAccount, isSigner: false, isWritable: true },\n    { pubkey: inputVault, isSigner: false, isWritable: true },\n    { pubkey: outputVault, isSigner: false, isWritable: true },\n    { pubkey: inputTokenProgram, isSigner: false, isWritable: false },\n    { pubkey: outputTokenProgram, isSigner: false, isWritable: false },\n    { pubkey: inputMint, isSigner: false, isWritable: false },\n    { pubkey: outputMint, isSigner: false, isWritable: false },\n    { pubkey: observationId, isSigner: false, isWritable: true },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      amountInMax,\n      amountOut,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: Buffer.from([...anchorDataBuf.swapBaseOutput, ...data]),\n  });\n}\n\nexport async function makeCpmmLockInstruction(props: {\n  poolInfo: ApiV3PoolInfoStandardItemCpmm;\n  poolKeys: CpmmKeys;\n  ownerInfo: {\n    feePayer: PublicKey;\n    wallet: PublicKey;\n  };\n  feeNftOwner: PublicKey;\n\n  lockProgram: PublicKey;\n  lockAuthProgram: PublicKey;\n  lpAmount: BN;\n  withMetadata?: boolean;\n  getEphemeralSigners?: (k: number) => any;\n}): Promise<ReturnTypeMakeInstructions<CpmmLockExtInfo>> {\n  const { ownerInfo, poolInfo, poolKeys, feeNftOwner, getEphemeralSigners } = props;\n\n  const signers: Signer[] = [];\n  const [poolId, lpMint] = [new PublicKey(poolInfo.id), new PublicKey(poolInfo.lpMint.address)];\n\n  let nftMintAccount: PublicKey;\n  if (getEphemeralSigners) {\n    nftMintAccount = new PublicKey((await getEphemeralSigners(1))[0]);\n  } else {\n    const _k = Keypair.generate();\n    signers.push(_k);\n    nftMintAccount = _k.publicKey;\n  }\n\n  const { publicKey: nftAccount } = getATAAddress(feeNftOwner, nftMintAccount, TOKEN_PROGRAM_ID);\n  const { publicKey: metadataAccount } = getPdaMetadataKey(nftMintAccount);\n  const { publicKey: lockPda } = getCpLockPda(props.lockProgram, nftMintAccount);\n\n  const { publicKey: userLpVault } = getATAAddress(ownerInfo.wallet, lpMint, TOKEN_PROGRAM_ID);\n  const { publicKey: lockLpVault } = getATAAddress(props.lockAuthProgram, lpMint, TOKEN_PROGRAM_ID);\n\n  const ins = cpmmLockPositionInstruction({\n    programId: props.lockProgram,\n    auth: props.lockAuthProgram,\n    payer: ownerInfo.feePayer,\n    liquidityOwner: ownerInfo.wallet,\n    nftOwner: feeNftOwner,\n    nftMint: nftMintAccount,\n    nftAccount,\n    poolId,\n    lockPda,\n    mintLp: lpMint,\n    userLpVault,\n    lockLpVault,\n    poolVaultA: new PublicKey(poolKeys.vault.A),\n    poolVaultB: new PublicKey(poolKeys.vault.B),\n    metadataAccount,\n    lpAmount: props.lpAmount,\n    withMetadata: props.withMetadata ?? true,\n  });\n\n  return {\n    address: {\n      nftMint: nftMintAccount,\n      nftAccount,\n      metadataAccount,\n      lockPda,\n      userLpVault,\n      lockLpVault,\n    },\n    instructions: [ins],\n    signers,\n    instructionTypes: [InstructionType.CpmmLockLp],\n    lookupTableAddress: [],\n  };\n}\n\nexport function cpmmLockPositionInstruction({\n  programId,\n  auth,\n  payer,\n  liquidityOwner,\n  nftOwner,\n  nftMint,\n  nftAccount,\n  poolId,\n  lockPda,\n  mintLp,\n  userLpVault,\n  lockLpVault,\n  poolVaultA,\n  poolVaultB,\n  metadataAccount,\n  lpAmount,\n  withMetadata,\n}: {\n  programId: PublicKey;\n  auth: PublicKey;\n  payer: PublicKey;\n  liquidityOwner: PublicKey;\n  nftOwner: PublicKey;\n  nftMint: PublicKey;\n  nftAccount: PublicKey;\n  poolId: PublicKey;\n  lockPda: PublicKey;\n  mintLp: PublicKey;\n  userLpVault: PublicKey;\n  lockLpVault: PublicKey;\n  poolVaultA: PublicKey;\n  poolVaultB: PublicKey;\n  metadataAccount: PublicKey;\n  lpAmount: BN;\n  withMetadata: boolean;\n}): TransactionInstruction {\n  const keys = [\n    { pubkey: auth, isSigner: false, isWritable: false },\n    { pubkey: payer, isSigner: true, isWritable: true },\n    { pubkey: liquidityOwner, isSigner: true, isWritable: false },\n    { pubkey: nftOwner, isSigner: false, isWritable: false },\n    { pubkey: nftMint, isSigner: true, isWritable: true },\n    { pubkey: nftAccount, isSigner: false, isWritable: true },\n    { pubkey: poolId, isSigner: false, isWritable: false },\n    { pubkey: lockPda, isSigner: false, isWritable: true },\n    { pubkey: mintLp, isSigner: false, isWritable: false },\n    { pubkey: userLpVault, isSigner: false, isWritable: true },\n    { pubkey: lockLpVault, isSigner: false, isWritable: true },\n    { pubkey: poolVaultA, isSigner: false, isWritable: true },\n    { pubkey: poolVaultB, isSigner: false, isWritable: true },\n    { pubkey: metadataAccount, isSigner: false, isWritable: true },\n    { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: METADATA_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n  const dataLayout = struct([u64(\"lpAmount\"), bool(\"withMetadata\")]);\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      lpAmount,\n      withMetadata,\n    },\n    data,\n  );\n  const aData = Buffer.from([...anchorDataBuf.lockCpLiquidity, ...data]);\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport function collectCpFeeInstruction({\n  programId,\n  nftOwner,\n  auth,\n  nftAccount,\n  lockPda,\n  poolId,\n  mintLp,\n  userVaultA,\n  userVaultB,\n  poolVaultA,\n  poolVaultB,\n  mintA,\n  mintB,\n  lockLpVault,\n  lpFeeAmount,\n  cpmmProgram,\n  cpmmAuthProgram,\n}: {\n  programId: PublicKey;\n  nftOwner: PublicKey;\n  auth: PublicKey;\n  nftMint: PublicKey;\n  nftAccount: PublicKey;\n  lockPda: PublicKey;\n  poolId: PublicKey;\n  mintLp: PublicKey;\n  userVaultA: PublicKey;\n  userVaultB: PublicKey;\n  poolVaultA: PublicKey;\n  poolVaultB: PublicKey;\n  mintA: PublicKey;\n  mintB: PublicKey;\n  lockLpVault: PublicKey;\n  lpFeeAmount: BN;\n  cpmmProgram?: PublicKey;\n  cpmmAuthProgram?: PublicKey;\n}): TransactionInstruction {\n  const keys = [\n    { pubkey: auth, isSigner: false, isWritable: false },\n    { pubkey: nftOwner, isSigner: true, isWritable: false },\n    // { pubkey: nftMint, isSigner: false, isWritable: true },\n    { pubkey: nftAccount, isSigner: false, isWritable: true },\n    { pubkey: lockPda, isSigner: false, isWritable: true },\n    { pubkey: cpmmProgram ?? CREATE_CPMM_POOL_PROGRAM, isSigner: false, isWritable: false },\n    { pubkey: cpmmAuthProgram ?? CREATE_CPMM_POOL_AUTH, isSigner: false, isWritable: false },\n    { pubkey: poolId, isSigner: false, isWritable: true },\n    { pubkey: mintLp, isSigner: false, isWritable: true },\n    { pubkey: userVaultA, isSigner: false, isWritable: true },\n    { pubkey: userVaultB, isSigner: false, isWritable: true },\n    { pubkey: poolVaultA, isSigner: false, isWritable: true },\n    { pubkey: poolVaultB, isSigner: false, isWritable: true },\n    { pubkey: mintA, isSigner: false, isWritable: false },\n    { pubkey: mintB, isSigner: false, isWritable: false },\n    { pubkey: lockLpVault, isSigner: false, isWritable: true },\n    // { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: MEMO_PROGRAM_ID2, isSigner: false, isWritable: false },\n  ];\n  const dataLayout = struct([u64(\"lpFeeAmount\")]);\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      lpFeeAmount,\n    },\n    data,\n  );\n  const aData = Buffer.from([...anchorDataBuf.collectCpFee, ...data]);\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport { findProgramAddress } from \"../../common/txTool/txUtils\";\n\nconst AUTH_SEED = Buffer.from(\"vault_and_lp_mint_auth_seed\", \"utf8\");\nconst AMM_CONFIG_SEED = Buffer.from(\"amm_config\", \"utf8\");\nconst POOL_SEED = Buffer.from(\"pool\", \"utf8\");\nconst POOL_LP_MINT_SEED = Buffer.from(\"pool_lp_mint\", \"utf8\");\nconst POOL_VAULT_SEED = Buffer.from(\"pool_vault\", \"utf8\");\nconst OBSERVATION_SEED = Buffer.from(\"observation\", \"utf8\");\n\nexport function getPdaPoolAuthority(programId: PublicKey): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([AUTH_SEED], programId);\n}\n\nexport function getCpmmPdaAmmConfigId(\n  programId: PublicKey,\n  index: number,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([AMM_CONFIG_SEED, u16ToBytes(index)], programId);\n}\n\nexport function getCpmmPdaPoolId(\n  programId: PublicKey,\n  ammConfigId: PublicKey,\n  mintA: PublicKey,\n  mintB: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_SEED, ammConfigId.toBuffer(), mintA.toBuffer(), mintB.toBuffer()], programId);\n}\n\nexport function getPdaLpMint(\n  programId: PublicKey,\n  poolId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_LP_MINT_SEED, poolId.toBuffer()], programId);\n}\n\nexport function getPdaVault(\n  programId: PublicKey,\n  poolId: PublicKey,\n  mint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_VAULT_SEED, poolId.toBuffer(), mint.toBuffer()], programId);\n}\n\nexport function getPdaObservationId(\n  programId: PublicKey,\n  poolId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([OBSERVATION_SEED, poolId.toBuffer()], programId);\n}\n\nfunction u16ToBytes(num: number): Uint8Array {\n  const arr = new ArrayBuffer(2);\n  const view = new DataView(arr);\n  view.setUint16(0, num, false);\n  return new Uint8Array(arr);\n}\n\nexport function getCreatePoolKeys({\n  poolId: propPoolId,\n  programId,\n  configId,\n  mintA,\n  mintB,\n}: {\n  poolId?: PublicKey;\n  programId: PublicKey;\n  configId: PublicKey;\n  mintA: PublicKey;\n  mintB: PublicKey;\n}): {\n  poolId: PublicKey;\n  configId: PublicKey;\n  authority: PublicKey;\n  lpMint: PublicKey;\n  vaultA: PublicKey;\n  vaultB: PublicKey;\n  observationId: PublicKey;\n} {\n  // const configId = getCpmmPdaAmmConfigId(programId, 0).publicKey;\n  const authority = getPdaPoolAuthority(programId).publicKey;\n  const poolId = propPoolId || getCpmmPdaPoolId(programId, configId, mintA, mintB).publicKey;\n  const lpMint = getPdaLpMint(programId, poolId).publicKey;\n  const vaultA = getPdaVault(programId, poolId, mintA).publicKey;\n  const vaultB = getPdaVault(programId, poolId, mintB).publicKey;\n  const observationId = getPdaObservationId(programId, poolId).publicKey;\n\n  return {\n    poolId,\n    configId,\n    authority,\n    lpMint,\n    vaultA,\n    vaultB,\n    observationId,\n  };\n}\n\nexport const LOCK_LIQUIDITY_SEED = Buffer.from(\"locked_liquidity\", \"utf8\");\n\nexport function getCpLockPda(\n  programId: PublicKey,\n  mint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([LOCK_LIQUIDITY_SEED, mint.toBuffer()], programId);\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { ApiV3PoolInfoConcentratedItem, ClmmKeys } from \"../../api/type\";\nimport {\n  CLMM_LOCK_AUTH_ID,\n  CLMM_LOCK_PROGRAM_ID,\n  CLMM_PROGRAM_ID,\n  InstructionType,\n  WSOLMint,\n  fetchMultipleMintInfos,\n  getATAAddress,\n  getMultipleAccountsInfoWithCustomFlags,\n} from \"@/common\";\nimport { AccountLayout, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { MakeMultiTxData, MakeTxData } from \"@/common/txTool/txTool\";\nimport { TxVersion } from \"@/common/txTool/txType\";\nimport { toApiV3Token, toFeeConfig } from \"../../raydium/token/utils\";\nimport { ComputeBudgetConfig, ReturnTypeFetchMultipleMintInfos, TxTipConfig } from \"../../raydium/type\";\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport { MakeTransaction } from \"../type\";\nimport { ClmmInstrument } from \"./instrument\";\nimport { ClmmConfigLayout, ClmmPositionLayout, OperationLayout, PoolInfoLayout, PositionInfoLayout } from \"./layout\";\nimport {\n  ClmmRpcData,\n  ClosePositionExtInfo,\n  CollectRewardParams,\n  CollectRewardsParams,\n  ComputeClmmPoolInfo,\n  CreateConcentratedPool,\n  DecreaseLiquidity,\n  HarvestAllRewardsParams,\n  HarvestLockPosition,\n  IncreasePositionFromBase,\n  IncreasePositionFromLiquidity,\n  InitRewardExtInfo,\n  InitRewardParams,\n  InitRewardsParams,\n  LockPosition,\n  ManipulateLiquidityExtInfo,\n  OpenPositionFromBase,\n  OpenPositionFromBaseExtInfo,\n  OpenPositionFromLiquidity,\n  OpenPositionFromLiquidityExtInfo,\n  ReturnTypeFetchMultiplePoolTickArrays,\n  SetRewardParams,\n  SetRewardsParams,\n  ClmmLockAddress,\n} from \"./type\";\nimport { MAX_SQRT_PRICE_X64, MIN_SQRT_PRICE_X64, mockV3CreatePoolInfo, ZERO } from \"./utils/constants\";\nimport { MathUtil, SqrtPriceMath } from \"./utils/math\";\nimport {\n  getPdaOperationAccount,\n  getPdaPersonalPositionAddress,\n  getPdaLockClPositionIdV2,\n  getPdaTickArrayAddress,\n  getPdaProtocolPositionAddress,\n  getPdaExBitmapAccount,\n  getPdaMintExAccount,\n} from \"./utils/pda\";\nimport { PoolUtils, clmmComputeInfoToApiInfo } from \"./utils/pool\";\nimport { TickUtils } from \"./utils/tick\";\n\nexport class Clmm extends ModuleBase {\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  public async getClmmPoolKeys(poolId: string): Promise<ClmmKeys> {\n    return ((await this.scope.api.fetchPoolKeysById({ idList: [poolId] })) as ClmmKeys[])[0];\n  }\n\n  public async createPool<T extends TxVersion>(\n    props: CreateConcentratedPool<T>,\n  ): Promise<MakeTxData<T, { mockPoolInfo: ApiV3PoolInfoConcentratedItem; address: ClmmKeys }>> {\n    const {\n      programId,\n      owner = this.scope.owner?.publicKey || PublicKey.default,\n      mint1,\n      mint2,\n      ammConfig,\n      initialPrice,\n      computeBudgetConfig,\n      forerunCreate,\n      getObserveState,\n      txVersion,\n      txTipConfig,\n      feePayer,\n    } = props;\n    const txBuilder = this.createTxBuilder(feePayer);\n    const [mintA, mintB, initPrice] = new BN(new PublicKey(mint1.address).toBuffer()).gt(\n      new BN(new PublicKey(mint2.address).toBuffer()),\n    )\n      ? [mint2, mint1, new Decimal(1).div(initialPrice)]\n      : [mint1, mint2, initialPrice];\n\n    const initialPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(initPrice, mintA.decimals, mintB.decimals);\n\n    const extendMintAccount: PublicKey[] = [];\n    const fetchAccounts: PublicKey[] = [];\n    if (mintA.programId === TOKEN_2022_PROGRAM_ID.toBase58())\n      fetchAccounts.push(getPdaMintExAccount(programId, new PublicKey(mintA.address)).publicKey);\n    if (mintB.programId === TOKEN_2022_PROGRAM_ID.toBase58())\n      fetchAccounts.push(getPdaMintExAccount(programId, new PublicKey(mintB.address)).publicKey);\n    const extMintRes = await this.scope.connection.getMultipleAccountsInfo(fetchAccounts);\n\n    extMintRes.forEach((r, idx) => {\n      if (r) extendMintAccount.push(fetchAccounts[idx]);\n    });\n\n    const insInfo = await ClmmInstrument.createPoolInstructions({\n      connection: this.scope.connection,\n      programId,\n      owner,\n      mintA,\n      mintB,\n      ammConfigId: ammConfig.id,\n      initialPriceX64,\n      forerunCreate: !getObserveState && forerunCreate,\n      extendMintAccount,\n    });\n\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n\n    return txBuilder.versionBuild<{\n      mockPoolInfo: ApiV3PoolInfoConcentratedItem;\n      address: ClmmKeys;\n      forerunCreate?: boolean;\n    }>({\n      txVersion,\n      extInfo: {\n        address: {\n          ...insInfo.address,\n          observationId: insInfo.address.observationId.toBase58(),\n          exBitmapAccount: insInfo.address.exBitmapAccount.toBase58(),\n          programId: programId.toString(),\n          id: insInfo.address.poolId.toString(),\n          mintA,\n          mintB,\n          openTime: \"0\",\n          vault: { A: insInfo.address.mintAVault.toString(), B: insInfo.address.mintBVault.toString() },\n          rewardInfos: [],\n          config: {\n            id: ammConfig.id.toString(),\n            index: ammConfig.index,\n            protocolFeeRate: ammConfig.protocolFeeRate,\n            tradeFeeRate: ammConfig.tradeFeeRate,\n            tickSpacing: ammConfig.tickSpacing,\n            fundFeeRate: ammConfig.fundFeeRate,\n            description: ammConfig.description,\n            defaultRange: 0,\n            defaultRangePoint: [],\n          },\n        },\n        mockPoolInfo: {\n          type: \"Concentrated\",\n          rewardDefaultPoolInfos: \"Clmm\",\n          id: insInfo.address.poolId.toString(),\n          mintA,\n          mintB,\n          feeRate: ammConfig.tradeFeeRate,\n          openTime: \"0\",\n          programId: programId.toString(),\n          price: initPrice.toNumber(),\n          config: {\n            id: ammConfig.id.toString(),\n            index: ammConfig.index,\n            protocolFeeRate: ammConfig.protocolFeeRate,\n            tradeFeeRate: ammConfig.tradeFeeRate,\n            tickSpacing: ammConfig.tickSpacing,\n            fundFeeRate: ammConfig.fundFeeRate,\n            description: ammConfig.description,\n            defaultRange: 0,\n            defaultRangePoint: [],\n          },\n          burnPercent: 0,\n          ...mockV3CreatePoolInfo,\n        },\n        forerunCreate,\n      },\n    }) as Promise<MakeTxData<T, { mockPoolInfo: ApiV3PoolInfoConcentratedItem; address: ClmmKeys }>>;\n  }\n\n  public async openPositionFromBase<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    base,\n    baseAmount,\n    otherAmountMax,\n    nft2022,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    withMetadata = \"create\",\n    getEphemeralSigners,\n    computeBudgetConfig,\n    txTipConfig,\n    txVersion,\n    feePayer,\n  }: OpenPositionFromBase<T>): Promise<MakeTxData<T, OpenPositionFromBaseExtInfo>> {\n    if (this.scope.availability.addConcentratedPosition === false)\n      this.logAndCreateError(\"add position feature disabled in your region\");\n\n    this.scope.checkOwner();\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    let ownerTokenAccountA: PublicKey | null = null;\n    let ownerTokenAccountB: PublicKey | null = null;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toString();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toString();\n    const [amountA, amountB] = base === \"MintA\" ? [baseAmount, otherAmountMax] : [otherAmountMax, baseAmount];\n\n    const { account: _ownerTokenAccountA, instructionParams: _tokenAccountAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintAUseSOLBalance || amountA.isZero()\n            ? {\n                payer: this.scope.ownerPubKey,\n                amount: amountA,\n              }\n            : undefined,\n        skipCloseAccount: !mintAUseSOLBalance,\n        notUseTokenAccount: mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountA) ownerTokenAccountA = _ownerTokenAccountA;\n    txBuilder.addInstruction(_tokenAccountAInstruction || {});\n\n    const { account: _ownerTokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintBUseSOLBalance || amountB.isZero()\n            ? {\n                payer: this.scope.ownerPubKey!,\n                amount: amountB,\n              }\n            : undefined,\n        skipCloseAccount: !mintBUseSOLBalance,\n        notUseTokenAccount: mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountB) ownerTokenAccountB = _ownerTokenAccountB;\n    txBuilder.addInstruction(_tokenAccountBInstruction || {});\n\n    if (!ownerTokenAccountA || !ownerTokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", {\n        ownerTokenAccountA: ownerTokenAccountA?.toBase58(),\n        ownerTokenAccountB: ownerTokenAccountB?.toBase58(),\n      });\n\n    const poolKeys = propPoolKeys || (await this.getClmmPoolKeys(poolInfo.id));\n    const insInfo = await ClmmInstrument.openPositionFromBaseInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        ...ownerInfo,\n        feePayer: this.scope.ownerPubKey,\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA: ownerTokenAccountA!,\n        tokenAccountB: ownerTokenAccountB!,\n      },\n      tickLower,\n      tickUpper,\n      base,\n      baseAmount,\n      otherAmountMax,\n      withMetadata,\n      getEphemeralSigners,\n      nft2022,\n    });\n\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<OpenPositionFromBaseExtInfo>({\n      txVersion,\n      extInfo: { ...insInfo.address },\n    }) as Promise<MakeTxData<T, OpenPositionFromBaseExtInfo>>;\n  }\n\n  public async openPositionFromLiquidity<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    ownerInfo,\n    amountMaxA,\n    amountMaxB,\n    tickLower,\n    tickUpper,\n    liquidity,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    withMetadata = \"create\",\n    txVersion,\n    computeBudgetConfig,\n    txTipConfig,\n    getEphemeralSigners,\n    nft2022,\n    feePayer,\n  }: OpenPositionFromLiquidity<T>): Promise<MakeTxData<T, OpenPositionFromLiquidityExtInfo>> {\n    if (this.scope.availability.createConcentratedPosition === false)\n      this.logAndCreateError(\"open position feature disabled in your region\");\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    let ownerTokenAccountA: PublicKey | null = null;\n    let ownerTokenAccountB: PublicKey | null = null;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toBase58();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toBase58();\n\n    const { account: _ownerTokenAccountA, instructionParams: _tokenAccountAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintAUseSOLBalance || amountMaxA.isZero()\n            ? {\n                payer: this.scope.ownerPubKey,\n                amount: amountMaxA,\n              }\n            : undefined,\n\n        skipCloseAccount: !mintAUseSOLBalance,\n        notUseTokenAccount: mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountA) ownerTokenAccountA = _ownerTokenAccountA;\n    txBuilder.addInstruction(_tokenAccountAInstruction || {});\n\n    const { account: _ownerTokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintBUseSOLBalance || amountMaxB.isZero()\n            ? {\n                payer: this.scope.ownerPubKey!,\n                amount: amountMaxB,\n              }\n            : undefined,\n        skipCloseAccount: !mintBUseSOLBalance,\n        notUseTokenAccount: mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountB) ownerTokenAccountB = _ownerTokenAccountB;\n    txBuilder.addInstruction(_tokenAccountBInstruction || {});\n\n    if (ownerTokenAccountA === undefined || ownerTokenAccountB === undefined)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", this.scope.account.tokenAccounts);\n\n    const poolKeys = propPoolKeys || (await this.getClmmPoolKeys(poolInfo.id));\n\n    const makeOpenPositionInstructions = await ClmmInstrument.openPositionFromLiquidityInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA: ownerTokenAccountA!,\n        tokenAccountB: ownerTokenAccountB!,\n      },\n      tickLower,\n      tickUpper,\n      liquidity,\n      amountMaxA,\n      amountMaxB,\n      withMetadata,\n      getEphemeralSigners,\n      nft2022,\n    });\n    txBuilder.addInstruction(makeOpenPositionInstructions);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<OpenPositionFromLiquidityExtInfo>({\n      txVersion,\n      extInfo: { address: makeOpenPositionInstructions.address },\n    }) as Promise<MakeTxData<T, OpenPositionFromLiquidityExtInfo>>;\n  }\n\n  public async increasePositionFromLiquidity<T extends TxVersion>(\n    props: IncreasePositionFromLiquidity<T>,\n  ): Promise<MakeTxData<T, ManipulateLiquidityExtInfo>> {\n    const {\n      poolInfo,\n      poolKeys: propPoolKeys,\n      ownerPosition,\n      amountMaxA,\n      amountMaxB,\n      liquidity,\n      ownerInfo,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n    } = props;\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    let ownerTokenAccountA: PublicKey | undefined = undefined;\n    let ownerTokenAccountB: PublicKey | undefined = undefined;\n\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toString();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toString();\n    const { account: _ownerTokenAccountA, instructionParams: _tokenAccountAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintAUseSOLBalance || amountMaxA.isZero()\n            ? {\n                payer: this.scope.ownerPubKey,\n                amount: amountMaxA,\n              }\n            : undefined,\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountA) ownerTokenAccountA = _ownerTokenAccountA;\n    txBuilder.addInstruction(_tokenAccountAInstruction || {});\n    const { account: _ownerTokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintBUseSOLBalance || amountMaxB.isZero()\n            ? {\n                payer: this.scope.ownerPubKey!,\n                amount: amountMaxB,\n              }\n            : undefined,\n        notUseTokenAccount: mintBUseSOLBalance,\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountB) ownerTokenAccountB = _ownerTokenAccountB;\n    txBuilder.addInstruction(_tokenAccountBInstruction || {});\n\n    if (!ownerTokenAccountA && !ownerTokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", this.scope.account.tokenAccounts);\n    const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n    const ins = ClmmInstrument.increasePositionFromLiquidityInstructions({\n      poolInfo,\n      poolKeys,\n      ownerPosition,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA: ownerTokenAccountA!,\n        tokenAccountB: ownerTokenAccountB!,\n      },\n      liquidity,\n      amountMaxA,\n      amountMaxB,\n      nft2022: (await this.scope.connection.getAccountInfo(ownerPosition.nftMint))?.owner.equals(TOKEN_2022_PROGRAM_ID),\n    });\n    txBuilder.addInstruction(ins);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<ManipulateLiquidityExtInfo>({\n      txVersion,\n      extInfo: { address: ins.address },\n    }) as Promise<MakeTxData<T, ManipulateLiquidityExtInfo>>;\n  }\n\n  public async increasePositionFromBase<T extends TxVersion>(\n    props: IncreasePositionFromBase<T>,\n  ): Promise<MakeTxData<T, ManipulateLiquidityExtInfo>> {\n    const {\n      poolInfo,\n      ownerPosition,\n      base,\n      baseAmount,\n      otherAmountMax,\n      ownerInfo,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n    } = props;\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    let ownerTokenAccountA: PublicKey | undefined = undefined;\n    let ownerTokenAccountB: PublicKey | undefined = undefined;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toString();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toString();\n\n    const { account: _ownerTokenAccountA, instructionParams: _tokenAccountAInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintAUseSOLBalance || (base === \"MintA\" ? baseAmount : otherAmountMax).isZero()\n            ? {\n                payer: this.scope.ownerPubKey,\n                amount: base === \"MintA\" ? baseAmount : otherAmountMax,\n              }\n            : undefined,\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountA) ownerTokenAccountA = _ownerTokenAccountA;\n    txBuilder.addInstruction(_tokenAccountAInstruction || {});\n\n    const { account: _ownerTokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo:\n          mintBUseSOLBalance || (base === \"MintA\" ? otherAmountMax : baseAmount).isZero()\n            ? {\n                payer: this.scope.ownerPubKey!,\n                amount: base === \"MintA\" ? otherAmountMax : baseAmount,\n              }\n            : undefined,\n        notUseTokenAccount: mintBUseSOLBalance,\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    if (_ownerTokenAccountB) ownerTokenAccountB = _ownerTokenAccountB;\n    txBuilder.addInstruction(_tokenAccountBInstruction || {});\n    if (!ownerTokenAccountA && !ownerTokenAccountB)\n      this.logAndCreateError(\"cannot found target token accounts\", \"tokenAccounts\", this.scope.account.tokenAccounts);\n\n    const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n    const ins = ClmmInstrument.increasePositionFromBaseInstructions({\n      poolInfo,\n      poolKeys,\n      ownerPosition,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA: ownerTokenAccountA!,\n        tokenAccountB: ownerTokenAccountB!,\n      },\n      base,\n      baseAmount,\n      otherAmountMax,\n      nft2022: (await this.scope.connection.getAccountInfo(ownerPosition.nftMint))?.owner.equals(TOKEN_2022_PROGRAM_ID),\n    });\n    txBuilder.addInstruction(ins);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<ManipulateLiquidityExtInfo>({\n      txVersion,\n      extInfo: { address: ins.address },\n    }) as Promise<MakeTxData<T, ManipulateLiquidityExtInfo>>;\n  }\n\n  public async decreaseLiquidity<T extends TxVersion>(\n    props: DecreaseLiquidity<T>,\n  ): Promise<MakeTxData<T, ManipulateLiquidityExtInfo & Partial<ClosePositionExtInfo>>> {\n    const {\n      poolInfo,\n      poolKeys: propPoolKeys,\n      ownerPosition,\n      ownerInfo,\n      amountMinA,\n      amountMinB,\n      liquidity,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n    } = props;\n    if (this.scope.availability.removeConcentratedPosition === false)\n      this.logAndCreateError(\"remove position feature disabled in your region\");\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toString();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toString();\n\n    let ownerTokenAccountA: PublicKey | undefined = undefined;\n    let ownerTokenAccountB: PublicKey | undefined = undefined;\n    const { account: _ownerTokenAccountA, instructionParams: accountAInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerTokenAccountA = _ownerTokenAccountA;\n    accountAInstructions && txBuilder.addInstruction(accountAInstructions);\n\n    const { account: _ownerTokenAccountB, instructionParams: accountBInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerTokenAccountB = _ownerTokenAccountB;\n    accountBInstructions && txBuilder.addInstruction(accountBInstructions);\n\n    const rewardAccounts: PublicKey[] = [];\n    for (const itemReward of poolInfo.rewardDefaultInfos) {\n      const rewardUseSOLBalance = ownerInfo.useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n\n      let ownerRewardAccount: PublicKey | undefined;\n\n      if (itemReward.mint.address === poolInfo.mintA.address) ownerRewardAccount = ownerTokenAccountA;\n      else if (itemReward.mint.address === poolInfo.mintB.address) ownerRewardAccount = ownerTokenAccountB;\n      else {\n        const { account: _ownerRewardAccount, instructionParams: ownerRewardAccountInstructions } =\n          await this.scope.account.getOrCreateTokenAccount({\n            tokenProgram: new PublicKey(itemReward.mint.programId),\n            mint: new PublicKey(itemReward.mint.address),\n            notUseTokenAccount: rewardUseSOLBalance,\n            owner: this.scope.ownerPubKey,\n            createInfo: {\n              payer: this.scope.ownerPubKey,\n              amount: 0,\n            },\n            skipCloseAccount: !rewardUseSOLBalance,\n            associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n            checkCreateATAOwner,\n          });\n        ownerRewardAccount = _ownerRewardAccount;\n        ownerRewardAccountInstructions && txBuilder.addInstruction(ownerRewardAccountInstructions);\n      }\n\n      rewardAccounts.push(ownerRewardAccount!);\n    }\n\n    if (!ownerTokenAccountA && !ownerTokenAccountB)\n      this.logAndCreateError(\n        \"cannot found target token accounts\",\n        \"tokenAccounts\",\n        this.scope.account.tokenAccountRawInfos,\n      );\n\n    const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n    const nft2022 = (await this.scope.connection.getAccountInfo(ownerPosition.nftMint))?.owner.equals(\n      TOKEN_2022_PROGRAM_ID,\n    );\n    const decreaseInsInfo = await ClmmInstrument.decreaseLiquidityInstructions({\n      poolInfo,\n      poolKeys,\n      ownerPosition,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA: ownerTokenAccountA!,\n        tokenAccountB: ownerTokenAccountB!,\n        rewardAccounts,\n      },\n      liquidity,\n      amountMinA,\n      amountMinB,\n      nft2022,\n    });\n\n    txBuilder.addInstruction({\n      instructions: decreaseInsInfo.instructions,\n      instructionTypes: [InstructionType.ClmmDecreasePosition],\n    });\n\n    let extInfo = { ...decreaseInsInfo.address };\n    if (ownerInfo.closePosition) {\n      const closeInsInfo = await ClmmInstrument.closePositionInstructions({\n        poolInfo,\n        poolKeys,\n        ownerInfo: { wallet: this.scope.ownerPubKey },\n        ownerPosition,\n        nft2022,\n      });\n      txBuilder.addInstruction({\n        endInstructions: closeInsInfo.instructions,\n        endInstructionTypes: closeInsInfo.instructionTypes,\n      });\n      extInfo = { ...extInfo, ...closeInsInfo.address };\n    }\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<ManipulateLiquidityExtInfo>({\n      txVersion,\n      extInfo: { address: extInfo },\n    }) as Promise<MakeTxData<T, ManipulateLiquidityExtInfo>>;\n  }\n\n  public async lockPosition<T extends TxVersion>(props: LockPosition<T>): Promise<MakeTxData<ClmmLockAddress>> {\n    const {\n      programId = CLMM_LOCK_PROGRAM_ID,\n      authProgramId = CLMM_LOCK_AUTH_ID,\n      poolProgramId = CLMM_PROGRAM_ID,\n      ownerPosition,\n      payer,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      getEphemeralSigners,\n      feePayer,\n    } = props;\n    const txBuilder = this.createTxBuilder(feePayer);\n    const lockIns = await ClmmInstrument.makeLockPositions({\n      programId,\n      authProgramId,\n      poolProgramId,\n      wallet: this.scope.ownerPubKey,\n      payer: payer ?? this.scope.ownerPubKey,\n      nftMint: ownerPosition.nftMint,\n      getEphemeralSigners,\n      nft2022: (await this.scope.connection.getAccountInfo(ownerPosition.nftMint))?.owner.equals(TOKEN_2022_PROGRAM_ID),\n    });\n\n    txBuilder.addInstruction(lockIns);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({\n      txVersion,\n      extInfo: lockIns.address,\n    }) as Promise<MakeTxData<ClmmLockAddress>>;\n  }\n\n  public async harvestLockPosition<T extends TxVersion>(props: HarvestLockPosition<T>): Promise<MakeTxData<T>> {\n    const {\n      programId = CLMM_LOCK_PROGRAM_ID,\n      authProgramId = CLMM_LOCK_AUTH_ID,\n      clmmProgram = CLMM_PROGRAM_ID,\n      poolKeys: propPoolKeys,\n      lockData,\n      ownerInfo = { useSOLBalance: true },\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txTipConfig,\n      txVersion,\n      feePayer,\n    } = props;\n\n    const poolKeys = propPoolKeys || (await this.getClmmPoolKeys(lockData.poolId.toString()));\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const positionData = await this.scope.connection.getAccountInfo(lockData.positionId);\n    if (!positionData) this.logger.logWithError(\"position not found\", lockData.positionId);\n    const position = PositionInfoLayout.decode(positionData!.data);\n\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolKeys.mintA.address === WSOLMint.toString();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolKeys.mintB.address === WSOLMint.toString();\n\n    let ownerTokenAccountA: PublicKey | undefined = undefined;\n    let ownerTokenAccountB: PublicKey | undefined = undefined;\n    const { account: _ownerTokenAccountA, instructionParams: accountAInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolKeys.mintA.programId,\n        mint: new PublicKey(poolKeys.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerTokenAccountA = _ownerTokenAccountA;\n    accountAInstructions && txBuilder.addInstruction(accountAInstructions);\n\n    const { account: _ownerTokenAccountB, instructionParams: accountBInstructions } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolKeys.mintB.programId,\n        mint: new PublicKey(poolKeys.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerTokenAccountB = _ownerTokenAccountB;\n    accountBInstructions && txBuilder.addInstruction(accountBInstructions);\n\n    const ownerMintToAccount: { [mint: string]: PublicKey } = {};\n    const rewardAccounts: PublicKey[] = [];\n    for (const itemReward of poolKeys.rewardInfos) {\n      const rewardUseSOLBalance = ownerInfo.useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n      let ownerRewardAccount = ownerMintToAccount[itemReward.mint.address];\n      if (!ownerRewardAccount) {\n        const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: new PublicKey(itemReward.mint.programId),\n          mint: new PublicKey(itemReward.mint.address),\n          notUseTokenAccount: rewardUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !rewardUseSOLBalance,\n          createInfo: {\n            payer: this.scope.ownerPubKey,\n            amount: 0,\n          },\n          associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n        });\n        ownerRewardAccount = account!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n\n      ownerMintToAccount[itemReward.mint.address] = ownerRewardAccount;\n      rewardAccounts.push(ownerRewardAccount!);\n    }\n    const lockPositionId = getPdaLockClPositionIdV2(programId, lockData.lockNftMint).publicKey;\n    const lockNftAccount = getATAAddress(this.scope.ownerPubKey, lockData.lockNftMint, TOKEN_PROGRAM_ID).publicKey;\n\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      position.tickLower,\n      poolKeys.config.tickSpacing,\n    );\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      position.tickUpper,\n      poolKeys.config.tickSpacing,\n    );\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(\n      new PublicKey(poolKeys.programId),\n      lockData.poolId,\n      tickArrayLowerStartIndex,\n    );\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(\n      new PublicKey(poolKeys.programId),\n      lockData.poolId,\n      tickArrayUpperStartIndex,\n    );\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n      new PublicKey(poolKeys.programId),\n      lockData.poolId,\n      position.tickLower,\n      position.tickUpper,\n    );\n\n    const rewardAccountsFullInfo: {\n      poolRewardVault: PublicKey;\n      ownerRewardVault: PublicKey;\n      rewardMint: PublicKey;\n    }[] = [];\n    for (let i = 0; i < poolKeys.rewardInfos.length; i++) {\n      rewardAccountsFullInfo.push({\n        poolRewardVault: new PublicKey(poolKeys.rewardInfos[i].vault),\n        ownerRewardVault: rewardAccounts[i],\n        rewardMint: new PublicKey(poolKeys.rewardInfos[i].mint.address),\n      });\n    }\n\n    const harvestLockIns = await ClmmInstrument.harvestLockPositionInstructionV2({\n      programId,\n      auth: authProgramId,\n      lockPositionId,\n      clmmProgram,\n      lockOwner: this.scope.ownerPubKey,\n      lockNftMint: lockData.lockNftMint,\n      lockNftAccount,\n      positionNftAccount: lockData.nftAccount,\n      positionId: lockData.positionId,\n      poolId: lockData.poolId,\n      protocolPosition,\n      vaultA: new PublicKey(poolKeys.vault.A),\n      vaultB: new PublicKey(poolKeys.vault.B),\n      tickArrayLower,\n      tickArrayUpper,\n      userVaultA: ownerTokenAccountA!,\n      userVaultB: ownerTokenAccountB!,\n      mintA: new PublicKey(poolKeys.mintA.address),\n      mintB: new PublicKey(poolKeys.mintB.address),\n      rewardAccounts: rewardAccountsFullInfo,\n      exTickArrayBitmap: getPdaExBitmapAccount(clmmProgram, lockData.poolId).publicKey,\n    });\n\n    txBuilder.addInstruction({\n      instructions: [harvestLockIns],\n      instructionTypes: [InstructionType.ClmmHarvestLockPosition],\n    });\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({\n      txVersion,\n    }) as Promise<MakeTxData<T>>;\n  }\n\n  public async closePosition<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    ownerPosition,\n    txVersion,\n    computeBudgetConfig,\n    txTipConfig,\n    feePayer,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys?: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n    computeBudgetConfig?: ComputeBudgetConfig;\n    txTipConfig?: TxTipConfig;\n    txVersion: T;\n    feePayer?: PublicKey;\n  }): Promise<MakeTxData<T, ClosePositionExtInfo>> {\n    if (this.scope.availability.removeConcentratedPosition === false)\n      this.logAndCreateError(\"remove position feature disabled in your region\");\n    const txBuilder = this.createTxBuilder(feePayer);\n    const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n    const ins = ClmmInstrument.closePositionInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: { wallet: this.scope.ownerPubKey },\n      ownerPosition,\n      nft2022: (await this.scope.connection.getAccountInfo(ownerPosition.nftMint))?.owner.equals(TOKEN_2022_PROGRAM_ID),\n    });\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.addInstruction(ins).versionBuild<ClosePositionExtInfo>({\n      txVersion,\n      extInfo: { address: ins.address },\n    }) as Promise<MakeTxData<T, ClosePositionExtInfo>>;\n  }\n\n  public async initReward<T extends TxVersion>({\n    poolInfo,\n    ownerInfo,\n    rewardInfo,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txVersion,\n    feePayer,\n  }: InitRewardParams<T>): Promise<MakeTxData<T, InitRewardExtInfo>> {\n    if (rewardInfo.endTime <= rewardInfo.openTime)\n      this.logAndCreateError(\"reward time error\", \"rewardInfo\", rewardInfo);\n\n    const txBuilder = this.createTxBuilder(feePayer);\n\n    const rewardMintUseSOLBalance =\n      ownerInfo.useSOLBalance && rewardInfo.mint.address.toString() === WSOLMint.toString();\n    const _baseRewardAmount = rewardInfo.perSecond.mul(rewardInfo.endTime - rewardInfo.openTime);\n\n    const { account: ownerRewardAccount, instructionParams: ownerRewardAccountIns } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: new PublicKey(rewardInfo.mint.address),\n        mint: new PublicKey(rewardInfo.mint.address),\n        notUseTokenAccount: !!rewardMintUseSOLBalance,\n        skipCloseAccount: !rewardMintUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: rewardMintUseSOLBalance\n          ? {\n              payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n              amount: new BN(\n                new Decimal(_baseRewardAmount.toFixed(0)).gte(_baseRewardAmount)\n                  ? _baseRewardAmount.toFixed(0)\n                  : _baseRewardAmount.add(1).toFixed(0),\n              ),\n            }\n          : undefined,\n        associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerRewardAccountIns && txBuilder.addInstruction(ownerRewardAccountIns);\n\n    if (!ownerRewardAccount)\n      this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n    const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n    const insInfo = ClmmInstrument.initRewardInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccount: ownerRewardAccount!,\n      },\n      rewardInfo: {\n        programId: new PublicKey(rewardInfo.mint.programId),\n        mint: new PublicKey(rewardInfo.mint.address),\n        openTime: rewardInfo.openTime,\n        endTime: rewardInfo.endTime,\n        emissionsPerSecondX64: MathUtil.decimalToX64(rewardInfo.perSecond),\n      },\n    });\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    return txBuilder.versionBuild<InitRewardExtInfo>({\n      txVersion,\n      extInfo: { address: insInfo.address },\n    }) as Promise<MakeTxData<T, InitRewardExtInfo>>;\n  }\n\n  public async initRewards<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    ownerInfo,\n    rewardInfos,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txTipConfig,\n    txVersion,\n    feePayer,\n  }: InitRewardsParams<T>): Promise<MakeTxData<T, { address: Record<string, PublicKey> }>> {\n    for (const rewardInfo of rewardInfos) {\n      if (rewardInfo.endTime <= rewardInfo.openTime)\n        this.logAndCreateError(\"reward time error\", \"rewardInfo\", rewardInfo);\n    }\n\n    const txBuilder = this.createTxBuilder(feePayer);\n    let address: Record<string, PublicKey> = {};\n\n    for (const rewardInfo of rewardInfos) {\n      const rewardMintUseSOLBalance = ownerInfo.useSOLBalance && rewardInfo.mint.address === WSOLMint.toString();\n      const _baseRewardAmount = rewardInfo.perSecond.mul(rewardInfo.endTime - rewardInfo.openTime);\n\n      const { account: ownerRewardAccount, instructionParams: ownerRewardAccountIns } =\n        await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: new PublicKey(rewardInfo.mint.programId),\n          mint: new PublicKey(rewardInfo.mint.address),\n          notUseTokenAccount: !!rewardMintUseSOLBalance,\n          skipCloseAccount: !rewardMintUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          createInfo: rewardMintUseSOLBalance\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: new BN(\n                  new Decimal(_baseRewardAmount.toFixed(0)).gte(_baseRewardAmount)\n                    ? _baseRewardAmount.toFixed(0)\n                    : _baseRewardAmount.add(1).toFixed(0),\n                ),\n              }\n            : undefined,\n          associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n      ownerRewardAccountIns && txBuilder.addInstruction(ownerRewardAccountIns);\n\n      if (!ownerRewardAccount)\n        this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n\n      const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n      const insInfo = ClmmInstrument.initRewardInstructions({\n        poolInfo,\n        poolKeys,\n        ownerInfo: {\n          wallet: this.scope.ownerPubKey,\n          tokenAccount: ownerRewardAccount!,\n        },\n        rewardInfo: {\n          programId: new PublicKey(rewardInfo.mint.programId),\n          mint: new PublicKey(rewardInfo.mint.address),\n          openTime: rewardInfo.openTime,\n          endTime: rewardInfo.endTime,\n          emissionsPerSecondX64: MathUtil.decimalToX64(rewardInfo.perSecond),\n        },\n      });\n      address = {\n        ...address,\n        ...insInfo.address,\n      };\n      txBuilder.addInstruction(insInfo);\n    }\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({\n      txVersion,\n      extInfo: { address },\n    }) as Promise<MakeTxData<T, { address: Record<string, PublicKey> }>>;\n  }\n\n  public async setReward<T extends TxVersion>({\n    poolInfo,\n    ownerInfo,\n    rewardInfo,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txTipConfig,\n    txVersion,\n    feePayer,\n  }: SetRewardParams<T>): Promise<MakeTxData<T, { address: Record<string, PublicKey> }>> {\n    if (rewardInfo.endTime <= rewardInfo.openTime)\n      this.logAndCreateError(\"reward time error\", \"rewardInfo\", rewardInfo);\n\n    const txBuilder = this.createTxBuilder(feePayer);\n    const rewardMintUseSOLBalance = ownerInfo.useSOLBalance && rewardInfo.mint.equals(WSOLMint);\n    const { account: ownerRewardAccount, instructionParams: ownerRewardIns } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: rewardInfo.programId,\n        mint: rewardInfo.mint,\n        notUseTokenAccount: rewardMintUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        createInfo: rewardMintUseSOLBalance\n          ? {\n              payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n              amount: new BN(\n                new Decimal(rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime).toFixed(0)).gte(\n                  rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime),\n                )\n                  ? rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime).toFixed(0)\n                  : rewardInfo.perSecond\n                      .sub(rewardInfo.endTime - rewardInfo.openTime)\n                      .add(1)\n                      .toFixed(0),\n              ),\n            }\n          : undefined,\n\n        associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerRewardIns && txBuilder.addInstruction(ownerRewardIns);\n    if (!ownerRewardAccount)\n      this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n    const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n    const insInfo = ClmmInstrument.setRewardInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccount: ownerRewardAccount!,\n      },\n      rewardInfo: {\n        mint: rewardInfo.mint,\n        openTime: rewardInfo.openTime,\n        endTime: rewardInfo.endTime,\n        emissionsPerSecondX64: MathUtil.decimalToX64(rewardInfo.perSecond),\n      },\n    });\n\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<{ address: Record<string, PublicKey> }>({\n      txVersion,\n      extInfo: { address: insInfo.address },\n    }) as Promise<MakeTxData<T, { address: Record<string, PublicKey> }>>;\n  }\n\n  public async setRewards<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    ownerInfo,\n    rewardInfos,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txTipConfig,\n    txVersion,\n    feePayer,\n  }: SetRewardsParams<T>): Promise<MakeTxData<T, { address: Record<string, PublicKey> }>> {\n    const txBuilder = this.createTxBuilder(feePayer);\n    let address: Record<string, PublicKey> = {};\n    for (const rewardInfo of rewardInfos) {\n      if (rewardInfo.endTime <= rewardInfo.openTime)\n        this.logAndCreateError(\"reward time error\", \"rewardInfo\", rewardInfo);\n\n      const rewardMintUseSOLBalance = ownerInfo.useSOLBalance && rewardInfo.mint.address === WSOLMint.toString();\n      const { account: ownerRewardAccount, instructionParams: ownerRewardIns } =\n        await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: new PublicKey(rewardInfo.mint.programId),\n          mint: new PublicKey(rewardInfo.mint.address),\n          notUseTokenAccount: rewardMintUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          createInfo: rewardMintUseSOLBalance\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: new BN(\n                  new Decimal(rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime).toFixed(0)).gte(\n                    rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime),\n                  )\n                    ? rewardInfo.perSecond.sub(rewardInfo.endTime - rewardInfo.openTime).toFixed(0)\n                    : rewardInfo.perSecond\n                        .sub(rewardInfo.endTime - rewardInfo.openTime)\n                        .add(1)\n                        .toFixed(0),\n                ),\n              }\n            : undefined,\n          associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n      ownerRewardIns && txBuilder.addInstruction(ownerRewardIns);\n      if (!ownerRewardAccount)\n        this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n      const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n      const insInfo = ClmmInstrument.setRewardInstructions({\n        poolInfo,\n        poolKeys,\n        ownerInfo: {\n          wallet: this.scope.ownerPubKey,\n          tokenAccount: ownerRewardAccount!,\n        },\n        rewardInfo: {\n          mint: new PublicKey(rewardInfo.mint.address),\n          openTime: rewardInfo.openTime,\n          endTime: rewardInfo.endTime,\n          emissionsPerSecondX64: MathUtil.decimalToX64(rewardInfo.perSecond),\n        },\n      });\n      txBuilder.addInstruction(insInfo);\n      address = {\n        ...address,\n        ...insInfo.address,\n      };\n    }\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<{ address: Record<string, PublicKey> }>({\n      txVersion,\n      extInfo: { address },\n    }) as Promise<MakeTxData<T, { address: Record<string, PublicKey> }>>;\n  }\n\n  public async collectReward<T extends TxVersion>({\n    poolInfo,\n    ownerInfo,\n    rewardMint,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txTipConfig,\n    txVersion,\n    feePayer,\n  }: CollectRewardParams<T>): Promise<MakeTxData<{ address: Record<string, PublicKey> }>> {\n    const rewardInfo = poolInfo!.rewardDefaultInfos.find((i) => i.mint.address === rewardMint.toString());\n    if (!rewardInfo) this.logAndCreateError(\"reward mint error\", \"not found reward mint\", rewardMint);\n\n    const txBuilder = this.createTxBuilder(feePayer);\n    const rewardMintUseSOLBalance = ownerInfo.useSOLBalance && rewardMint.equals(WSOLMint);\n    const { account: ownerRewardAccount, instructionParams: ownerRewardIns } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: new PublicKey(rewardInfo!.mint.programId),\n        mint: rewardMint,\n        notUseTokenAccount: rewardMintUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !rewardMintUseSOLBalance,\n        createInfo: {\n          payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n          amount: 0,\n        },\n        associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    ownerRewardIns && txBuilder.addInstruction(ownerRewardIns);\n\n    if (!ownerRewardAccount)\n      this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n    const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n    const insInfo = ClmmInstrument.collectRewardInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        tokenAccount: ownerRewardAccount!,\n      },\n      rewardMint,\n    });\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild<{ address: Record<string, PublicKey> }>({\n      txVersion,\n      extInfo: { address: insInfo.address },\n    }) as Promise<MakeTxData<{ address: Record<string, PublicKey> }>>;\n  }\n\n  public async collectRewards({\n    poolInfo,\n    ownerInfo,\n    rewardMints,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txTipConfig,\n    feePayer,\n  }: CollectRewardsParams): Promise<MakeTransaction> {\n    const txBuilder = this.createTxBuilder(feePayer);\n    let address: Record<string, PublicKey> = {};\n\n    for (const rewardMint of rewardMints) {\n      const rewardInfo = poolInfo!.rewardDefaultInfos.find((i) => i.mint.address === rewardMint.toString());\n      if (!rewardInfo) {\n        this.logAndCreateError(\"reward mint error\", \"not found reward mint\", rewardMint);\n        continue;\n      }\n\n      const rewardMintUseSOLBalance = ownerInfo.useSOLBalance && rewardMint.equals(WSOLMint);\n      const { account: ownerRewardAccount, instructionParams: ownerRewardIns } =\n        await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: new PublicKey(rewardInfo.mint.programId),\n          mint: rewardMint,\n          notUseTokenAccount: rewardMintUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !rewardMintUseSOLBalance,\n          createInfo: {\n            payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          associatedOnly: rewardMintUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n      if (!ownerRewardAccount)\n        this.logAndCreateError(\"no money\", \"ownerRewardAccount\", this.scope.account.tokenAccountRawInfos);\n      ownerRewardIns && txBuilder.addInstruction(ownerRewardIns);\n      const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n      const insInfo = ClmmInstrument.collectRewardInstructions({\n        poolInfo,\n        poolKeys,\n        ownerInfo: {\n          wallet: this.scope.ownerPubKey,\n          tokenAccount: ownerRewardAccount!,\n        },\n\n        rewardMint,\n      });\n      txBuilder.addInstruction(insInfo);\n      address = { ...address, ...insInfo.address };\n    }\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.build<{ address: Record<string, PublicKey> }>({ address });\n  }\n\n  public async swap<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    inputMint,\n    amountIn,\n    amountOutMin,\n    priceLimit,\n    observationId,\n    ownerInfo,\n    remainingAccounts,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    txVersion,\n    computeBudgetConfig,\n    txTipConfig,\n    feePayer,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys?: ClmmKeys;\n    inputMint: string | PublicKey;\n    amountIn: BN;\n    amountOutMin: BN;\n    priceLimit?: Decimal;\n    observationId: PublicKey;\n    ownerInfo: {\n      useSOLBalance?: boolean;\n      feePayer?: PublicKey;\n    };\n    remainingAccounts: PublicKey[];\n    associatedOnly?: boolean;\n    checkCreateATAOwner?: boolean;\n    txVersion?: T;\n    computeBudgetConfig?: ComputeBudgetConfig;\n    txTipConfig?: TxTipConfig;\n    feePayer?: PublicKey;\n  }): Promise<MakeTxData<T>> {\n    const txBuilder = this.createTxBuilder(feePayer);\n    const baseIn = inputMint.toString() === poolInfo.mintA.address;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toBase58();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toBase58();\n\n    let sqrtPriceLimitX64: BN;\n    if (!priceLimit || priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 = baseIn ? MIN_SQRT_PRICE_X64.add(new BN(1)) : MAX_SQRT_PRICE_X64.sub(new BN(1));\n    } else {\n      sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n        priceLimit,\n        poolInfo.mintA.decimals,\n        poolInfo.mintB.decimals,\n      );\n    }\n\n    let ownerTokenAccountA: PublicKey | undefined;\n    if (!ownerTokenAccountA) {\n      const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !mintAUseSOLBalance,\n        createInfo:\n          mintAUseSOLBalance || !baseIn\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: baseIn ? amountIn : 0,\n              }\n            : undefined,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n      ownerTokenAccountA = account!;\n      instructionParams && txBuilder.addInstruction(instructionParams);\n    }\n\n    let ownerTokenAccountB: PublicKey | undefined;\n    if (!ownerTokenAccountB) {\n      const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !mintBUseSOLBalance,\n        createInfo:\n          mintBUseSOLBalance || baseIn\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: baseIn ? 0 : amountIn,\n              }\n            : undefined,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n      ownerTokenAccountB = account!;\n      instructionParams && txBuilder.addInstruction(instructionParams);\n    }\n\n    if (!ownerTokenAccountA || !ownerTokenAccountB)\n      this.logAndCreateError(\"user do not have token account\", {\n        tokenA: poolInfo.mintA.symbol || poolInfo.mintA.address,\n        tokenB: poolInfo.mintB.symbol || poolInfo.mintB.address,\n        ownerTokenAccountA,\n        ownerTokenAccountB,\n        mintAUseSOLBalance,\n        mintBUseSOLBalance,\n        associatedOnly,\n      });\n\n    const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n    txBuilder.addInstruction(\n      ClmmInstrument.makeSwapBaseInInstructions({\n        poolInfo,\n        poolKeys,\n        observationId,\n        ownerInfo: {\n          wallet: this.scope.ownerPubKey,\n          tokenAccountA: ownerTokenAccountA!,\n          tokenAccountB: ownerTokenAccountB!,\n        },\n        inputMint: new PublicKey(inputMint),\n        amountIn,\n        amountOutMin,\n        sqrtPriceLimitX64,\n        remainingAccounts,\n      }),\n    );\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async swapBaseOut<T extends TxVersion>({\n    poolInfo,\n    poolKeys: propPoolKeys,\n    outputMint,\n    amountOut,\n    amountInMax,\n    priceLimit,\n    observationId,\n    ownerInfo,\n    remainingAccounts,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    txVersion,\n    computeBudgetConfig,\n    txTipConfig,\n    feePayer,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys?: ClmmKeys;\n    outputMint: string | PublicKey;\n    amountOut: BN;\n    amountInMax: BN;\n    priceLimit?: Decimal;\n    observationId: PublicKey;\n    ownerInfo: {\n      useSOLBalance?: boolean;\n      feePayer?: PublicKey;\n    };\n    remainingAccounts: PublicKey[];\n    associatedOnly?: boolean;\n    checkCreateATAOwner?: boolean;\n    txVersion?: T;\n    computeBudgetConfig?: ComputeBudgetConfig;\n    txTipConfig?: TxTipConfig;\n    feePayer?: PublicKey;\n  }): Promise<MakeTxData<T>> {\n    const txBuilder = this.createTxBuilder(feePayer);\n    const baseIn = outputMint.toString() === poolInfo.mintB.address;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toBase58();\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toBase58();\n\n    let sqrtPriceLimitX64: BN;\n    if (!priceLimit || priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 =\n        outputMint.toString() === poolInfo.mintB.address\n          ? MIN_SQRT_PRICE_X64.add(new BN(1))\n          : MAX_SQRT_PRICE_X64.sub(new BN(1));\n    } else {\n      sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n        priceLimit,\n        poolInfo.mintA.decimals,\n        poolInfo.mintB.decimals,\n      );\n    }\n\n    let ownerTokenAccountA: PublicKey | undefined;\n    if (!ownerTokenAccountA) {\n      const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintA.programId,\n        mint: new PublicKey(poolInfo.mintA.address),\n        notUseTokenAccount: mintAUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !mintAUseSOLBalance,\n        createInfo:\n          mintAUseSOLBalance || !baseIn\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: baseIn ? amountInMax : 0,\n              }\n            : undefined,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n      ownerTokenAccountA = account!;\n      instructionParams && txBuilder.addInstruction(instructionParams);\n    }\n\n    let ownerTokenAccountB: PublicKey | undefined;\n    if (!ownerTokenAccountB) {\n      const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolInfo.mintB.programId,\n        mint: new PublicKey(poolInfo.mintB.address),\n        notUseTokenAccount: mintBUseSOLBalance,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !mintBUseSOLBalance,\n        createInfo:\n          mintBUseSOLBalance || baseIn\n            ? {\n                payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n                amount: baseIn ? 0 : amountInMax,\n              }\n            : undefined,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n      ownerTokenAccountB = account!;\n      instructionParams && txBuilder.addInstruction(instructionParams);\n    }\n\n    if (!ownerTokenAccountA || !ownerTokenAccountB)\n      this.logAndCreateError(\"user do not have token account\", {\n        tokenA: poolInfo.mintA.symbol || poolInfo.mintA.address,\n        tokenB: poolInfo.mintB.symbol || poolInfo.mintB.address,\n        ownerTokenAccountA,\n        ownerTokenAccountB,\n        mintAUseSOLBalance,\n        mintBUseSOLBalance,\n        associatedOnly,\n      });\n\n    const poolKeys = propPoolKeys ?? (await this.getClmmPoolKeys(poolInfo.id));\n    txBuilder.addInstruction(\n      ClmmInstrument.makeSwapBaseOutInstructions({\n        poolInfo,\n        poolKeys,\n        observationId,\n        ownerInfo: {\n          wallet: this.scope.ownerPubKey,\n          tokenAccountA: ownerTokenAccountA!,\n          tokenAccountB: ownerTokenAccountB!,\n        },\n        outputMint: new PublicKey(outputMint),\n        amountOut,\n        amountInMax,\n        sqrtPriceLimitX64,\n        remainingAccounts,\n      }),\n    );\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    txBuilder.addTipInstruction(txTipConfig);\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async harvestAllRewards<T extends TxVersion = TxVersion.LEGACY>({\n    allPoolInfo,\n    allPositions,\n    lockInfo,\n    ownerInfo,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    programId,\n    txVersion,\n    computeBudgetConfig,\n    feePayer,\n  }: HarvestAllRewardsParams<T>): Promise<MakeMultiTxData<T>> {\n    const ownerMintToAccount: { [mint: string]: PublicKey } = {};\n    for (const item of this.scope.account.tokenAccountRawInfos) {\n      if (associatedOnly) {\n        const ata = getATAAddress(this.scope.ownerPubKey, item.accountInfo.mint, programId).publicKey;\n        if (ata.equals(item.pubkey)) ownerMintToAccount[item.accountInfo.mint.toString()] = item.pubkey;\n      } else {\n        ownerMintToAccount[item.accountInfo.mint.toString()] = item.pubkey;\n      }\n    }\n    const allNftMints = Object.values(allPositions)\n      .flat()\n      .map((p) => p.nftMint);\n\n    const mintData = await getMultipleAccountsInfoWithCustomFlags(\n      this.scope.connection,\n      allNftMints.map((n) => ({ pubkey: n })),\n    );\n    const record: Record<string, PublicKey | null> = {};\n    mintData.forEach((data) => {\n      record[data.pubkey.toBase58()] = data?.accountInfo?.owner ?? null;\n    });\n\n    const txBuilder = this.createTxBuilder(feePayer);\n    for (const itemInfo of Object.values(allPoolInfo)) {\n      if (allPositions[itemInfo.id] === undefined) continue;\n      if (\n        !allPositions[itemInfo.id].find(\n          (i) => !i.liquidity.isZero() || i.rewardInfos.find((ii) => !ii.rewardAmountOwed.isZero()),\n        )\n      )\n        continue;\n\n      const poolInfo = itemInfo;\n      const mintAUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintA.address === WSOLMint.toString();\n      const mintBUseSOLBalance = ownerInfo.useSOLBalance && poolInfo.mintB.address === WSOLMint.toString();\n\n      let ownerTokenAccountA = ownerMintToAccount[poolInfo.mintA.address];\n      if (!ownerTokenAccountA) {\n        const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: poolInfo.mintA.programId,\n          mint: new PublicKey(poolInfo.mintA.address),\n          notUseTokenAccount: mintAUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !mintAUseSOLBalance,\n          createInfo: {\n            payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n        ownerTokenAccountA = account!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n\n      let ownerTokenAccountB = ownerMintToAccount[poolInfo.mintB.address];\n      if (!ownerTokenAccountB) {\n        const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          tokenProgram: poolInfo.mintB.programId,\n          mint: new PublicKey(poolInfo.mintB.address),\n          notUseTokenAccount: mintBUseSOLBalance,\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !mintBUseSOLBalance,\n          createInfo: {\n            payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n        ownerTokenAccountB = account!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n\n      ownerMintToAccount[poolInfo.mintA.address] = ownerTokenAccountA;\n      ownerMintToAccount[poolInfo.mintB.address] = ownerTokenAccountB;\n\n      const rewardAccounts: PublicKey[] = [];\n\n      for (const itemReward of poolInfo.rewardDefaultInfos) {\n        const rewardUseSOLBalance = ownerInfo.useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n        let ownerRewardAccount = ownerMintToAccount[itemReward.mint.address];\n        if (!ownerRewardAccount) {\n          const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n            tokenProgram: new PublicKey(itemReward.mint.programId),\n            mint: new PublicKey(itemReward.mint.address),\n            notUseTokenAccount: rewardUseSOLBalance,\n            owner: this.scope.ownerPubKey,\n            skipCloseAccount: !rewardUseSOLBalance,\n            createInfo: {\n              payer: ownerInfo.feePayer || this.scope.ownerPubKey,\n              amount: 0,\n            },\n            associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n          });\n          ownerRewardAccount = account!;\n          instructionParams && txBuilder.addInstruction(instructionParams);\n        }\n\n        ownerMintToAccount[itemReward.mint.address] = ownerRewardAccount;\n        rewardAccounts.push(ownerRewardAccount!);\n      }\n\n      const poolKeys = await this.getClmmPoolKeys(poolInfo.id);\n\n      const rewardAccountsFullInfo: {\n        poolRewardVault: PublicKey;\n        ownerRewardVault: PublicKey;\n        rewardMint: PublicKey;\n      }[] = [];\n      for (let i = 0; i < poolKeys.rewardInfos.length; i++) {\n        rewardAccountsFullInfo.push({\n          poolRewardVault: new PublicKey(poolKeys.rewardInfos[i].vault),\n          ownerRewardVault: rewardAccounts[i],\n          rewardMint: new PublicKey(poolKeys.rewardInfos[i].mint.address),\n        });\n      }\n\n      for (const itemPosition of allPositions[itemInfo.id]) {\n        const lockData = lockInfo?.[itemInfo.id]?.[itemPosition.nftMint.toBase58()];\n        if (lockData) {\n          const lockNftAccount = getATAAddress(\n            this.scope.ownerPubKey,\n            lockData.lockNftMint,\n            TOKEN_PROGRAM_ID,\n          ).publicKey;\n\n          const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n            itemPosition.tickLower,\n            poolKeys.config.tickSpacing,\n          );\n          const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n            itemPosition.tickUpper,\n            poolKeys.config.tickSpacing,\n          );\n          const { publicKey: tickArrayLower } = getPdaTickArrayAddress(\n            new PublicKey(poolKeys.programId),\n            lockData.poolId,\n            tickArrayLowerStartIndex,\n          );\n          const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(\n            new PublicKey(poolKeys.programId),\n            lockData.poolId,\n            tickArrayUpperStartIndex,\n          );\n          const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n            new PublicKey(poolKeys.programId),\n            lockData.poolId,\n            itemPosition.tickLower,\n            itemPosition.tickUpper,\n          );\n          const lockPositionId = getPdaLockClPositionIdV2(CLMM_LOCK_PROGRAM_ID, lockData.lockNftMint).publicKey;\n          const harvestLockIns = ClmmInstrument.harvestLockPositionInstructionV2({\n            programId: CLMM_LOCK_PROGRAM_ID,\n            auth: CLMM_LOCK_AUTH_ID,\n            lockPositionId,\n            clmmProgram: CLMM_PROGRAM_ID,\n            lockOwner: this.scope.ownerPubKey,\n            lockNftMint: lockData.lockNftMint,\n            lockNftAccount,\n            positionNftAccount: lockData.nftAccount,\n            positionId: lockData.positionId,\n            poolId: lockData.poolId,\n            protocolPosition,\n            vaultA: new PublicKey(poolKeys.vault.A),\n            vaultB: new PublicKey(poolKeys.vault.B),\n            tickArrayLower,\n            tickArrayUpper,\n            userVaultA: ownerTokenAccountA!,\n            userVaultB: ownerTokenAccountB!,\n            mintA: new PublicKey(poolKeys.mintA.address),\n            mintB: new PublicKey(poolKeys.mintB.address),\n            rewardAccounts: rewardAccountsFullInfo,\n            exTickArrayBitmap: getPdaExBitmapAccount(CLMM_PROGRAM_ID, lockData.poolId).publicKey,\n          });\n          txBuilder.addInstruction({\n            instructions: [harvestLockIns],\n            instructionTypes: [InstructionType.ClmmHarvestLockPosition],\n            lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n          });\n        } else {\n          const insData = ClmmInstrument.decreaseLiquidityInstructions({\n            poolInfo,\n            poolKeys,\n            ownerPosition: itemPosition,\n            ownerInfo: {\n              wallet: this.scope.ownerPubKey,\n              tokenAccountA: ownerTokenAccountA,\n              tokenAccountB: ownerTokenAccountB,\n              rewardAccounts,\n            },\n            liquidity: new BN(0),\n            amountMinA: new BN(0),\n            amountMinB: new BN(0),\n            nft2022: record[itemPosition.nftMint.toBase58()]?.equals(TOKEN_2022_PROGRAM_ID),\n          });\n          txBuilder.addInstruction(insData);\n        }\n      }\n    }\n\n    if (txVersion === TxVersion.V0)\n      return txBuilder.sizeCheckBuildV0({ computeBudgetConfig }) as Promise<MakeMultiTxData<T>>;\n    return txBuilder.sizeCheckBuild({ computeBudgetConfig }) as Promise<MakeMultiTxData<T>>;\n  }\n\n  public async getWhiteListMint({ programId }: { programId: PublicKey }): Promise<PublicKey[]> {\n    const accountInfo = await this.scope.connection.getAccountInfo(getPdaOperationAccount(programId).publicKey);\n    if (!accountInfo) return [];\n    const whitelistMintsInfo = OperationLayout.decode(accountInfo.data);\n    return whitelistMintsInfo.whitelistMints.filter((i) => !i.equals(PublicKey.default));\n  }\n\n  public async getOwnerPositionInfo({\n    programId,\n  }: {\n    programId: string | PublicKey;\n  }): Promise<ReturnType<typeof PositionInfoLayout.decode>[]> {\n    await this.scope.account.fetchWalletTokenAccounts();\n    const balanceMints = this.scope.account.tokenAccountRawInfos.filter((acc) => acc.accountInfo.amount.eq(new BN(1)));\n    const allPositionKey = balanceMints.map(\n      (acc) => getPdaPersonalPositionAddress(new PublicKey(programId), acc.accountInfo.mint).publicKey,\n    );\n\n    const accountInfo = await this.scope.connection.getMultipleAccountsInfo(allPositionKey);\n    const allPosition: ReturnType<typeof PositionInfoLayout.decode>[] = [];\n    accountInfo.forEach((positionRes) => {\n      if (!positionRes) return;\n      const position = PositionInfoLayout.decode(positionRes.data);\n      allPosition.push(position);\n    });\n\n    return allPosition;\n  }\n\n  public async getRpcClmmPoolInfo({ poolId }: { poolId: string | PublicKey }): Promise<ClmmRpcData> {\n    return (await this.getRpcClmmPoolInfos({ poolIds: [poolId] }))[String(poolId)];\n  }\n\n  public async getRpcClmmPoolInfos({\n    poolIds,\n    config,\n  }: {\n    poolIds: (string | PublicKey)[];\n    config?: { batchRequest?: boolean; chunkCount?: number };\n  }): Promise<{\n    [poolId: string]: ClmmRpcData;\n  }> {\n    const accounts = await getMultipleAccountsInfoWithCustomFlags(\n      this.scope.connection,\n      poolIds.map((i) => ({ pubkey: new PublicKey(i) })),\n      config,\n    );\n    const returnData: {\n      [poolId: string]: ClmmRpcData;\n    } = {};\n    for (let i = 0; i < poolIds.length; i++) {\n      const item = accounts[i];\n      if (item === null || !item.accountInfo) throw Error(\"fetch pool info error: \" + String(poolIds[i]));\n      const rpc = PoolInfoLayout.decode(item.accountInfo.data);\n      const currentPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n        rpc.sqrtPriceX64,\n        rpc.mintDecimalsA,\n        rpc.mintDecimalsB,\n      ).toNumber();\n\n      returnData[String(poolIds[i])] = {\n        ...rpc,\n        currentPrice,\n        programId: item.accountInfo.owner,\n      };\n    }\n    return returnData;\n  }\n\n  public async getComputeClmmPoolInfos({\n    clmmPoolsRpcInfo,\n    mintInfos,\n  }: {\n    clmmPoolsRpcInfo: Record<\n      string,\n      ReturnType<typeof PoolInfoLayout.decode> & { currentPrice: number; programId: PublicKey }\n    >;\n    mintInfos: ReturnTypeFetchMultipleMintInfos;\n  }): Promise<{\n    computeClmmPoolInfo: Record<string, ComputeClmmPoolInfo>;\n    computePoolTickData: ReturnTypeFetchMultiplePoolTickArrays;\n  }> {\n    const configSet = new Set(Object.keys(clmmPoolsRpcInfo).map((p) => clmmPoolsRpcInfo[p].ammConfig.toBase58()));\n    const res = await getMultipleAccountsInfoWithCustomFlags(\n      this.scope.connection,\n      Array.from(configSet).map((s) => ({ pubkey: new PublicKey(s) })),\n    );\n    const clmmConfigs: Record<string, ReturnType<typeof ClmmConfigLayout.decode>> = {};\n    res.forEach((acc) => {\n      if (!acc.accountInfo) return;\n      clmmConfigs[acc.pubkey.toBase58()] = ClmmConfigLayout.decode(acc.accountInfo.data);\n    });\n    const computeClmmPoolInfo = await PoolUtils.fetchComputeMultipleClmmInfo({\n      connection: this.scope.connection,\n      rpcDataMap: clmmPoolsRpcInfo,\n      poolList: Object.keys(clmmPoolsRpcInfo).map((poolId) => {\n        const [mintA, mintB] = [clmmPoolsRpcInfo[poolId].mintA.toBase58(), clmmPoolsRpcInfo[poolId].mintB.toBase58()];\n        return {\n          id: poolId,\n          programId: clmmPoolsRpcInfo[poolId].programId.toBase58(),\n          mintA: toApiV3Token({\n            address: mintA,\n            decimals: clmmPoolsRpcInfo[poolId].mintDecimalsA,\n            programId: mintInfos[mintA].programId.toBase58() || TOKEN_PROGRAM_ID.toBase58(),\n            extensions: {\n              feeConfig: mintInfos[mintA]?.feeConfig ? toFeeConfig(mintInfos[mintA]?.feeConfig) : undefined,\n            },\n          }),\n          mintB: toApiV3Token({\n            address: mintB,\n            decimals: clmmPoolsRpcInfo[poolId].mintDecimalsB,\n            programId: mintInfos[mintB].programId.toBase58() || TOKEN_PROGRAM_ID.toBase58(),\n            extensions: {\n              feeConfig: mintInfos[mintB]?.feeConfig ? toFeeConfig(mintInfos[mintB]?.feeConfig) : undefined,\n            },\n          }),\n          price: clmmPoolsRpcInfo[poolId].currentPrice,\n          config: {\n            ...clmmConfigs[clmmPoolsRpcInfo[poolId].ammConfig.toBase58()],\n            id: clmmPoolsRpcInfo[poolId].ammConfig.toBase58(),\n\n            fundFeeRate: 0,\n            description: \"\",\n            defaultRange: 0,\n            defaultRangePoint: [],\n          },\n        };\n      }),\n    });\n\n    const computePoolTickData = await PoolUtils.fetchMultiplePoolTickArrays({\n      connection: this.scope.connection,\n      poolKeys: Object.values(computeClmmPoolInfo),\n    });\n\n    return {\n      computeClmmPoolInfo,\n      computePoolTickData,\n    };\n  }\n\n  public async getPoolInfoFromRpc(poolId: string): Promise<{\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    computePoolInfo: ComputeClmmPoolInfo;\n    tickData: ReturnTypeFetchMultiplePoolTickArrays;\n  }> {\n    const rpcData = await this.getRpcClmmPoolInfo({ poolId });\n\n    const mintSet = new Set([rpcData.mintA.toBase58(), rpcData.mintB.toBase58()]);\n\n    const mintInfos = await fetchMultipleMintInfos({\n      connection: this.scope.connection,\n      mints: Array.from(mintSet).map((m) => new PublicKey(m)),\n    });\n\n    const { computeClmmPoolInfo, computePoolTickData } = await this.scope.clmm.getComputeClmmPoolInfos({\n      clmmPoolsRpcInfo: { [poolId]: rpcData },\n      mintInfos,\n    });\n    const vaultData = await getMultipleAccountsInfoWithCustomFlags(this.scope.connection, [\n      { pubkey: rpcData.vaultA },\n      { pubkey: rpcData.vaultB },\n    ]);\n\n    const poolInfo = clmmComputeInfoToApiInfo(computeClmmPoolInfo[poolId]);\n\n    if (!vaultData[0].accountInfo || !vaultData[1].accountInfo) throw new Error(\"pool vault data not found\");\n    poolInfo.mintAmountA = Number(AccountLayout.decode(vaultData[0].accountInfo.data).amount.toString());\n    poolInfo.mintAmountB = Number(AccountLayout.decode(vaultData[1].accountInfo?.data).amount.toString());\n\n    const poolKeys: ClmmKeys = {\n      ...computeClmmPoolInfo[poolId],\n      exBitmapAccount: computeClmmPoolInfo[poolId].exBitmapAccount.toBase58(),\n      observationId: computeClmmPoolInfo[poolId].observationId.toBase58(),\n      id: poolId,\n      programId: rpcData.programId.toBase58(),\n      openTime: rpcData.startTime.toString(),\n      vault: {\n        A: rpcData.vaultA.toBase58(),\n        B: rpcData.vaultB.toBase58(),\n      },\n      config: poolInfo.config,\n      rewardInfos: computeClmmPoolInfo[poolId].rewardInfos\n        .filter((r) => !r.tokenVault.equals(PublicKey.default))\n        .map((r) => ({\n          mint: toApiV3Token({ address: r.tokenMint.toBase58(), programId: TOKEN_PROGRAM_ID.toBase58(), decimals: 10 }),\n          vault: r.tokenVault.toBase58(),\n        })),\n    };\n    return { poolInfo, poolKeys, computePoolInfo: computeClmmPoolInfo[poolId], tickData: computePoolTickData };\n  }\n}\n","import { Connection, Keypair, PublicKey, Signer, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { ReturnTypeMakeInstructions } from \"@/raydium/type\";\nimport { ApiV3PoolInfoConcentratedItem, ApiV3Token, ClmmKeys } from \"@/api/type\";\nimport {\n  InstructionType,\n  MEMO_PROGRAM_ID,\n  MEMO_PROGRAM_ID2,\n  METADATA_PROGRAM_ID,\n  RENT_PROGRAM_ID,\n  createLogger,\n  getATAAddress,\n  parseBigNumberish,\n} from \"@/common\";\nimport { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { bool, s32, struct, u128, u64, u8 } from \"@/marshmallow\";\nimport { ClmmPositionLayout, ObservationInfoLayout } from \"./layout\";\nimport {\n  ClmmPoolPersonalPosition,\n  ClosePositionExtInfo,\n  InitRewardExtInfo,\n  ManipulateLiquidityExtInfo,\n  OpenPositionFromBaseExtInfo,\n  OpenPositionFromLiquidityExtInfo,\n  ClmmLockAddress,\n} from \"./type\";\nimport {\n  getPdaExBitmapAccount,\n  getPdaLockPositionId,\n  getPdaMetadataKey,\n  getPdaObservationAccount,\n  getPdaOperationAccount,\n  getPdaPersonalPositionAddress,\n  getPdaPoolId,\n  getPdaPoolRewardVaulId,\n  getPdaPoolVaultId,\n  getPdaProtocolPositionAddress,\n  getPdaTickArrayAddress,\n  getPdaLockClPositionIdV2,\n  getPdaMintExAccount,\n} from \"./utils/pda\";\nimport { PoolUtils } from \"./utils/pool\";\nimport { TickUtils } from \"./utils/tick\";\nimport { ZERO } from \"./utils/constants\";\nObservationInfoLayout.span; // do not delete this line\n\nconst logger = createLogger(\"Raydium_Clmm\");\n\nconst anchorDataBuf = {\n  createPool: [233, 146, 209, 142, 207, 104, 64, 188],\n  initReward: [95, 135, 192, 196, 242, 129, 230, 68],\n  setRewardEmissions: [112, 52, 167, 75, 32, 201, 211, 137],\n  openPosition: [77, 184, 74, 214, 112, 86, 241, 199],\n  openPositionWithTokenEx: [77, 255, 174, 82, 125, 29, 201, 46],\n  closePosition: [123, 134, 81, 0, 49, 68, 98, 98],\n  increaseLiquidity: [133, 29, 89, 223, 69, 238, 176, 10],\n  decreaseLiquidity: [58, 127, 188, 62, 79, 82, 196, 96],\n  swap: [43, 4, 237, 11, 26, 201, 30, 98], // [248, 198, 158, 145, 225, 117, 135, 200],\n  collectReward: [18, 237, 166, 197, 34, 16, 213, 144],\n};\n\nconst lockInsDataBuf = [188, 37, 179, 131, 82, 150, 84, 73];\nconst lockHarvestInsDataBuf = [16, 72, 250, 198, 14, 162, 212, 19];\n\ninterface CreatePoolInstruction {\n  connection: Connection;\n  programId: PublicKey;\n  owner: PublicKey;\n  mintA: ApiV3Token;\n  mintB: ApiV3Token;\n  ammConfigId: PublicKey;\n  initialPriceX64: BN;\n  forerunCreate?: boolean;\n  extendMintAccount?: PublicKey[];\n}\n\nexport class ClmmInstrument {\n  static createPoolInstruction(\n    programId: PublicKey,\n    poolId: PublicKey,\n    poolCreator: PublicKey,\n    ammConfigId: PublicKey,\n    observationId: PublicKey,\n    mintA: PublicKey,\n    mintVaultA: PublicKey,\n    mintProgramIdA: PublicKey,\n    mintB: PublicKey,\n    mintVaultB: PublicKey,\n    mintProgramIdB: PublicKey,\n    exTickArrayBitmap: PublicKey,\n    sqrtPriceX64: BN,\n    extendMintAccount?: PublicKey[],\n  ): TransactionInstruction {\n    const dataLayout = struct([u128(\"sqrtPriceX64\"), u64(\"zero\")]);\n\n    const keys = [\n      { pubkey: poolCreator, isSigner: true, isWritable: true },\n      { pubkey: ammConfigId, isSigner: false, isWritable: false },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: mintA, isSigner: false, isWritable: false },\n      { pubkey: mintB, isSigner: false, isWritable: false },\n      { pubkey: mintVaultA, isSigner: false, isWritable: true },\n      { pubkey: mintVaultB, isSigner: false, isWritable: true },\n      { pubkey: observationId, isSigner: false, isWritable: true },\n      { pubkey: exTickArrayBitmap, isSigner: false, isWritable: true },\n      { pubkey: mintProgramIdA, isSigner: false, isWritable: false },\n      { pubkey: mintProgramIdB, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      ...(extendMintAccount?.map((k) => ({ pubkey: k, isSigner: false, isWritable: false })) || []),\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        sqrtPriceX64,\n        zero: ZERO,\n      },\n      data,\n    );\n    const aData = Buffer.from([...anchorDataBuf.createPool, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static async createPoolInstructions(props: CreatePoolInstruction): Promise<\n    ReturnTypeMakeInstructions<{\n      poolId: PublicKey;\n      observationId: PublicKey;\n      exBitmapAccount: PublicKey;\n      mintAVault: PublicKey;\n      mintBVault: PublicKey;\n    }>\n  > {\n    const { programId, owner, mintA, mintB, ammConfigId, initialPriceX64, extendMintAccount } = props;\n    const [mintAAddress, mintBAddress] = [new PublicKey(mintA.address), new PublicKey(mintB.address)];\n\n    const { publicKey: poolId } = getPdaPoolId(programId, ammConfigId, mintAAddress, mintBAddress);\n    const { publicKey: observationId } = getPdaObservationAccount(programId, poolId);\n    const { publicKey: mintAVault } = getPdaPoolVaultId(programId, poolId, mintAAddress);\n    const { publicKey: mintBVault } = getPdaPoolVaultId(programId, poolId, mintBAddress);\n    const exBitmapAccount = getPdaExBitmapAccount(programId, poolId).publicKey;\n\n    const ins = [\n      this.createPoolInstruction(\n        programId,\n        poolId,\n        owner,\n        ammConfigId,\n        observationId,\n        mintAAddress,\n        mintAVault,\n        new PublicKey(mintA.programId || TOKEN_PROGRAM_ID),\n        mintBAddress,\n        mintBVault,\n        new PublicKey(mintB.programId || TOKEN_PROGRAM_ID),\n        exBitmapAccount,\n        initialPriceX64,\n        extendMintAccount,\n      ),\n    ];\n\n    return {\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.CreateAccount, InstructionType.ClmmCreatePool],\n      address: { poolId, observationId, exBitmapAccount, mintAVault, mintBVault },\n      lookupTableAddress: [],\n    };\n  }\n\n  static openPositionFromLiquidityInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftMint: PublicKey,\n    positionNftAccount: PublicKey,\n    metadataAccount: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    personalPosition: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    tokenVaultA: PublicKey,\n    tokenVaultB: PublicKey,\n    tokenMintA: PublicKey,\n    tokenMintB: PublicKey,\n\n    tickLowerIndex: number,\n    tickUpperIndex: number,\n    tickArrayLowerStartIndex: number,\n    tickArrayUpperStartIndex: number,\n    liquidity: BN,\n    amountMaxA: BN,\n    amountMaxB: BN,\n    withMetadata: \"create\" | \"no-create\",\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      s32(\"tickLowerIndex\"),\n      s32(\"tickUpperIndex\"),\n      s32(\"tickArrayLowerStartIndex\"),\n      s32(\"tickArrayUpperStartIndex\"),\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      bool(\"withMetadata\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: positionNftOwner, isSigner: false, isWritable: false },\n      { pubkey: positionNftMint, isSigner: true, isWritable: true },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: metadataAccount, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultA, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: METADATA_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: tokenMintA, isSigner: false, isWritable: false },\n      { pubkey: tokenMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        tickLowerIndex,\n        tickUpperIndex,\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n        liquidity,\n        amountMaxA,\n        amountMaxB,\n        withMetadata: withMetadata === \"create\",\n        baseFlag: false,\n        optionBaseFlag: 0,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.openPosition, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static openPositionFromLiquidityInstruction22(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftMint: PublicKey,\n    positionNftAccount: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    personalPosition: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    tokenVaultA: PublicKey,\n    tokenVaultB: PublicKey,\n    tokenMintA: PublicKey,\n    tokenMintB: PublicKey,\n\n    tickLowerIndex: number,\n    tickUpperIndex: number,\n    tickArrayLowerStartIndex: number,\n    tickArrayUpperStartIndex: number,\n    liquidity: BN,\n    amountMaxA: BN,\n    amountMaxB: BN,\n    withMetadata: \"create\" | \"no-create\",\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      s32(\"tickLowerIndex\"),\n      s32(\"tickUpperIndex\"),\n      s32(\"tickArrayLowerStartIndex\"),\n      s32(\"tickArrayUpperStartIndex\"),\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      bool(\"withMetadata\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: positionNftOwner, isSigner: false, isWritable: false },\n      { pubkey: positionNftMint, isSigner: true, isWritable: true },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultA, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: tokenMintA, isSigner: false, isWritable: false },\n      { pubkey: tokenMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        tickLowerIndex,\n        tickUpperIndex,\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n        liquidity,\n        amountMaxA,\n        amountMaxB,\n        withMetadata: withMetadata === \"create\",\n        baseFlag: false,\n        optionBaseFlag: 0,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.openPositionWithTokenEx, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static async openPositionInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    amountMaxA,\n    amountMaxB,\n    withMetadata,\n    getEphemeralSigners,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      feePayer: PublicKey;\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    tickLower: number;\n    tickUpper: number;\n    liquidity: BN;\n    amountMaxA: BN;\n    amountMaxB: BN;\n    withMetadata: \"create\" | \"no-create\";\n    getEphemeralSigners?: (k: number) => any;\n    nft2022?: boolean;\n  }): Promise<ReturnTypeMakeInstructions> {\n    const signers: Signer[] = [];\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n\n    let nftMintAccount;\n    if (getEphemeralSigners) {\n      nftMintAccount = new PublicKey((await getEphemeralSigners(1))[0]);\n    } else {\n      const _k = Keypair.generate();\n      signers.push(_k);\n      nftMintAccount = _k.publicKey;\n    }\n\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(tickLower, poolInfo.config.tickSpacing);\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(tickUpper, poolInfo.config.tickSpacing);\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(programId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(programId, id, tickArrayUpperStartIndex);\n\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_PROGRAM_ID);\n    const { publicKey: metadataAccount } = getPdaMetadataKey(nftMintAccount);\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, nftMintAccount);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(programId, id, tickLower, tickUpper);\n\n    const ins = nft2022\n      ? this.openPositionFromLiquidityInstruction22(\n          programId,\n          ownerInfo.feePayer,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolInfo.mintA.address),\n          new PublicKey(poolInfo.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n          liquidity,\n          amountMaxA,\n          amountMaxB,\n          withMetadata,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        )\n      : this.openPositionFromLiquidityInstruction(\n          programId,\n          ownerInfo.feePayer,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          metadataAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolInfo.mintA.address),\n          new PublicKey(poolInfo.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n          liquidity,\n          amountMaxA,\n          amountMaxB,\n          withMetadata,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        );\n\n    return {\n      signers,\n      instructions: [ins],\n      instructionTypes: [InstructionType.ClmmOpenPosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n      address: {\n        nftMint: nftMintAccount,\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        metadataAccount,\n        personalPosition,\n        protocolPosition,\n      },\n    };\n  }\n\n  static async openPositionFromBaseInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    base,\n    baseAmount,\n    otherAmountMax,\n    withMetadata,\n    getEphemeralSigners,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      feePayer: PublicKey;\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    tickLower: number;\n    tickUpper: number;\n\n    base: \"MintA\" | \"MintB\";\n    baseAmount: BN;\n\n    otherAmountMax: BN;\n    withMetadata: \"create\" | \"no-create\";\n    getEphemeralSigners?: (k: number) => any;\n    nft2022?: boolean;\n  }): Promise<ReturnTypeMakeInstructions<OpenPositionFromBaseExtInfo>> {\n    const signers: Signer[] = [];\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n\n    let nftMintAccount: PublicKey;\n    if (getEphemeralSigners) {\n      nftMintAccount = new PublicKey((await getEphemeralSigners(1))[0]);\n    } else {\n      const _k = Keypair.generate();\n      signers.push(_k);\n      nftMintAccount = _k.publicKey;\n    }\n\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(tickLower, poolInfo.config.tickSpacing);\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(tickUpper, poolInfo.config.tickSpacing);\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(programId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(programId, id, tickArrayUpperStartIndex);\n\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_PROGRAM_ID);\n    const { publicKey: metadataAccount } = getPdaMetadataKey(nftMintAccount);\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, nftMintAccount);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(programId, id, tickLower, tickUpper);\n\n    const ins = nft2022\n      ? this.openPositionFromBaseInstruction22(\n          programId,\n          ownerInfo.feePayer,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolInfo.mintA.address),\n          new PublicKey(poolInfo.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n\n          withMetadata,\n\n          base,\n          baseAmount,\n\n          otherAmountMax,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        )\n      : this.openPositionFromBaseInstruction(\n          programId,\n          ownerInfo.feePayer,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          metadataAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolInfo.mintA.address),\n          new PublicKey(poolInfo.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n\n          withMetadata,\n\n          base,\n          baseAmount,\n\n          otherAmountMax,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        );\n\n    return {\n      address: {\n        nftMint: nftMintAccount,\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        metadataAccount,\n        personalPosition,\n        protocolPosition,\n      },\n      instructions: [ins],\n      signers,\n      instructionTypes: [InstructionType.ClmmOpenPosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static openPositionFromBaseInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftMint: PublicKey,\n    positionNftAccount: PublicKey,\n    metadataAccount: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    personalPosition: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    tokenVaultA: PublicKey,\n    tokenVaultB: PublicKey,\n    tokenMintA: PublicKey,\n    tokenMintB: PublicKey,\n\n    tickLowerIndex: number,\n    tickUpperIndex: number,\n    tickArrayLowerStartIndex: number,\n    tickArrayUpperStartIndex: number,\n\n    withMetadata: \"create\" | \"no-create\",\n    base: \"MintA\" | \"MintB\",\n    baseAmount: BN,\n\n    otherAmountMax: BN,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      s32(\"tickLowerIndex\"),\n      s32(\"tickUpperIndex\"),\n      s32(\"tickArrayLowerStartIndex\"),\n      s32(\"tickArrayUpperStartIndex\"),\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      bool(\"withMetadata\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: positionNftOwner, isSigner: false, isWritable: false },\n      { pubkey: positionNftMint, isSigner: true, isWritable: true },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: metadataAccount, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultA, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: METADATA_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: tokenMintA, isSigner: false, isWritable: false },\n      { pubkey: tokenMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        tickLowerIndex,\n        tickUpperIndex,\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n        liquidity: new BN(0),\n        amountMaxA: base === \"MintA\" ? baseAmount : otherAmountMax,\n        amountMaxB: base === \"MintA\" ? otherAmountMax : baseAmount,\n        withMetadata: withMetadata === \"create\",\n        baseFlag: base === \"MintA\",\n        optionBaseFlag: 1,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.openPosition, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static openPositionFromBaseInstruction22(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftMint: PublicKey,\n    positionNftAccount: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    personalPosition: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    tokenVaultA: PublicKey,\n    tokenVaultB: PublicKey,\n    tokenMintA: PublicKey,\n    tokenMintB: PublicKey,\n\n    tickLowerIndex: number,\n    tickUpperIndex: number,\n    tickArrayLowerStartIndex: number,\n    tickArrayUpperStartIndex: number,\n\n    withMetadata: \"create\" | \"no-create\",\n    base: \"MintA\" | \"MintB\",\n    baseAmount: BN,\n\n    otherAmountMax: BN,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      s32(\"tickLowerIndex\"),\n      s32(\"tickUpperIndex\"),\n      s32(\"tickArrayLowerStartIndex\"),\n      s32(\"tickArrayUpperStartIndex\"),\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      bool(\"withMetadata\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: positionNftOwner, isSigner: false, isWritable: false },\n      { pubkey: positionNftMint, isSigner: true, isWritable: true },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultA, isSigner: false, isWritable: true },\n      { pubkey: tokenVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: tokenMintA, isSigner: false, isWritable: false },\n      { pubkey: tokenMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        tickLowerIndex,\n        tickUpperIndex,\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n        liquidity: new BN(0),\n        amountMaxA: base === \"MintA\" ? baseAmount : otherAmountMax,\n        amountMaxB: base === \"MintA\" ? otherAmountMax : baseAmount,\n        withMetadata: withMetadata === \"create\",\n        baseFlag: base === \"MintA\",\n        optionBaseFlag: 1,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.openPositionWithTokenEx, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static async openPositionFromLiquidityInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    amountMaxA,\n    amountMaxB,\n    withMetadata,\n    getEphemeralSigners,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    tickLower: number;\n    tickUpper: number;\n    liquidity: BN;\n    amountMaxA: BN;\n    amountMaxB: BN;\n    withMetadata: \"create\" | \"no-create\";\n    getEphemeralSigners?: (k: number) => any;\n    nft2022?: boolean;\n  }): Promise<ReturnTypeMakeInstructions<OpenPositionFromLiquidityExtInfo[\"address\"]>> {\n    let nftMintAccount: PublicKey;\n    const signers: Keypair[] = [];\n    if (getEphemeralSigners) {\n      nftMintAccount = new PublicKey((await getEphemeralSigners(1))[0]);\n    } else {\n      const _k = Keypair.generate();\n      signers.push(_k);\n      nftMintAccount = _k.publicKey;\n    }\n\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(tickLower, poolInfo.config.tickSpacing);\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(tickUpper, poolInfo.config.tickSpacing);\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(programId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(programId, id, tickArrayUpperStartIndex);\n\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, nftMintAccount, TOKEN_PROGRAM_ID);\n    const { publicKey: metadataAccount } = getPdaMetadataKey(nftMintAccount);\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, nftMintAccount);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(programId, id, tickLower, tickUpper);\n\n    const ins = nft2022\n      ? this.openPositionFromLiquidityInstruction22(\n          programId,\n          ownerInfo.wallet,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolKeys.mintA.address),\n          new PublicKey(poolKeys.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n          liquidity,\n          amountMaxA,\n          amountMaxB,\n          withMetadata,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        )\n      : this.openPositionFromLiquidityInstruction(\n          programId,\n          ownerInfo.wallet,\n          id,\n          ownerInfo.wallet,\n          nftMintAccount,\n          positionNftAccount,\n          metadataAccount,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          personalPosition,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolKeys.mintA.address),\n          new PublicKey(poolKeys.mintB.address),\n\n          tickLower,\n          tickUpper,\n          tickArrayLowerStartIndex,\n          tickArrayUpperStartIndex,\n          liquidity,\n          amountMaxA,\n          amountMaxB,\n          withMetadata,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        );\n\n    return {\n      address: {\n        nftMint: nftMintAccount,\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        metadataAccount,\n        personalPosition,\n        protocolPosition,\n      },\n      instructions: [ins],\n      signers,\n      instructionTypes: [InstructionType.ClmmOpenPosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static closePositionInstruction(\n    programId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftMint: PublicKey,\n    positionNftAccount: PublicKey,\n    personalPosition: PublicKey,\n    nft2022?: boolean,\n  ): TransactionInstruction {\n    const dataLayout = struct([]);\n\n    const keys = [\n      { pubkey: positionNftOwner, isSigner: true, isWritable: true },\n      { pubkey: positionNftMint, isSigner: false, isWritable: true },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: nft2022 ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode({}, data);\n\n    const aData = Buffer.from([...anchorDataBuf.closePosition, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static closePositionInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    ownerPosition,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n    ownerInfo: {\n      wallet: PublicKey;\n    };\n    nft2022?: boolean;\n  }): ReturnTypeMakeInstructions<ClosePositionExtInfo[\"address\"]> {\n    const programId = new PublicKey(poolInfo.programId);\n    // const { publicKey: positionNftAccount } = getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_PROGRAM_ID);\n    const positionNftAccount = nft2022\n      ? getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_2022_PROGRAM_ID).publicKey\n      : getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_PROGRAM_ID).publicKey;\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, ownerPosition.nftMint);\n\n    const ins: TransactionInstruction[] = [];\n    ins.push(\n      this.closePositionInstruction(\n        programId,\n        ownerInfo.wallet,\n        ownerPosition.nftMint,\n        positionNftAccount,\n        personalPosition,\n        nft2022,\n      ),\n    );\n\n    return {\n      address: {\n        positionNftAccount,\n        personalPosition,\n      },\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmClosePosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static increasePositionFromLiquidityInstruction(\n    programId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftAccount: PublicKey,\n    personalPosition: PublicKey,\n\n    poolId: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    mintVaultA: PublicKey,\n    mintVaultB: PublicKey,\n    mintMintA: PublicKey,\n    mintMintB: PublicKey,\n\n    liquidity: BN,\n    amountMaxA: BN,\n    amountMaxB: BN,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: positionNftOwner, isSigner: true, isWritable: false },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: false },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: mintVaultA, isSigner: false, isWritable: true },\n      { pubkey: mintVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: mintMintA, isSigner: false, isWritable: false },\n      { pubkey: mintMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        liquidity,\n        amountMaxA,\n        amountMaxB,\n        optionBaseFlag: 0,\n        baseFlag: false,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.increaseLiquidity, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static increasePositionFromLiquidityInstructions({\n    poolInfo,\n    poolKeys,\n    ownerPosition,\n    ownerInfo,\n    liquidity,\n    amountMaxA,\n    amountMaxB,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    liquidity: BN;\n    amountMaxA: BN;\n    amountMaxB: BN;\n    nft2022?: boolean;\n  }): ReturnTypeMakeInstructions<ManipulateLiquidityExtInfo[\"address\"]> {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickLower,\n      poolInfo.config.tickSpacing,\n    );\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickUpper,\n      poolInfo.config.tickSpacing,\n    );\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(programId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(programId, id, tickArrayUpperStartIndex);\n\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_PROGRAM_ID);\n\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, ownerPosition.nftMint);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n      programId,\n      id,\n      ownerPosition.tickLower,\n      ownerPosition.tickUpper,\n    );\n\n    const ins = this.increasePositionFromLiquidityInstruction(\n      programId,\n      ownerInfo.wallet,\n      positionNftAccount,\n      personalPosition,\n      id,\n      protocolPosition,\n      tickArrayLower,\n      tickArrayUpper,\n      ownerInfo.tokenAccountA,\n      ownerInfo.tokenAccountB,\n      new PublicKey(poolKeys.vault.A),\n      new PublicKey(poolKeys.vault.B),\n      new PublicKey(poolInfo.mintA.address),\n      new PublicKey(poolInfo.mintB.address),\n\n      liquidity,\n      amountMaxA,\n      amountMaxB,\n      PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n      ])\n        ? getPdaExBitmapAccount(programId, id).publicKey\n        : undefined,\n    );\n\n    return {\n      address: {\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        personalPosition,\n        protocolPosition,\n      },\n      signers: [],\n      instructions: [ins],\n      instructionTypes: [InstructionType.ClmmIncreasePosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static increasePositionFromBaseInstructions({\n    poolInfo,\n    poolKeys,\n    ownerPosition,\n    ownerInfo,\n    base,\n    baseAmount,\n    otherAmountMax,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPoolPersonalPosition;\n\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    base: \"MintA\" | \"MintB\";\n    baseAmount: BN;\n\n    otherAmountMax: BN;\n    nft2022?: boolean;\n  }): ReturnTypeMakeInstructions<ManipulateLiquidityExtInfo[\"address\"]> {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickLower,\n      poolInfo.config.tickSpacing,\n    );\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickUpper,\n      poolInfo.config.tickSpacing,\n    );\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(programId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(programId, id, tickArrayUpperStartIndex);\n\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_PROGRAM_ID);\n\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(programId, ownerPosition.nftMint);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n      programId,\n      id,\n      ownerPosition.tickLower,\n      ownerPosition.tickUpper,\n    );\n\n    return {\n      address: {\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        personalPosition,\n        protocolPosition,\n      },\n      instructions: [\n        this.increasePositionFromBaseInstruction(\n          programId,\n          ownerInfo.wallet,\n          positionNftAccount,\n          personalPosition,\n          id,\n          protocolPosition,\n          tickArrayLower,\n          tickArrayUpper,\n          ownerInfo.tokenAccountA,\n          ownerInfo.tokenAccountB,\n          new PublicKey(poolKeys.vault.A),\n          new PublicKey(poolKeys.vault.B),\n          new PublicKey(poolInfo.mintA.address),\n          new PublicKey(poolInfo.mintB.address),\n\n          base,\n          baseAmount,\n\n          otherAmountMax,\n          PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n            tickArrayLowerStartIndex,\n            tickArrayUpperStartIndex,\n          ])\n            ? getPdaExBitmapAccount(programId, id).publicKey\n            : undefined,\n        ),\n      ],\n      signers: [],\n      instructionTypes: [InstructionType.ClmmIncreasePosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static increasePositionFromBaseInstruction(\n    programId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftAccount: PublicKey,\n    personalPosition: PublicKey,\n\n    poolId: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    mintVaultA: PublicKey,\n    mintVaultB: PublicKey,\n    mintMintA: PublicKey,\n    mintMintB: PublicKey,\n\n    base: \"MintA\" | \"MintB\",\n    baseAmount: BN,\n\n    otherAmountMax: BN,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      u128(\"liquidity\"),\n      u64(\"amountMaxA\"),\n      u64(\"amountMaxB\"),\n      u8(\"optionBaseFlag\"),\n      bool(\"baseFlag\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n    ];\n\n    const keys = [\n      { pubkey: positionNftOwner, isSigner: true, isWritable: false },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: false },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n      { pubkey: mintVaultA, isSigner: false, isWritable: true },\n      { pubkey: mintVaultB, isSigner: false, isWritable: true },\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: mintMintA, isSigner: false, isWritable: false },\n      { pubkey: mintMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        liquidity: new BN(0),\n        amountMaxA: base === \"MintA\" ? baseAmount : otherAmountMax,\n        amountMaxB: base === \"MintA\" ? otherAmountMax : baseAmount,\n        baseFlag: base === \"MintA\",\n        optionBaseFlag: 1,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.increaseLiquidity, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static decreaseLiquidityInstruction(\n    programId: PublicKey,\n    positionNftOwner: PublicKey,\n    positionNftAccount: PublicKey,\n    personalPosition: PublicKey,\n\n    poolId: PublicKey,\n    protocolPosition: PublicKey,\n    tickArrayLower: PublicKey,\n    tickArrayUpper: PublicKey,\n    ownerTokenAccountA: PublicKey,\n    ownerTokenAccountB: PublicKey,\n    mintVaultA: PublicKey,\n    mintVaultB: PublicKey,\n    mintMintA: PublicKey,\n    mintMintB: PublicKey,\n    rewardAccounts: {\n      poolRewardVault: PublicKey;\n      ownerRewardVault: PublicKey;\n      rewardMint: PublicKey;\n    }[],\n\n    liquidity: BN,\n    amountMinA: BN,\n    amountMinB: BN,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([u128(\"liquidity\"), u64(\"amountMinA\"), u64(\"amountMinB\")]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n      ...rewardAccounts\n        .map((i) => [\n          { pubkey: i.poolRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.ownerRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.rewardMint, isSigner: false, isWritable: false },\n        ])\n        .flat(),\n    ];\n\n    const keys = [\n      { pubkey: positionNftOwner, isSigner: true, isWritable: false },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: false },\n      { pubkey: personalPosition, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: mintVaultA, isSigner: false, isWritable: true },\n      { pubkey: mintVaultB, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n\n      { pubkey: ownerTokenAccountA, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccountB, isSigner: false, isWritable: true },\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: mintMintA, isSigner: false, isWritable: false },\n      { pubkey: mintMintB, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        liquidity,\n        amountMinA,\n        amountMinB,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.decreaseLiquidity, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static decreaseLiquidityInstructions({\n    poolInfo,\n    poolKeys,\n    ownerPosition,\n    ownerInfo,\n    liquidity,\n    amountMinA,\n    amountMinB,\n    programId,\n    nft2022,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n      rewardAccounts: PublicKey[];\n    };\n\n    liquidity: BN;\n    amountMinA: BN;\n    amountMinB: BN;\n    programId?: PublicKey;\n    nft2022?: boolean;\n  }): ReturnTypeMakeInstructions<ManipulateLiquidityExtInfo[\"address\"]> {\n    const [poolProgramId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickLower,\n      poolInfo.config.tickSpacing,\n    );\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      ownerPosition.tickUpper,\n      poolInfo.config.tickSpacing,\n    );\n\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(poolProgramId, id, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(poolProgramId, id, tickArrayUpperStartIndex);\n    const { publicKey: positionNftAccount } = nft2022\n      ? getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, TOKEN_2022_PROGRAM_ID)\n      : getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, programId);\n    const { publicKey: personalPosition } = getPdaPersonalPositionAddress(poolProgramId, ownerPosition.nftMint);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n      poolProgramId,\n      id,\n      ownerPosition.tickLower,\n      ownerPosition.tickUpper,\n    );\n\n    const rewardAccounts: {\n      poolRewardVault: PublicKey;\n      ownerRewardVault: PublicKey;\n      rewardMint: PublicKey;\n    }[] = [];\n    for (let i = 0; i < poolInfo.rewardDefaultInfos.length; i++) {\n      rewardAccounts.push({\n        poolRewardVault: new PublicKey(poolKeys.rewardInfos[i].vault),\n        ownerRewardVault: ownerInfo.rewardAccounts[i],\n        rewardMint: new PublicKey(poolInfo.rewardDefaultInfos[i].mint.address),\n      });\n    }\n\n    const ins: TransactionInstruction[] = [];\n    const decreaseIns = this.decreaseLiquidityInstruction(\n      poolProgramId,\n      ownerInfo.wallet,\n      positionNftAccount,\n      personalPosition,\n      id,\n      protocolPosition,\n      tickArrayLower,\n      tickArrayUpper,\n      ownerInfo.tokenAccountA,\n      ownerInfo.tokenAccountB,\n      new PublicKey(poolKeys.vault.A),\n      new PublicKey(poolKeys.vault.B),\n      new PublicKey(poolInfo.mintA.address),\n      new PublicKey(poolInfo.mintB.address),\n      rewardAccounts,\n\n      liquidity,\n      amountMinA,\n      amountMinB,\n      PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.config.tickSpacing, [\n        tickArrayLowerStartIndex,\n        tickArrayUpperStartIndex,\n      ])\n        ? getPdaExBitmapAccount(poolProgramId, id).publicKey\n        : undefined,\n    );\n    ins.push(decreaseIns);\n\n    return {\n      address: {\n        tickArrayLower,\n        tickArrayUpper,\n        positionNftAccount,\n        personalPosition,\n        protocolPosition,\n      },\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmDecreasePosition],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static swapInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    ammConfigId: PublicKey,\n    inputTokenAccount: PublicKey,\n    outputTokenAccount: PublicKey,\n    inputVault: PublicKey,\n    outputVault: PublicKey,\n    inputMint: PublicKey,\n    outputMint: PublicKey,\n    tickArray: PublicKey[],\n    observationId: PublicKey,\n\n    amount: BN,\n    otherAmountThreshold: BN,\n    sqrtPriceLimitX64: BN,\n    isBaseInput: boolean,\n\n    exTickArrayBitmap?: PublicKey,\n  ): TransactionInstruction {\n    const dataLayout = struct([\n      u64(\"amount\"),\n      u64(\"otherAmountThreshold\"),\n      u128(\"sqrtPriceLimitX64\"),\n      bool(\"isBaseInput\"),\n    ]);\n\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n      ...tickArray.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n    ];\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: false },\n      { pubkey: ammConfigId, isSigner: false, isWritable: false },\n\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: inputTokenAccount, isSigner: false, isWritable: true },\n      { pubkey: outputTokenAccount, isSigner: false, isWritable: true },\n      { pubkey: inputVault, isSigner: false, isWritable: true },\n      { pubkey: outputVault, isSigner: false, isWritable: true },\n\n      { pubkey: observationId, isSigner: false, isWritable: true },\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: inputMint, isSigner: false, isWritable: false },\n      { pubkey: outputMint, isSigner: false, isWritable: false },\n\n      ...remainingAccounts,\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        amount,\n        otherAmountThreshold,\n        sqrtPriceLimitX64,\n        isBaseInput,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.swap, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static makeSwapBaseInInstructions({\n    poolInfo,\n    poolKeys,\n    observationId,\n    ownerInfo,\n    inputMint,\n    amountIn,\n    amountOutMin,\n    sqrtPriceLimitX64,\n    remainingAccounts,\n  }: {\n    poolInfo: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\">;\n    poolKeys: ClmmKeys;\n    observationId: PublicKey;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    inputMint: PublicKey;\n\n    amountIn: BN;\n    amountOutMin: BN;\n    sqrtPriceLimitX64: BN;\n\n    remainingAccounts: PublicKey[];\n  }): ReturnTypeMakeInstructions {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const [mintAVault, mintBVault] = [new PublicKey(poolKeys.vault.A), new PublicKey(poolKeys.vault.B)];\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n\n    const isInputMintA = poolInfo.mintA.address === inputMint.toString();\n\n    const ins = [\n      this.swapInstruction(\n        programId,\n        ownerInfo.wallet,\n\n        id,\n        new PublicKey(poolInfo.config.id),\n\n        isInputMintA ? ownerInfo.tokenAccountA : ownerInfo.tokenAccountB,\n        isInputMintA ? ownerInfo.tokenAccountB : ownerInfo.tokenAccountA,\n\n        isInputMintA ? mintAVault : mintBVault,\n        isInputMintA ? mintBVault : mintAVault,\n\n        isInputMintA ? mintA : mintB,\n        isInputMintA ? mintB : mintA,\n\n        remainingAccounts,\n        observationId,\n        amountIn,\n        amountOutMin,\n        sqrtPriceLimitX64,\n        true,\n        getPdaExBitmapAccount(programId, id).publicKey,\n      ),\n    ];\n    return {\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmSwapBaseIn],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n      address: {},\n    };\n  }\n\n  static makeSwapBaseOutInstructions({\n    poolInfo,\n    poolKeys,\n    observationId,\n    ownerInfo,\n    outputMint,\n    amountOut,\n    amountInMax,\n    sqrtPriceLimitX64,\n    remainingAccounts,\n  }: {\n    poolInfo: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\">;\n    poolKeys: ClmmKeys;\n    observationId: PublicKey;\n\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccountA: PublicKey;\n      tokenAccountB: PublicKey;\n    };\n\n    outputMint: PublicKey;\n\n    amountOut: BN;\n    amountInMax: BN;\n    sqrtPriceLimitX64: BN;\n\n    remainingAccounts: PublicKey[];\n  }): ReturnTypeMakeInstructions {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const [mintAVault, mintBVault] = [new PublicKey(poolKeys.vault.A), new PublicKey(poolKeys.vault.B)];\n    const [mintA, mintB] = [new PublicKey(poolInfo.mintA.address), new PublicKey(poolInfo.mintB.address)];\n    const isInputMintA = poolInfo.mintA.address === outputMint.toBase58();\n    const ins = [\n      this.swapInstruction(\n        programId,\n        ownerInfo.wallet,\n\n        id,\n        new PublicKey(poolInfo.config.id),\n\n        isInputMintA ? ownerInfo.tokenAccountB : ownerInfo.tokenAccountA,\n        isInputMintA ? ownerInfo.tokenAccountA : ownerInfo.tokenAccountB,\n\n        isInputMintA ? mintBVault : mintAVault,\n        isInputMintA ? mintAVault : mintBVault,\n\n        isInputMintA ? mintB : mintA,\n        isInputMintA ? mintA : mintB,\n\n        remainingAccounts,\n        observationId,\n        amountOut,\n        amountInMax,\n        sqrtPriceLimitX64,\n        false,\n        getPdaExBitmapAccount(programId, id).publicKey,\n      ),\n    ];\n    return {\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmSwapBaseOut],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n      address: {},\n    };\n  }\n\n  static initRewardInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    operationId: PublicKey,\n    ammConfigId: PublicKey,\n\n    ownerTokenAccount: PublicKey,\n    rewardProgramId: PublicKey,\n    rewardMint: PublicKey,\n    rewardVault: PublicKey,\n\n    openTime: number,\n    endTime: number,\n    emissionsPerSecondX64: BN,\n  ): TransactionInstruction {\n    const dataLayout = struct([u64(\"openTime\"), u64(\"endTime\"), u128(\"emissionsPerSecondX64\")]);\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: ownerTokenAccount, isSigner: false, isWritable: true },\n      { pubkey: ammConfigId, isSigner: false, isWritable: false },\n\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: operationId, isSigner: false, isWritable: true },\n      { pubkey: rewardMint, isSigner: false, isWritable: false },\n      { pubkey: rewardVault, isSigner: false, isWritable: true },\n\n      { pubkey: rewardProgramId, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        openTime: parseBigNumberish(openTime),\n        endTime: parseBigNumberish(endTime),\n        emissionsPerSecondX64,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.initReward, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static initRewardInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    rewardInfo,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccount: PublicKey;\n    };\n    rewardInfo: {\n      programId: PublicKey;\n      mint: PublicKey;\n      openTime: number;\n      endTime: number;\n      emissionsPerSecondX64: BN;\n    };\n  }): ReturnTypeMakeInstructions<InitRewardExtInfo[\"address\"]> {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    const poolRewardVault = getPdaPoolRewardVaulId(programId, id, rewardInfo.mint).publicKey;\n    const operationId = getPdaOperationAccount(programId).publicKey;\n    const ins = [\n      this.initRewardInstruction(\n        programId,\n        ownerInfo.wallet,\n        id,\n        operationId,\n        new PublicKey(poolInfo.config.id),\n\n        ownerInfo.tokenAccount,\n        rewardInfo.programId,\n        rewardInfo.mint,\n        poolRewardVault,\n\n        rewardInfo.openTime,\n        rewardInfo.endTime,\n        rewardInfo.emissionsPerSecondX64,\n      ),\n    ];\n    return {\n      address: { poolRewardVault, operationId },\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmInitReward],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static setRewardInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n    operationId: PublicKey,\n    ammConfigId: PublicKey,\n\n    ownerTokenAccount: PublicKey,\n    rewardVault: PublicKey,\n    rewardMint: PublicKey,\n\n    rewardIndex: number,\n    openTime: number,\n    endTime: number,\n    emissionsPerSecondX64: BN,\n  ): TransactionInstruction {\n    const dataLayout = struct([u8(\"rewardIndex\"), u128(\"emissionsPerSecondX64\"), u64(\"openTime\"), u64(\"endTime\")]);\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: ammConfigId, isSigner: false, isWritable: false },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: operationId, isSigner: false, isWritable: true },\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n\n      { pubkey: rewardVault, isSigner: false, isWritable: true },\n      { pubkey: ownerTokenAccount, isSigner: false, isWritable: true },\n      { pubkey: rewardMint, isSigner: false, isWritable: true },\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        rewardIndex,\n        emissionsPerSecondX64,\n        openTime: parseBigNumberish(openTime),\n        endTime: parseBigNumberish(endTime),\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.setRewardEmissions, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static setRewardInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    rewardInfo,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccount: PublicKey;\n    };\n    rewardInfo: {\n      mint: PublicKey;\n      openTime: number;\n      endTime: number;\n      emissionsPerSecondX64: BN;\n    };\n  }): ReturnTypeMakeInstructions {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n\n    let rewardIndex: number | undefined;\n    let rewardVault: PublicKey | undefined;\n    let rewardMint: PublicKey | undefined;\n    for (let index = 0; index < poolInfo.rewardDefaultInfos.length; index++)\n      if (poolInfo.rewardDefaultInfos[index].mint.address === rewardInfo.mint.toString()) {\n        rewardIndex = index;\n        rewardVault = new PublicKey(poolKeys.rewardInfos[index].vault);\n        rewardMint = new PublicKey(poolKeys.rewardInfos[index].mint.address);\n      }\n\n    if (rewardIndex === undefined || rewardVault === undefined)\n      logger.logWithError(\"reward mint check error\", \"no reward mint\", poolInfo.rewardDefaultInfos);\n\n    const operationId = getPdaOperationAccount(programId).publicKey;\n\n    const ins = [\n      this.setRewardInstruction(\n        programId,\n        ownerInfo.wallet,\n        id,\n        operationId,\n        new PublicKey(poolInfo.config.id),\n\n        ownerInfo.tokenAccount,\n        rewardVault!,\n        rewardMint!,\n\n        rewardIndex!,\n        rewardInfo.openTime,\n        rewardInfo.endTime,\n        rewardInfo.emissionsPerSecondX64,\n      ),\n    ];\n    return {\n      address: { rewardVault: rewardVault!, operationId },\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmSetReward],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static collectRewardInstruction(\n    programId: PublicKey,\n    payer: PublicKey,\n    poolId: PublicKey,\n\n    ownerTokenAccount: PublicKey,\n    rewardVault: PublicKey,\n    rewardMint: PublicKey,\n\n    rewardIndex: number,\n  ): TransactionInstruction {\n    const dataLayout = struct([u8(\"rewardIndex\")]);\n\n    const keys = [\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: ownerTokenAccount, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: rewardVault, isSigner: false, isWritable: true },\n      { pubkey: rewardMint, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        rewardIndex,\n      },\n      data,\n    );\n\n    const aData = Buffer.from([...anchorDataBuf.collectReward, ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static collectRewardInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    rewardMint,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerInfo: {\n      wallet: PublicKey;\n      tokenAccount: PublicKey;\n    };\n    rewardMint: PublicKey;\n  }): ReturnTypeMakeInstructions {\n    const [programId, id] = [new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)];\n    let rewardIndex: number | undefined;\n    let rewardVault: PublicKey | undefined;\n    for (let index = 0; index < poolInfo.rewardDefaultInfos.length; index++)\n      if (poolInfo.rewardDefaultInfos[index].mint.address === rewardMint.toString()) {\n        rewardIndex = index;\n        rewardVault = new PublicKey(poolKeys.rewardInfos[index].vault);\n      }\n\n    if (rewardIndex === undefined || rewardVault === undefined)\n      logger.logWithError(\"reward mint check error\", \"no reward mint\", poolInfo.rewardDefaultInfos);\n\n    const ins = [\n      this.collectRewardInstruction(\n        programId,\n        ownerInfo.wallet,\n        id,\n\n        ownerInfo.tokenAccount,\n        rewardVault!,\n        rewardMint,\n\n        rewardIndex!,\n      ),\n    ];\n    return {\n      address: { rewardVault: rewardVault! },\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.ClmmCollectReward],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    };\n  }\n\n  static async makeLockPositions({\n    programId,\n    authProgramId,\n    poolProgramId,\n    payer,\n    wallet,\n    nftMint,\n    nft2022,\n    getEphemeralSigners,\n  }: {\n    programId: PublicKey;\n    authProgramId: PublicKey;\n    poolProgramId: PublicKey;\n    wallet: PublicKey;\n    payer: PublicKey;\n    nftMint: PublicKey;\n    nft2022?: boolean;\n    getEphemeralSigners?: (k: number) => any;\n  }): Promise<ReturnTypeMakeInstructions<ClmmLockAddress>> {\n    const signers: Signer[] = [];\n    let lockNftMint: PublicKey;\n    if (getEphemeralSigners) {\n      lockNftMint = new PublicKey((await getEphemeralSigners(1))[0]);\n    } else {\n      const _k = Keypair.generate();\n      signers.push(_k);\n      lockNftMint = _k.publicKey;\n    }\n\n    const positionNftAccount = nft2022\n      ? getATAAddress(wallet, nftMint, TOKEN_2022_PROGRAM_ID).publicKey\n      : getATAAddress(wallet, nftMint, TOKEN_PROGRAM_ID).publicKey;\n    const { publicKey: positionId } = getPdaPersonalPositionAddress(poolProgramId, nftMint);\n    const lockPositionId = getPdaLockClPositionIdV2(programId, lockNftMint).publicKey;\n    const lockNftAccount = getATAAddress(wallet, lockNftMint, TOKEN_PROGRAM_ID).publicKey;\n    const metadataAccount = getPdaMetadataKey(lockNftMint).publicKey;\n\n    const ins = ClmmInstrument.lockPositionInstructionV2({\n      programId,\n      auth: authProgramId,\n      payer,\n      positionOwner: wallet,\n      lockOwner: wallet,\n      positionNftAccount,\n      positionId,\n      lockPositionId,\n      lockNftMint,\n      lockNftAccount,\n      metadataAccount,\n      withMetadata: true,\n      nft2022,\n\n      positionNftMint: nftMint,\n      authPositionNftAccount: getATAAddress(authProgramId, nftMint, nft2022 ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID)\n        .publicKey,\n      positionNftProgram: nft2022 ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID,\n    });\n\n    return {\n      address: {\n        positionId,\n        lockPositionId,\n        lockNftAccount,\n        lockNftMint,\n        positionNftAccount,\n        metadataAccount,\n      },\n      instructions: [ins],\n      signers,\n      instructionTypes: [InstructionType.ClmmLockPosition],\n      lookupTableAddress: [],\n    };\n  }\n\n  static lockPositionInstructionV2({\n    programId,\n    auth,\n    payer,\n    positionOwner,\n    lockOwner,\n    positionNftAccount,\n    positionId,\n    positionNftMint,\n    authPositionNftAccount,\n    positionNftProgram,\n    lockPositionId,\n    lockNftMint,\n    lockNftAccount,\n    metadataAccount,\n    withMetadata,\n  }: {\n    programId: PublicKey;\n    auth: PublicKey;\n    payer: PublicKey;\n    positionOwner: PublicKey;\n    lockOwner: PublicKey;\n    positionNftAccount: PublicKey;\n    positionId: PublicKey;\n    positionNftMint: PublicKey;\n    authPositionNftAccount: PublicKey;\n    positionNftProgram: PublicKey;\n    lockPositionId: PublicKey;\n    lockNftMint: PublicKey;\n    lockNftAccount: PublicKey;\n    metadataAccount: PublicKey;\n    withMetadata: boolean;\n    nft2022?: boolean;\n  }): TransactionInstruction {\n    const keys = [\n      { pubkey: auth, isSigner: false, isWritable: false },\n      { pubkey: payer, isSigner: true, isWritable: true },\n      { pubkey: positionOwner, isSigner: true, isWritable: true },\n      { pubkey: lockOwner, isSigner: false, isWritable: false },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: positionId, isSigner: false, isWritable: false },\n      { pubkey: positionNftMint, isSigner: false, isWritable: true },\n      { pubkey: authPositionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: lockPositionId, isSigner: false, isWritable: true },\n      { pubkey: lockNftMint, isSigner: true, isWritable: true },\n      { pubkey: lockNftAccount, isSigner: false, isWritable: true },\n      { pubkey: metadataAccount, isSigner: false, isWritable: true },\n      { pubkey: METADATA_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: positionNftProgram, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    ];\n    const dataLayout = struct([bool(\"withMetadata\")]);\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        withMetadata,\n      },\n      data,\n    );\n    const aData = Buffer.from([...lockInsDataBuf, ...data]);\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n\n  static lockPositionInstruction({\n    programId,\n    authProgramId,\n    poolProgramId,\n    owner,\n    positionNft,\n  }: {\n    programId: PublicKey;\n    authProgramId: PublicKey;\n    poolProgramId: PublicKey;\n    owner: PublicKey;\n    positionNft: PublicKey;\n  }): TransactionInstruction {\n    const { publicKey: nftAccount } = getATAAddress(owner, positionNft, TOKEN_PROGRAM_ID);\n    const { publicKey: positionId } = getPdaPersonalPositionAddress(poolProgramId, positionNft);\n\n    const keys = [\n      { pubkey: authProgramId, isSigner: false, isWritable: false },\n      { pubkey: owner, isSigner: true, isWritable: false },\n      { pubkey: nftAccount, isSigner: false, isWritable: true },\n      { pubkey: positionId, isSigner: false, isWritable: false },\n      { pubkey: getPdaLockPositionId(programId, positionId).publicKey, isSigner: false, isWritable: true },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    ];\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: Buffer.from(lockInsDataBuf),\n    });\n  }\n\n  static harvestLockPositionInstruction(props: {\n    poolKeys: ClmmKeys;\n    programId: PublicKey;\n    authProgramId: PublicKey;\n    ownerPosition: ClmmPositionLayout;\n    owner: PublicKey;\n    ownerRewardAccounts: PublicKey[];\n    userVaultA: PublicKey;\n    userVaultB: PublicKey;\n  }): TransactionInstruction {\n    const [poolProgramId, poolId] = [new PublicKey(props.poolKeys.programId), new PublicKey(props.poolKeys.id)];\n\n    const tickArrayLowerStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      props.ownerPosition.tickLower,\n      props.poolKeys.config.tickSpacing,\n    );\n    const tickArrayUpperStartIndex = TickUtils.getTickArrayStartIndexByTick(\n      props.ownerPosition.tickUpper,\n      props.poolKeys.config.tickSpacing,\n    );\n    const { publicKey: tickArrayLower } = getPdaTickArrayAddress(poolProgramId, poolId, tickArrayLowerStartIndex);\n    const { publicKey: tickArrayUpper } = getPdaTickArrayAddress(poolProgramId, poolId, tickArrayUpperStartIndex);\n    const { publicKey: nftAccount } = getATAAddress(props.owner, props.ownerPosition.nftMint, TOKEN_PROGRAM_ID);\n    const { publicKey: positionId } = getPdaPersonalPositionAddress(poolProgramId, props.ownerPosition.nftMint);\n    const { publicKey: protocolPosition } = getPdaProtocolPositionAddress(\n      poolProgramId,\n      poolId,\n      props.ownerPosition.tickLower,\n      props.ownerPosition.tickUpper,\n    );\n\n    const rewardAccounts: {\n      poolRewardVault: PublicKey;\n      ownerRewardVault: PublicKey;\n      rewardMint: PublicKey;\n    }[] = [];\n\n    for (let i = 0; i < props.poolKeys.rewardInfos.length; i++) {\n      rewardAccounts.push({\n        poolRewardVault: new PublicKey(props.poolKeys.rewardInfos[i].vault),\n        ownerRewardVault: props.ownerRewardAccounts[i],\n        rewardMint: new PublicKey(props.poolKeys.rewardInfos[i].mint.address),\n      });\n    }\n\n    const remainingAccounts = [\n      ...rewardAccounts\n        .map((i) => [\n          { pubkey: i.poolRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.ownerRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.rewardMint, isSigner: false, isWritable: false },\n        ])\n        .flat(),\n    ];\n\n    const keys = [\n      { pubkey: props.authProgramId, isSigner: false, isWritable: false },\n      { pubkey: getPdaLockPositionId(props.programId, positionId).publicKey, isSigner: false, isWritable: false },\n      { pubkey: poolProgramId, isSigner: false, isWritable: false },\n      { pubkey: props.owner, isSigner: true, isWritable: false },\n      { pubkey: nftAccount, isSigner: false, isWritable: true },\n      { pubkey: positionId, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: new PublicKey(props.poolKeys.vault.A), isSigner: false, isWritable: true },\n      { pubkey: new PublicKey(props.poolKeys.vault.B), isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: props.userVaultA, isSigner: false, isWritable: true },\n      { pubkey: props.userVaultB, isSigner: false, isWritable: true },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: MEMO_PROGRAM_ID2, isSigner: false, isWritable: false },\n      { pubkey: new PublicKey(props.poolKeys.mintA.address), isSigner: false, isWritable: false },\n      { pubkey: new PublicKey(props.poolKeys.mintB.address), isSigner: false, isWritable: false },\n      ...remainingAccounts,\n    ];\n\n    return new TransactionInstruction({\n      keys,\n      programId: props.programId,\n      data: Buffer.from(lockHarvestInsDataBuf),\n    });\n  }\n\n  static harvestLockPositionInstructionV2({\n    programId,\n    auth,\n    lockPositionId,\n    clmmProgram,\n    lockOwner,\n    lockNftMint,\n    lockNftAccount,\n    positionNftAccount,\n    positionId,\n    poolId,\n    protocolPosition,\n    vaultA,\n    vaultB,\n    tickArrayLower,\n    tickArrayUpper,\n    userVaultA,\n    userVaultB,\n    mintA,\n    mintB,\n    rewardAccounts,\n    exTickArrayBitmap,\n  }: {\n    programId: PublicKey;\n    auth: PublicKey;\n    lockPositionId: PublicKey;\n    clmmProgram: PublicKey;\n    lockOwner: PublicKey;\n    lockNftMint: PublicKey;\n    lockNftAccount: PublicKey;\n    positionNftAccount: PublicKey;\n    positionId: PublicKey;\n    poolId: PublicKey;\n    protocolPosition: PublicKey;\n    vaultA: PublicKey;\n    vaultB: PublicKey;\n    tickArrayLower: PublicKey;\n    tickArrayUpper: PublicKey;\n    userVaultA: PublicKey;\n    userVaultB: PublicKey;\n    mintA: PublicKey;\n    mintB: PublicKey;\n    rewardAccounts: {\n      poolRewardVault: PublicKey;\n      ownerRewardVault: PublicKey;\n      rewardMint: PublicKey;\n    }[];\n\n    exTickArrayBitmap?: PublicKey;\n  }): TransactionInstruction {\n    const remainingAccounts = [\n      ...(exTickArrayBitmap ? [{ pubkey: exTickArrayBitmap, isSigner: false, isWritable: true }] : []),\n      ...rewardAccounts\n        .map((i) => [\n          { pubkey: i.poolRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.ownerRewardVault, isSigner: false, isWritable: true },\n          { pubkey: i.rewardMint, isSigner: false, isWritable: false },\n        ])\n        .flat(),\n    ];\n\n    const keys = [\n      { pubkey: auth, isSigner: false, isWritable: false },\n      { pubkey: lockOwner, isSigner: true, isWritable: false },\n      // { pubkey: lockNftMint, isSigner: false, isWritable: false },\n      { pubkey: lockNftAccount, isSigner: false, isWritable: true },\n      { pubkey: lockPositionId, isSigner: false, isWritable: false },\n      { pubkey: clmmProgram, isSigner: false, isWritable: false },\n      { pubkey: positionNftAccount, isSigner: false, isWritable: true },\n      { pubkey: positionId, isSigner: false, isWritable: true },\n      { pubkey: poolId, isSigner: false, isWritable: true },\n      { pubkey: protocolPosition, isSigner: false, isWritable: true },\n      { pubkey: vaultA, isSigner: false, isWritable: true },\n      { pubkey: vaultB, isSigner: false, isWritable: true },\n      { pubkey: tickArrayLower, isSigner: false, isWritable: true },\n      { pubkey: tickArrayUpper, isSigner: false, isWritable: true },\n      { pubkey: userVaultA, isSigner: false, isWritable: true },\n      { pubkey: userVaultB, isSigner: false, isWritable: true },\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n      { pubkey: MEMO_PROGRAM_ID2, isSigner: false, isWritable: false },\n      { pubkey: mintA, isSigner: false, isWritable: false },\n      { pubkey: mintB, isSigner: false, isWritable: false },\n      ...remainingAccounts,\n    ];\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: Buffer.from(lockHarvestInsDataBuf),\n    });\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"../../../api/type\";\nimport { ClmmPoolInfo, TickArrayBitmapExtensionType } from \"../type\";\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { SqrtPriceMath, TickMath } from \"./math\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { TickQuery } from \"./tickQuery\";\n\nexport const TICK_ARRAY_SIZE = 60;\nexport const TICK_ARRAY_BITMAP_SIZE = 512;\n\nexport interface ReturnTypeGetTickPrice {\n  tick: number;\n  price: Decimal;\n  tickSqrtPriceX64: BN;\n}\n\nexport interface ReturnTypeGetPriceAndTick {\n  tick: number;\n  price: Decimal;\n}\n\nexport type Tick = {\n  tick: number;\n  liquidityNet: BN;\n  liquidityGross: BN;\n  feeGrowthOutsideX64A: BN;\n  feeGrowthOutsideX64B: BN;\n  rewardGrowthsOutsideX64: BN[];\n};\n\nexport type TickArray = {\n  address: PublicKey;\n  poolId: PublicKey;\n  startTickIndex: number;\n  ticks: Tick[];\n  initializedTickCount: number;\n};\n\nexport type TickState = {\n  tick: number;\n  liquidityNet: BN;\n  liquidityGross: BN;\n  feeGrowthOutsideX64A: BN;\n  feeGrowthOutsideX64B: BN;\n  tickCumulativeOutside: BN;\n  secondsPerLiquidityOutsideX64: BN;\n  secondsOutside: number;\n  rewardGrowthsOutside: BN[];\n};\n\nexport type TickArrayState = {\n  ammPool: PublicKey;\n  startTickIndex: number;\n  ticks: TickState[];\n  initializedTickCount: number;\n};\n\nexport class TickUtils {\n  public static getTickArrayAddressByTick(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickIndex: number,\n    tickSpacing: number,\n  ): PublicKey {\n    const startIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n    const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, startIndex);\n    return tickArrayAddress;\n  }\n\n  public static getTickOffsetInArray(tickIndex: number, tickSpacing: number): number {\n    if (tickIndex % tickSpacing != 0) {\n      throw new Error(\"tickIndex % tickSpacing not equal 0\");\n    }\n    const startTickIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n    const offsetInArray = Math.floor((tickIndex - startTickIndex) / tickSpacing);\n    if (offsetInArray < 0 || offsetInArray >= TICK_ARRAY_SIZE) {\n      throw new Error(\"tick offset in array overflow\");\n    }\n    return offsetInArray;\n  }\n\n  public static getTickArrayBitIndex(tickIndex: number, tickSpacing: number): number {\n    const ticksInArray = TickQuery.tickCount(tickSpacing);\n\n    let startIndex: number = tickIndex / ticksInArray;\n    if (tickIndex < 0 && tickIndex % ticksInArray != 0) {\n      startIndex = Math.ceil(startIndex) - 1;\n    } else {\n      startIndex = Math.floor(startIndex);\n    }\n    return startIndex;\n  }\n\n  public static getTickArrayStartIndexByTick(tickIndex: number, tickSpacing: number): number {\n    return this.getTickArrayBitIndex(tickIndex, tickSpacing) * TickQuery.tickCount(tickSpacing);\n  }\n\n  public static getTickArrayOffsetInBitmapByTick(tick: number, tickSpacing: number): number {\n    const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n    const compressed = Math.floor(tick / multiplier) + 512;\n    return Math.abs(compressed);\n  }\n\n  public static checkTickArrayIsInitialized(\n    bitmap: BN,\n    tick: number,\n    tickSpacing: number,\n  ): {\n    isInitialized: boolean;\n    startIndex: number;\n  } {\n    const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n    const compressed = Math.floor(tick / multiplier) + 512;\n    const bitPos = Math.abs(compressed);\n    return {\n      isInitialized: bitmap.testn(bitPos),\n      startIndex: (bitPos - 512) * multiplier,\n    };\n  }\n\n  public static getNextTickArrayStartIndex(\n    lastTickArrayStartIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n  ): number {\n    return zeroForOne\n      ? lastTickArrayStartIndex - tickSpacing * TICK_ARRAY_SIZE\n      : lastTickArrayStartIndex + tickSpacing * TICK_ARRAY_SIZE;\n  }\n\n  public static mergeTickArrayBitmap(bns: BN[]): BN {\n    let b = new BN(0);\n    for (let i = 0; i < bns.length; i++) {\n      b = b.add(bns[i].shln(64 * i));\n    }\n    return b;\n  }\n\n  public static getInitializedTickArrayInRange(\n    tickArrayBitmap: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n    tickSpacing: number,\n    tickArrayStartIndex: number,\n    expectedCount: number,\n  ): number[] {\n    const tickArrayOffset = Math.floor(tickArrayStartIndex / (tickSpacing * TICK_ARRAY_SIZE));\n    return [\n      // find right of currenct offset\n      ...TickUtils.searchLowBitFromStart(\n        tickArrayBitmap,\n        exTickArrayBitmap,\n        tickArrayOffset - 1,\n        expectedCount,\n        tickSpacing,\n      ),\n\n      // find left of current offset\n      ...TickUtils.searchHightBitFromStart(\n        tickArrayBitmap,\n        exTickArrayBitmap,\n        tickArrayOffset,\n        expectedCount,\n        tickSpacing,\n      ),\n    ];\n  }\n\n  public static getAllInitializedTickArrayStartIndex(\n    tickArrayBitmap: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n    tickSpacing: number,\n  ): number[] {\n    // find from offset 0 to 1024\n    return TickUtils.searchHightBitFromStart(\n      tickArrayBitmap,\n      exTickArrayBitmap,\n      -7680,\n      TICK_ARRAY_BITMAP_SIZE,\n      tickSpacing,\n    );\n  }\n\n  public static getAllInitializedTickArrayInfo(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickArrayBitmap: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n    tickSpacing: number,\n  ): {\n    tickArrayStartIndex: number;\n    tickArrayAddress: PublicKey;\n  }[] {\n    const result: {\n      tickArrayStartIndex: number;\n      tickArrayAddress: PublicKey;\n    }[] = [];\n    const allInitializedTickArrayIndex: number[] = TickUtils.getAllInitializedTickArrayStartIndex(\n      tickArrayBitmap,\n      exTickArrayBitmap,\n      tickSpacing,\n    );\n    for (const startIndex of allInitializedTickArrayIndex) {\n      const { publicKey: address } = getPdaTickArrayAddress(programId, poolId, startIndex);\n      result.push({\n        tickArrayStartIndex: startIndex,\n        tickArrayAddress: address,\n      });\n    }\n    return result;\n  }\n\n  public static getAllInitializedTickInTickArray(tickArray: TickArrayState): TickState[] {\n    return tickArray.ticks.filter((i) => i.liquidityGross.gtn(0));\n  }\n\n  public static searchLowBitFromStart(\n    tickArrayBitmap: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n    currentTickArrayBitStartIndex: number,\n    expectedCount: number,\n    tickSpacing: number,\n  ): number[] {\n    const tickArrayBitmaps = [\n      ...[...exTickArrayBitmap.negativeTickArrayBitmap].reverse(),\n      tickArrayBitmap.slice(0, 8),\n      tickArrayBitmap.slice(8, 16),\n      ...exTickArrayBitmap.positiveTickArrayBitmap,\n    ].map((i) => TickUtils.mergeTickArrayBitmap(i));\n    const result: number[] = [];\n    while (currentTickArrayBitStartIndex >= -7680) {\n      const arrayIndex = Math.floor((currentTickArrayBitStartIndex + 7680) / 512);\n      const searchIndex = (currentTickArrayBitStartIndex + 7680) % 512;\n\n      if (tickArrayBitmaps[arrayIndex].testn(searchIndex)) result.push(currentTickArrayBitStartIndex);\n\n      currentTickArrayBitStartIndex--;\n      if (result.length === expectedCount) break;\n    }\n\n    const tickCount = TickQuery.tickCount(tickSpacing);\n    return result.map((i) => i * tickCount);\n  }\n\n  public static searchHightBitFromStart(\n    tickArrayBitmap: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n    currentTickArrayBitStartIndex: number,\n    expectedCount: number,\n    tickSpacing: number,\n  ): number[] {\n    const tickArrayBitmaps = [\n      ...[...exTickArrayBitmap.negativeTickArrayBitmap].reverse(),\n      tickArrayBitmap.slice(0, 8),\n      tickArrayBitmap.slice(8, 16),\n      ...exTickArrayBitmap.positiveTickArrayBitmap,\n    ].map((i) => TickUtils.mergeTickArrayBitmap(i));\n    const result: number[] = [];\n    while (currentTickArrayBitStartIndex < 7680) {\n      const arrayIndex = Math.floor((currentTickArrayBitStartIndex + 7680) / 512);\n      const searchIndex = (currentTickArrayBitStartIndex + 7680) % 512;\n\n      if (tickArrayBitmaps[arrayIndex].testn(searchIndex)) result.push(currentTickArrayBitStartIndex);\n\n      currentTickArrayBitStartIndex++;\n      if (result.length === expectedCount) break;\n    }\n\n    const tickCount = TickQuery.tickCount(tickSpacing);\n    return result.map((i) => i * tickCount);\n  }\n\n  public static checkIsOutOfBoundary(tick: number): boolean {\n    return tick < MIN_TICK || tick > MAX_TICK;\n  }\n\n  public static nextInitTick(\n    tickArrayCurrent: TickArray,\n    currentTickIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n    t: boolean,\n  ): Tick | null {\n    const currentTickArrayStartIndex = TickQuery.getArrayStartIndex(currentTickIndex, tickSpacing);\n    if (currentTickArrayStartIndex != tickArrayCurrent.startTickIndex) {\n      return null;\n    }\n    let offsetInArray = Math.floor((currentTickIndex - tickArrayCurrent.startTickIndex) / tickSpacing);\n\n    if (zeroForOne) {\n      while (offsetInArray >= 0) {\n        if (tickArrayCurrent.ticks[offsetInArray].liquidityGross.gtn(0)) {\n          return tickArrayCurrent.ticks[offsetInArray];\n        }\n        offsetInArray = offsetInArray - 1;\n      }\n    } else {\n      if (!t) offsetInArray = offsetInArray + 1;\n      while (offsetInArray < TICK_ARRAY_SIZE) {\n        if (tickArrayCurrent.ticks[offsetInArray].liquidityGross.gtn(0)) {\n          return tickArrayCurrent.ticks[offsetInArray];\n        }\n        offsetInArray = offsetInArray + 1;\n      }\n    }\n    return null;\n  }\n\n  public static firstInitializedTick(tickArrayCurrent: TickArray, zeroForOne: boolean): Tick {\n    if (zeroForOne) {\n      let i = TICK_ARRAY_SIZE - 1;\n      while (i >= 0) {\n        if (tickArrayCurrent.ticks[i].liquidityGross.gtn(0)) {\n          return tickArrayCurrent.ticks[i];\n        }\n        i = i - 1;\n      }\n    } else {\n      let i = 0;\n      while (i < TICK_ARRAY_SIZE) {\n        if (tickArrayCurrent.ticks[i].liquidityGross.gtn(0)) {\n          return tickArrayCurrent.ticks[i];\n        }\n        i = i + 1;\n      }\n    }\n\n    throw Error(`firstInitializedTick check error: ${tickArrayCurrent} - ${zeroForOne}`);\n  }\n\n  public static _getTickPriceLegacy({\n    poolInfo,\n    tick,\n    baseIn,\n  }: {\n    poolInfo: ClmmPoolInfo;\n    tick: number;\n    baseIn: boolean;\n  }): ReturnTypeGetTickPrice {\n    const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n    const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      tickSqrtPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n\n    return baseIn\n      ? { tick, price: tickPrice, tickSqrtPriceX64 }\n      : { tick, price: new Decimal(1).div(tickPrice), tickSqrtPriceX64 };\n  }\n\n  public static _getPriceAndTickLegacy({\n    poolInfo,\n    price,\n    baseIn,\n  }: {\n    poolInfo: ClmmPoolInfo;\n    price: Decimal;\n    baseIn: boolean;\n  }): ReturnTypeGetPriceAndTick {\n    const _price = baseIn ? price : new Decimal(1).div(price);\n\n    const tick = TickMath.getTickWithPriceAndTickspacing(\n      _price,\n      poolInfo.ammConfig.tickSpacing,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n    const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      tickSqrtPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n\n    return baseIn ? { tick, price: tickPrice } : { tick, price: new Decimal(1).div(tickPrice) };\n  }\n\n  public static getTickPrice({\n    poolInfo,\n    tick,\n    baseIn,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    tick: number;\n    baseIn: boolean;\n  }): ReturnTypeGetTickPrice {\n    const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n    const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      tickSqrtPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n\n    return baseIn\n      ? { tick, price: tickPrice, tickSqrtPriceX64 }\n      : { tick, price: new Decimal(1).div(tickPrice), tickSqrtPriceX64 };\n  }\n\n  public static getPriceAndTick({\n    poolInfo,\n    price,\n    baseIn,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    price: Decimal;\n    baseIn: boolean;\n  }): ReturnTypeGetPriceAndTick {\n    const _price = baseIn ? price : new Decimal(1).div(price);\n\n    const tick = TickMath.getTickWithPriceAndTickspacing(\n      _price,\n      poolInfo.config.tickSpacing,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const tickSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n    const tickPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      tickSqrtPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n\n    return baseIn ? { tick, price: tickPrice } : { tick, price: new Decimal(1).div(tickPrice) };\n  }\n}\n","import BN from \"bn.js\";\n\nexport const ZERO = new BN(0);\nexport const ONE = new BN(1);\nexport const NEGATIVE_ONE = new BN(-1);\n\nexport const Q64 = new BN(1).shln(64);\nexport const Q128 = new BN(1).shln(128);\n\nexport const MaxU64 = Q64.sub(ONE);\n\nexport const U64Resolution = 64;\n\nexport const MaxUint128 = Q128.subn(1);\n\nexport const MIN_TICK = -443636;\nexport const MAX_TICK = -MIN_TICK;\n\nexport const MIN_SQRT_PRICE_X64: BN = new BN(\"4295048016\");\nexport const MAX_SQRT_PRICE_X64: BN = new BN(\"79226673521066979257578248091\");\n\nexport const MIN_SQRT_PRICE_X64_ADD_ONE: BN = new BN(\"4295048017\");\nexport const MAX_SQRT_PRICE_X64_SUB_ONE: BN = new BN(\"79226673521066979257578248090\");\n\n// export const MIN_TICK_ARRAY_START_INDEX = -307200;\n// export const MAX_TICK_ARRAY_START_INDEX = 306600;\n\nexport const BIT_PRECISION = 16;\nexport const LOG_B_2_X32 = \"59543866431248\";\nexport const LOG_B_P_ERR_MARGIN_LOWER_X64 = \"184467440737095516\";\nexport const LOG_B_P_ERR_MARGIN_UPPER_X64 = \"15793534762490258745\";\n\nexport const FEE_RATE_DENOMINATOR = new BN(10).pow(new BN(6));\n\nexport enum Fee {\n  rate_500 = 500, //  500 / 10e6 = 0.0005\n  rate_3000 = 3000, // 3000/ 10e6 = 0.003\n  rate_10000 = 10000, // 10000 /10e6 = 0.01\n}\nexport const TICK_SPACINGS: { [amount in Fee]: number } = {\n  [Fee.rate_500]: 10,\n  [Fee.rate_3000]: 60,\n  [Fee.rate_10000]: 200,\n};\n\nexport const mockCreatePoolInfo = {\n  version: 6,\n  liquidity: ZERO,\n  tickCurrent: 0,\n  feeGrowthGlobalX64A: ZERO,\n  feeGrowthGlobalX64B: ZERO,\n  protocolFeesTokenA: ZERO,\n  protocolFeesTokenB: ZERO,\n  swapInAmountTokenA: ZERO,\n  swapOutAmountTokenB: ZERO,\n  swapInAmountTokenB: ZERO,\n  swapOutAmountTokenA: ZERO,\n  tickArrayBitmap: [],\n\n  rewardInfos: [],\n\n  day: {\n    volume: 0,\n    volumeFee: 0,\n    feeA: 0,\n    feeB: 0,\n    feeApr: 0,\n    rewardApr: { A: 0, B: 0, C: 0 },\n    apr: 0,\n    priceMax: 0,\n    priceMin: 0,\n  },\n  week: {\n    volume: 0,\n    volumeFee: 0,\n    feeA: 0,\n    feeB: 0,\n    feeApr: 0,\n    rewardApr: { A: 0, B: 0, C: 0 },\n    apr: 0,\n    priceMax: 0,\n    priceMin: 0,\n  },\n  month: {\n    volume: 0,\n    volumeFee: 0,\n    feeA: 0,\n    feeB: 0,\n    feeApr: 0,\n    rewardApr: { A: 0, B: 0, C: 0 },\n    apr: 0,\n    priceMax: 0,\n    priceMin: 0,\n  },\n  tvl: 0,\n};\n\nexport const mockV3CreatePoolInfo = {\n  tvl: 0,\n  volumeQuote: 0,\n  mintAmountA: 0,\n  mintAmountB: 0,\n  rewardDefaultInfos: [],\n  farmUpcomingCount: 0,\n  farmOngoingCount: 0,\n  farmFinishedCount: 0,\n\n  day: {\n    volume: 0,\n    volumeQuote: 0,\n    volumeFee: 0,\n    apr: 0,\n    feeApr: 0,\n    priceMin: 0,\n    priceMax: 0,\n    rewardApr: [0],\n  },\n  week: {\n    volume: 0,\n    volumeQuote: 0,\n    volumeFee: 0,\n    apr: 0,\n    feeApr: 0,\n    priceMin: 0,\n    priceMax: 0,\n    rewardApr: [0],\n  },\n  month: {\n    volume: 0,\n    volumeQuote: 0,\n    volumeFee: 0,\n    apr: 0,\n    feeApr: 0,\n    priceMin: 0,\n    priceMax: 0,\n    rewardApr: [0],\n  },\n  pooltype: [],\n};\n\nexport const U64_IGNORE_RANGE = new BN(\"18446744073700000000\");\n","import { EpochInfo, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"../../../api/type\";\nimport { getTransferAmountFeeV2, minExpirationTime } from \"../../../common/transfer\";\nimport { ReturnTypeGetLiquidityAmountOut, TickArrayBitmapExtensionType } from \"../type\";\nimport {\n  BIT_PRECISION,\n  Fee,\n  FEE_RATE_DENOMINATOR,\n  LOG_B_2_X32,\n  LOG_B_P_ERR_MARGIN_LOWER_X64,\n  LOG_B_P_ERR_MARGIN_UPPER_X64,\n  MAX_SQRT_PRICE_X64,\n  MAX_TICK,\n  MaxU64,\n  MaxUint128,\n  MIN_SQRT_PRICE_X64,\n  MIN_TICK,\n  NEGATIVE_ONE,\n  ONE,\n  Q128,\n  Q64,\n  U64Resolution,\n  ZERO,\n} from \"./constants\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { PoolUtils } from \"./pool\";\nimport { Tick, TickArray, TickUtils } from \"./tick\";\nimport { TickQuery } from \"./tickQuery\";\n\nexport class MathUtil {\n  public static mulDivRoundingUp(a: BN, b: BN, denominator: BN): BN {\n    const numerator = a.mul(b);\n    let result = numerator.div(denominator);\n    if (!numerator.mod(denominator).eq(ZERO)) {\n      result = result.add(ONE);\n    }\n    return result;\n  }\n\n  public static mulDivFloor(a: BN, b: BN, denominator: BN): BN {\n    if (denominator.eq(ZERO)) {\n      throw new Error(\"division by 0\");\n    }\n    return a.mul(b).div(denominator);\n  }\n\n  public static mulDivCeil(a: BN, b: BN, denominator: BN): BN {\n    if (denominator.eq(ZERO)) {\n      throw new Error(\"division by 0\");\n    }\n    const numerator = a.mul(b).add(denominator.sub(ONE));\n    return numerator.div(denominator);\n  }\n\n  public static x64ToDecimal(num: BN, decimalPlaces?: number): Decimal {\n    return new Decimal(num.toString()).div(Decimal.pow(2, 64)).toDecimalPlaces(decimalPlaces);\n  }\n\n  public static decimalToX64(num: Decimal): BN {\n    return new BN(num.mul(Decimal.pow(2, 64)).floor().toFixed());\n  }\n\n  public static wrappingSubU128(n0: BN, n1: BN): BN {\n    return n0.add(Q128).sub(n1).mod(Q128);\n  }\n}\n\n// sqrt price math\nfunction mulRightShift(val: BN, mulBy: BN): BN {\n  return signedRightShift(val.mul(mulBy), 64, 256);\n}\n\nfunction signedLeftShift(n0: BN, shiftBy: number, bitWidth: number): BN {\n  const twosN0 = n0.toTwos(bitWidth).shln(shiftBy);\n  twosN0.imaskn(bitWidth + 1);\n  return twosN0.fromTwos(bitWidth);\n}\n\nfunction signedRightShift(n0: BN, shiftBy: number, bitWidth: number): BN {\n  const twoN0 = n0.toTwos(bitWidth).shrn(shiftBy);\n  twoN0.imaskn(bitWidth - shiftBy + 1);\n  return twoN0.fromTwos(bitWidth - shiftBy);\n}\n\nexport class SqrtPriceMath {\n  public static sqrtPriceX64ToPrice(sqrtPriceX64: BN, decimalsA: number, decimalsB: number): Decimal {\n    return MathUtil.x64ToDecimal(sqrtPriceX64)\n      .pow(2)\n      .mul(Decimal.pow(10, decimalsA - decimalsB));\n  }\n\n  public static priceToSqrtPriceX64(price: Decimal, decimalsA: number, decimalsB: number): BN {\n    return MathUtil.decimalToX64(price.mul(Decimal.pow(10, decimalsB - decimalsA)).sqrt());\n  }\n\n  public static getNextSqrtPriceX64FromInput(sqrtPriceX64: BN, liquidity: BN, amountIn: BN, zeroForOne: boolean): BN {\n    if (!sqrtPriceX64.gt(ZERO)) {\n      throw new Error(\"sqrtPriceX64 must greater than 0\");\n    }\n    if (!liquidity.gt(ZERO)) {\n      throw new Error(\"liquidity must greater than 0\");\n    }\n\n    return zeroForOne\n      ? this.getNextSqrtPriceFromTokenAmountARoundingUp(sqrtPriceX64, liquidity, amountIn, true)\n      : this.getNextSqrtPriceFromTokenAmountBRoundingDown(sqrtPriceX64, liquidity, amountIn, true);\n  }\n\n  public static getNextSqrtPriceX64FromOutput(sqrtPriceX64: BN, liquidity: BN, amountOut: BN, zeroForOne: boolean): BN {\n    if (!sqrtPriceX64.gt(ZERO)) {\n      throw new Error(\"sqrtPriceX64 must greater than 0\");\n    }\n    if (!liquidity.gt(ZERO)) {\n      throw new Error(\"liquidity must greater than 0\");\n    }\n\n    return zeroForOne\n      ? this.getNextSqrtPriceFromTokenAmountBRoundingDown(sqrtPriceX64, liquidity, amountOut, false)\n      : this.getNextSqrtPriceFromTokenAmountARoundingUp(sqrtPriceX64, liquidity, amountOut, false);\n  }\n\n  private static getNextSqrtPriceFromTokenAmountARoundingUp(\n    sqrtPriceX64: BN,\n    liquidity: BN,\n    amount: BN,\n    add: boolean,\n  ): BN {\n    if (amount.eq(ZERO)) return sqrtPriceX64;\n    const liquidityLeftShift = liquidity.shln(U64Resolution);\n\n    if (add) {\n      const numerator1 = liquidityLeftShift;\n      const denominator = liquidityLeftShift.add(amount.mul(sqrtPriceX64));\n      if (denominator.gte(numerator1)) {\n        return MathUtil.mulDivCeil(numerator1, sqrtPriceX64, denominator);\n      }\n      return MathUtil.mulDivRoundingUp(numerator1, ONE, numerator1.div(sqrtPriceX64).add(amount));\n    } else {\n      const amountMulSqrtPrice = amount.mul(sqrtPriceX64);\n      if (!liquidityLeftShift.gt(amountMulSqrtPrice)) {\n        throw new Error(\"getNextSqrtPriceFromTokenAmountARoundingUp,liquidityLeftShift must gt amountMulSqrtPrice\");\n      }\n      const denominator = liquidityLeftShift.sub(amountMulSqrtPrice);\n      return MathUtil.mulDivCeil(liquidityLeftShift, sqrtPriceX64, denominator);\n    }\n  }\n\n  private static getNextSqrtPriceFromTokenAmountBRoundingDown(\n    sqrtPriceX64: BN,\n    liquidity: BN,\n    amount: BN,\n    add: boolean,\n  ): BN {\n    const deltaY = amount.shln(U64Resolution);\n    if (add) {\n      return sqrtPriceX64.add(deltaY.div(liquidity));\n    } else {\n      const amountDivLiquidity = MathUtil.mulDivRoundingUp(deltaY, ONE, liquidity);\n      if (!sqrtPriceX64.gt(amountDivLiquidity)) {\n        throw new Error(\"getNextSqrtPriceFromTokenAmountBRoundingDown sqrtPriceX64 must gt amountDivLiquidity\");\n      }\n      return sqrtPriceX64.sub(amountDivLiquidity);\n    }\n  }\n\n  public static getSqrtPriceX64FromTick(tick: number): BN {\n    if (!Number.isInteger(tick)) {\n      throw new Error(\"tick must be integer\");\n    }\n    if (tick < MIN_TICK || tick > MAX_TICK) {\n      throw new Error(\"tick must be in MIN_TICK and MAX_TICK\");\n    }\n    const tickAbs: number = tick < 0 ? tick * -1 : tick;\n\n    let ratio: BN = (tickAbs & 0x1) != 0 ? new BN(\"18445821805675395072\") : new BN(\"18446744073709551616\");\n    if ((tickAbs & 0x2) != 0) ratio = mulRightShift(ratio, new BN(\"18444899583751176192\"));\n    if ((tickAbs & 0x4) != 0) ratio = mulRightShift(ratio, new BN(\"18443055278223355904\"));\n    if ((tickAbs & 0x8) != 0) ratio = mulRightShift(ratio, new BN(\"18439367220385607680\"));\n    if ((tickAbs & 0x10) != 0) ratio = mulRightShift(ratio, new BN(\"18431993317065453568\"));\n    if ((tickAbs & 0x20) != 0) ratio = mulRightShift(ratio, new BN(\"18417254355718170624\"));\n    if ((tickAbs & 0x40) != 0) ratio = mulRightShift(ratio, new BN(\"18387811781193609216\"));\n    if ((tickAbs & 0x80) != 0) ratio = mulRightShift(ratio, new BN(\"18329067761203558400\"));\n    if ((tickAbs & 0x100) != 0) ratio = mulRightShift(ratio, new BN(\"18212142134806163456\"));\n    if ((tickAbs & 0x200) != 0) ratio = mulRightShift(ratio, new BN(\"17980523815641700352\"));\n    if ((tickAbs & 0x400) != 0) ratio = mulRightShift(ratio, new BN(\"17526086738831433728\"));\n    if ((tickAbs & 0x800) != 0) ratio = mulRightShift(ratio, new BN(\"16651378430235570176\"));\n    if ((tickAbs & 0x1000) != 0) ratio = mulRightShift(ratio, new BN(\"15030750278694412288\"));\n    if ((tickAbs & 0x2000) != 0) ratio = mulRightShift(ratio, new BN(\"12247334978884435968\"));\n    if ((tickAbs & 0x4000) != 0) ratio = mulRightShift(ratio, new BN(\"8131365268886854656\"));\n    if ((tickAbs & 0x8000) != 0) ratio = mulRightShift(ratio, new BN(\"3584323654725218816\"));\n    if ((tickAbs & 0x10000) != 0) ratio = mulRightShift(ratio, new BN(\"696457651848324352\"));\n    if ((tickAbs & 0x20000) != 0) ratio = mulRightShift(ratio, new BN(\"26294789957507116\"));\n    if ((tickAbs & 0x40000) != 0) ratio = mulRightShift(ratio, new BN(\"37481735321082\"));\n\n    if (tick > 0) ratio = MaxUint128.div(ratio);\n    return ratio;\n  }\n\n  public static getTickFromPrice(price: Decimal, decimalsA: number, decimalsB: number): number {\n    return SqrtPriceMath.getTickFromSqrtPriceX64(SqrtPriceMath.priceToSqrtPriceX64(price, decimalsA, decimalsB));\n  }\n\n  public static getTickFromSqrtPriceX64(sqrtPriceX64: BN): number {\n    if (sqrtPriceX64.gt(MAX_SQRT_PRICE_X64) || sqrtPriceX64.lt(MIN_SQRT_PRICE_X64)) {\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 = signedLeftShift(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      const 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 = signedRightShift(logbpX64.sub(new BN(LOG_B_P_ERR_MARGIN_LOWER_X64)), 64, 128).toNumber();\n    const tickHigh = signedRightShift(logbpX64.add(new BN(LOG_B_P_ERR_MARGIN_UPPER_X64)), 64, 128).toNumber();\n\n    if (tickLow == tickHigh) {\n      return tickLow;\n    } else {\n      const derivedTickHighSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tickHigh);\n      return derivedTickHighSqrtPriceX64.lte(sqrtPriceX64) ? tickHigh : tickLow;\n    }\n  }\n}\n\n// tick math\nexport class TickMath {\n  public static getTickWithPriceAndTickspacing(\n    price: Decimal,\n    tickSpacing: number,\n    mintDecimalsA: number,\n    mintDecimalsB: number,\n  ): number {\n    const tick = SqrtPriceMath.getTickFromSqrtPriceX64(\n      SqrtPriceMath.priceToSqrtPriceX64(price, mintDecimalsA, mintDecimalsB),\n    );\n    let result = tick / tickSpacing;\n    if (result < 0) {\n      result = Math.floor(result);\n    } else {\n      result = Math.ceil(result);\n    }\n    return result * tickSpacing;\n  }\n\n  public static roundPriceWithTickspacing(\n    price: Decimal,\n    tickSpacing: number,\n    mintDecimalsA: number,\n    mintDecimalsB: number,\n  ): Decimal {\n    const tick = TickMath.getTickWithPriceAndTickspacing(price, tickSpacing, mintDecimalsA, mintDecimalsB);\n    const sqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n    return SqrtPriceMath.sqrtPriceX64ToPrice(sqrtPriceX64, mintDecimalsA, mintDecimalsB);\n  }\n}\n\nexport class LiquidityMath {\n  public static addDelta(x: BN, y: BN): BN {\n    return x.add(y);\n  }\n\n  public static getTokenAmountAFromLiquidity(\n    sqrtPriceX64A: BN,\n    sqrtPriceX64B: BN,\n    liquidity: BN,\n    roundUp: boolean,\n  ): BN {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n\n    if (!sqrtPriceX64A.gt(ZERO)) {\n      throw new Error(\"sqrtPriceX64A must greater than 0\");\n    }\n\n    const numerator1 = liquidity.ushln(U64Resolution);\n    const numerator2 = sqrtPriceX64B.sub(sqrtPriceX64A);\n\n    return roundUp\n      ? MathUtil.mulDivRoundingUp(MathUtil.mulDivCeil(numerator1, numerator2, sqrtPriceX64B), ONE, sqrtPriceX64A)\n      : MathUtil.mulDivFloor(numerator1, numerator2, sqrtPriceX64B).div(sqrtPriceX64A);\n  }\n\n  public static getTokenAmountBFromLiquidity(\n    sqrtPriceX64A: BN,\n    sqrtPriceX64B: BN,\n    liquidity: BN,\n    roundUp: boolean,\n  ): BN {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n    if (!sqrtPriceX64A.gt(ZERO)) {\n      throw new Error(\"sqrtPriceX64A must greater than 0\");\n    }\n\n    return roundUp\n      ? MathUtil.mulDivCeil(liquidity, sqrtPriceX64B.sub(sqrtPriceX64A), Q64)\n      : MathUtil.mulDivFloor(liquidity, sqrtPriceX64B.sub(sqrtPriceX64A), Q64);\n  }\n\n  public static getLiquidityFromTokenAmountA(sqrtPriceX64A: BN, sqrtPriceX64B: BN, amountA: BN, roundUp: boolean): BN {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n\n    const numerator = amountA.mul(sqrtPriceX64A).mul(sqrtPriceX64B);\n    const denominator = sqrtPriceX64B.sub(sqrtPriceX64A);\n    const result = numerator.div(denominator);\n\n    if (roundUp) {\n      return MathUtil.mulDivRoundingUp(result, ONE, MaxU64);\n    } else {\n      return result.shrn(U64Resolution);\n    }\n  }\n\n  public static getLiquidityFromTokenAmountB(sqrtPriceX64A: BN, sqrtPriceX64B: BN, amountB: BN): BN {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n    return MathUtil.mulDivFloor(amountB, MaxU64, sqrtPriceX64B.sub(sqrtPriceX64A));\n  }\n\n  public static getLiquidityFromTokenAmounts(\n    sqrtPriceCurrentX64: BN,\n    sqrtPriceX64A: BN,\n    sqrtPriceX64B: BN,\n    amountA: BN,\n    amountB: BN,\n  ): BN {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n\n    if (sqrtPriceCurrentX64.lte(sqrtPriceX64A)) {\n      return LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceX64A, sqrtPriceX64B, amountA, false);\n    } else if (sqrtPriceCurrentX64.lt(sqrtPriceX64B)) {\n      const liquidity0 = LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceCurrentX64, sqrtPriceX64B, amountA, false);\n      const liquidity1 = LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceCurrentX64, amountB);\n      return liquidity0.lt(liquidity1) ? liquidity0 : liquidity1;\n    } else {\n      return LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceX64B, amountB);\n    }\n  }\n\n  public static getAmountsFromLiquidity(\n    sqrtPriceCurrentX64: BN,\n    sqrtPriceX64A: BN,\n    sqrtPriceX64B: BN,\n    liquidity: BN,\n    roundUp: boolean,\n  ): { amountA: BN; amountB: BN } {\n    if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n      [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n    }\n\n    if (sqrtPriceCurrentX64.lte(sqrtPriceX64A)) {\n      return {\n        amountA: LiquidityMath.getTokenAmountAFromLiquidity(sqrtPriceX64A, sqrtPriceX64B, liquidity, roundUp),\n        amountB: new BN(0),\n      };\n    } else if (sqrtPriceCurrentX64.lt(sqrtPriceX64B)) {\n      const amountA = LiquidityMath.getTokenAmountAFromLiquidity(\n        sqrtPriceCurrentX64,\n        sqrtPriceX64B,\n        liquidity,\n        roundUp,\n      );\n      const amountB = LiquidityMath.getTokenAmountBFromLiquidity(\n        sqrtPriceX64A,\n        sqrtPriceCurrentX64,\n        liquidity,\n        roundUp,\n      );\n      return { amountA, amountB };\n    } else {\n      return {\n        amountA: new BN(0),\n        amountB: LiquidityMath.getTokenAmountBFromLiquidity(sqrtPriceX64A, sqrtPriceX64B, liquidity, roundUp),\n      };\n    }\n  }\n\n  public static getAmountsFromLiquidityWithSlippage(\n    sqrtPriceCurrentX64: BN,\n    sqrtPriceX64A: BN,\n    sqrtPriceX64B: BN,\n    liquidity: BN,\n    amountMax: boolean,\n    roundUp: boolean,\n    amountSlippage: number,\n  ): { amountSlippageA: BN; amountSlippageB: BN } {\n    const { amountA, amountB } = LiquidityMath.getAmountsFromLiquidity(\n      sqrtPriceCurrentX64,\n      sqrtPriceX64A,\n      sqrtPriceX64B,\n      liquidity,\n      roundUp,\n    );\n    const coefficient = amountMax ? 1 + amountSlippage : 1 - amountSlippage;\n\n    const amount0Slippage = new BN(new Decimal(amountA.toString()).mul(coefficient).toFixed(0));\n    const amount1Slippage = new BN(new Decimal(amountB.toString()).mul(coefficient).toFixed(0));\n    return {\n      amountSlippageA: amount0Slippage,\n      amountSlippageB: amount1Slippage,\n    };\n  }\n\n  public static getAmountsOutFromLiquidity({\n    poolInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    slippage,\n    add,\n    epochInfo,\n    amountAddFee,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    tickLower: number;\n    tickUpper: number;\n    liquidity: BN;\n    slippage: number;\n    add: boolean;\n\n    epochInfo: EpochInfo;\n    amountAddFee: boolean;\n  }): ReturnTypeGetLiquidityAmountOut {\n    const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n      new Decimal(poolInfo.price),\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(tickLower);\n    const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(tickUpper);\n\n    const coefficientRe = add ? 1 + slippage : 1 - slippage;\n\n    const amounts = LiquidityMath.getAmountsFromLiquidity(sqrtPriceX64, sqrtPriceX64A, sqrtPriceX64B, liquidity, add);\n\n    const [amountA, amountB] = [\n      getTransferAmountFeeV2(amounts.amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, amountAddFee),\n      getTransferAmountFeeV2(amounts.amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, amountAddFee),\n    ];\n    const [amountSlippageA, amountSlippageB] = [\n      getTransferAmountFeeV2(\n        new BN(new Decimal(amounts.amountA.toString()).mul(coefficientRe).toFixed(0)),\n        poolInfo.mintA.extensions?.feeConfig,\n        epochInfo,\n        amountAddFee,\n      ),\n      getTransferAmountFeeV2(\n        new BN(new Decimal(amounts.amountB.toString()).mul(coefficientRe).toFixed(0)),\n        poolInfo.mintB.extensions?.feeConfig,\n        epochInfo,\n        amountAddFee,\n      ),\n    ];\n\n    return {\n      liquidity,\n      amountA,\n      amountB,\n      amountSlippageA,\n      amountSlippageB,\n      expirationTime: minExpirationTime(amountA.expirationTime, amountB.expirationTime),\n    };\n  }\n}\n\n// swap math\n\ntype SwapStep = {\n  sqrtPriceX64Next: BN;\n  amountIn: BN;\n  amountOut: BN;\n  feeAmount: BN;\n};\n\nexport interface StepComputations {\n  sqrtPriceStartX64: BN;\n  tickNext: number;\n  initialized: boolean;\n  sqrtPriceNextX64: BN;\n  amountIn: BN;\n  amountOut: BN;\n  feeAmount: BN;\n}\n\nexport abstract class SwapMath {\n  public static swapCompute(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickArrayCache: { [key: string]: TickArray },\n    tickArrayBitmap: BN[],\n    tickarrayBitmapExtension: TickArrayBitmapExtensionType,\n    zeroForOne: boolean,\n    fee: number,\n    liquidity: BN,\n    currentTick: number,\n    tickSpacing: number,\n    currentSqrtPriceX64: BN,\n    amountSpecified: BN,\n    lastSavedTickArrayStartIndex: number,\n    sqrtPriceLimitX64?: BN,\n    catchLiquidityInsufficient = false,\n  ): {\n    allTrade: boolean;\n    amountSpecifiedRemaining: BN;\n    amountCalculated: BN;\n    feeAmount: BN;\n    sqrtPriceX64: BN;\n    liquidity: BN;\n    tickCurrent: number;\n    accounts: PublicKey[];\n  } {\n    if (amountSpecified.eq(ZERO)) {\n      throw new Error(\"amountSpecified must not be 0\");\n    }\n    if (!sqrtPriceLimitX64) sqrtPriceLimitX64 = zeroForOne ? MIN_SQRT_PRICE_X64.add(ONE) : MAX_SQRT_PRICE_X64.sub(ONE);\n\n    if (zeroForOne) {\n      if (sqrtPriceLimitX64.lt(MIN_SQRT_PRICE_X64)) {\n        throw new Error(\"sqrtPriceX64 must greater than MIN_SQRT_PRICE_X64\");\n      }\n\n      if (sqrtPriceLimitX64.gte(currentSqrtPriceX64)) {\n        throw new Error(\"sqrtPriceX64 must smaller than current\");\n      }\n    } else {\n      if (sqrtPriceLimitX64.gt(MAX_SQRT_PRICE_X64)) {\n        throw new Error(\"sqrtPriceX64 must smaller than MAX_SQRT_PRICE_X64\");\n      }\n\n      if (sqrtPriceLimitX64.lte(currentSqrtPriceX64)) {\n        throw new Error(\"sqrtPriceX64 must greater than current\");\n      }\n    }\n    const baseInput = amountSpecified.gt(ZERO);\n\n    const state = {\n      amountSpecifiedRemaining: amountSpecified,\n      amountCalculated: ZERO,\n      sqrtPriceX64: currentSqrtPriceX64,\n      tick:\n        currentTick > lastSavedTickArrayStartIndex\n          ? Math.min(lastSavedTickArrayStartIndex + TickQuery.tickCount(tickSpacing) - 1, currentTick)\n          : lastSavedTickArrayStartIndex,\n      accounts: [] as PublicKey[],\n      liquidity,\n      feeAmount: new BN(0),\n    };\n    let tickAarrayStartIndex = lastSavedTickArrayStartIndex;\n    let tickArrayCurrent = tickArrayCache[lastSavedTickArrayStartIndex];\n    let loopCount = 0;\n    let t = !zeroForOne && tickArrayCurrent.startTickIndex === state.tick;\n    while (\n      !state.amountSpecifiedRemaining.eq(ZERO) &&\n      !state.sqrtPriceX64.eq(sqrtPriceLimitX64)\n      // state.tick < MAX_TICK &&\n      // state.tick > MIN_TICK\n    ) {\n      if (loopCount > 10) {\n        // throw Error('liquidity limit')\n      }\n      const step: Partial<StepComputations> = {};\n      step.sqrtPriceStartX64 = state.sqrtPriceX64;\n\n      const tickState: Tick | null = TickUtils.nextInitTick(tickArrayCurrent, state.tick, tickSpacing, zeroForOne, t);\n\n      let nextInitTick: Tick | null = tickState ? tickState : null; // TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne)\n      let tickArrayAddress: null | PublicKey = null;\n\n      if (!nextInitTick?.liquidityGross.gtn(0)) {\n        const nextInitTickArrayIndex = PoolUtils.nextInitializedTickArrayStartIndex(\n          {\n            tickCurrent: state.tick,\n            tickSpacing,\n            tickArrayBitmap,\n            exBitmapInfo: tickarrayBitmapExtension,\n          },\n          tickAarrayStartIndex,\n          zeroForOne,\n        );\n        if (!nextInitTickArrayIndex.isExist) {\n          if (catchLiquidityInsufficient) {\n            return {\n              allTrade: false,\n              amountSpecifiedRemaining: state.amountSpecifiedRemaining,\n              amountCalculated: state.amountCalculated,\n              feeAmount: state.feeAmount,\n              sqrtPriceX64: state.sqrtPriceX64,\n              liquidity: state.liquidity,\n              tickCurrent: state.tick,\n              accounts: state.accounts,\n            };\n          }\n          throw Error(\"swapCompute LiquidityInsufficient\");\n        }\n        tickAarrayStartIndex = nextInitTickArrayIndex.nextStartIndex;\n\n        const { publicKey: expectedNextTickArrayAddress } = getPdaTickArrayAddress(\n          programId,\n          poolId,\n          tickAarrayStartIndex,\n        );\n        tickArrayAddress = expectedNextTickArrayAddress;\n        tickArrayCurrent = tickArrayCache[tickAarrayStartIndex];\n\n        try {\n          nextInitTick = TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne);\n        } catch (e) {\n          throw Error(\"not found next tick info\");\n        }\n      }\n\n      step.tickNext = nextInitTick.tick;\n      step.initialized = nextInitTick.liquidityGross.gtn(0);\n      if (lastSavedTickArrayStartIndex !== tickAarrayStartIndex && tickArrayAddress) {\n        state.accounts.push(tickArrayAddress);\n        lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n      }\n      if (step.tickNext < MIN_TICK) {\n        step.tickNext = MIN_TICK;\n      } else if (step.tickNext > MAX_TICK) {\n        step.tickNext = MAX_TICK;\n      }\n\n      step.sqrtPriceNextX64 = SqrtPriceMath.getSqrtPriceX64FromTick(step.tickNext);\n      let targetPrice: BN;\n      if (\n        (zeroForOne && step.sqrtPriceNextX64.lt(sqrtPriceLimitX64)) ||\n        (!zeroForOne && step.sqrtPriceNextX64.gt(sqrtPriceLimitX64))\n      ) {\n        targetPrice = sqrtPriceLimitX64;\n      } else {\n        targetPrice = step.sqrtPriceNextX64;\n      }\n      [state.sqrtPriceX64, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.swapStepCompute(\n        state.sqrtPriceX64,\n        targetPrice,\n        state.liquidity,\n        state.amountSpecifiedRemaining,\n        fee,\n        zeroForOne,\n      );\n\n      state.feeAmount = state.feeAmount.add(step.feeAmount);\n\n      if (baseInput) {\n        state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.sub(step.amountIn.add(step.feeAmount));\n        state.amountCalculated = state.amountCalculated.sub(step.amountOut);\n      } else {\n        state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.add(step.amountOut);\n        state.amountCalculated = state.amountCalculated.add(step.amountIn.add(step.feeAmount));\n      }\n      if (state.sqrtPriceX64.eq(step.sqrtPriceNextX64)) {\n        if (step.initialized) {\n          let liquidityNet = nextInitTick.liquidityNet;\n          if (zeroForOne) liquidityNet = liquidityNet.mul(NEGATIVE_ONE);\n          state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n        }\n\n        t = step.tickNext != state.tick && !zeroForOne && tickArrayCurrent.startTickIndex === step.tickNext;\n        state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext; //\n      } else if (state.sqrtPriceX64 != step.sqrtPriceStartX64) {\n        const _T = SqrtPriceMath.getTickFromSqrtPriceX64(state.sqrtPriceX64);\n        t = _T != state.tick && !zeroForOne && tickArrayCurrent.startTickIndex === _T;\n        state.tick = _T;\n      }\n      ++loopCount;\n    }\n\n    try {\n      const { nextStartIndex: tickAarrayStartIndex, isExist } = TickQuery.nextInitializedTickArray(\n        state.tick,\n        tickSpacing,\n        zeroForOne,\n        tickArrayBitmap,\n        tickarrayBitmapExtension,\n      );\n      if (isExist && lastSavedTickArrayStartIndex !== tickAarrayStartIndex) {\n        state.accounts.push(getPdaTickArrayAddress(programId, poolId, tickAarrayStartIndex).publicKey);\n        lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n      }\n    } catch (e) {\n      /* empty */\n    }\n\n    return {\n      allTrade: true,\n      amountSpecifiedRemaining: ZERO,\n      amountCalculated: state.amountCalculated,\n      feeAmount: state.feeAmount,\n      sqrtPriceX64: state.sqrtPriceX64,\n      liquidity: state.liquidity,\n      tickCurrent: state.tick,\n      accounts: state.accounts,\n    };\n  }\n  // public static swapCompute(\n  //   programId: PublicKey,\n  //   poolId: PublicKey,\n  //   tickArrayCache: { [key: string]: TickArray },\n  //   tickArrayBitmap: BN[],\n  //   tickarrayBitmapExtension: TickArrayBitmapExtensionType,\n  //   zeroForOne: boolean,\n  //   fee: number,\n  //   liquidity: BN,\n  //   currentTick: number,\n  //   tickSpacing: number,\n  //   currentSqrtPriceX64: BN,\n  //   amountSpecified: BN,\n  //   lastSavedTickArrayStartIndex: number,\n  //   sqrtPriceLimitX64?: BN,\n  // ): {\n  //   amountCalculated: BN;\n  //   feeAmount: BN;\n  //   sqrtPriceX64: BN;\n  //   liquidity: BN;\n  //   tickCurrent: number;\n  //   accounts: PublicKey[];\n  // } {\n  //   if (amountSpecified.eq(ZERO)) {\n  //     throw new Error(\"amountSpecified must not be 0\");\n  //   }\n  //   if (!sqrtPriceLimitX64) sqrtPriceLimitX64 = zeroForOne ? MIN_SQRT_PRICE_X64.add(ONE) : MAX_SQRT_PRICE_X64.sub(ONE);\n\n  //   if (zeroForOne) {\n  //     if (sqrtPriceLimitX64.lt(MIN_SQRT_PRICE_X64)) {\n  //       throw new Error(\"sqrtPriceX64 must greater than MIN_SQRT_PRICE_X64\");\n  //     }\n\n  //     if (sqrtPriceLimitX64.gte(currentSqrtPriceX64)) {\n  //       throw new Error(\"sqrtPriceX64 must smaller than current\");\n  //     }\n  //   } else {\n  //     if (sqrtPriceLimitX64.gt(MAX_SQRT_PRICE_X64)) {\n  //       throw new Error(\"sqrtPriceX64 must smaller than MAX_SQRT_PRICE_X64\");\n  //     }\n\n  //     if (sqrtPriceLimitX64.lte(currentSqrtPriceX64)) {\n  //       throw new Error(\"sqrtPriceX64 must greater than current\");\n  //     }\n  //   }\n  //   const baseInput = amountSpecified.gt(ZERO);\n\n  //   const state = {\n  //     amountSpecifiedRemaining: amountSpecified,\n  //     amountCalculated: ZERO,\n  //     sqrtPriceX64: currentSqrtPriceX64,\n  //     tick:\n  //       currentTick > lastSavedTickArrayStartIndex\n  //         ? Math.min(lastSavedTickArrayStartIndex + TickQuery.tickCount(tickSpacing) - 1, currentTick)\n  //         : lastSavedTickArrayStartIndex,\n  //     accounts: [] as PublicKey[],\n  //     liquidity,\n  //     feeAmount: new BN(0),\n  //   };\n  //   let tickAarrayStartIndex = lastSavedTickArrayStartIndex;\n  //   let tickArrayCurrent = tickArrayCache[lastSavedTickArrayStartIndex];\n  //   let loopCount = 0;\n  //   while (\n  //     !state.amountSpecifiedRemaining.eq(ZERO) &&\n  //     !state.sqrtPriceX64.eq(sqrtPriceLimitX64)\n  //     // state.tick < MAX_TICK &&\n  //     // state.tick > MIN_TICK\n  //   ) {\n  //     if (loopCount > 10) {\n  //       throw Error(\"liquidity limit\");\n  //     }\n  //     const step: Partial<StepComputations> = {};\n  //     step.sqrtPriceStartX64 = state.sqrtPriceX64;\n\n  //     const tickState: Tick | null = TickUtils.nextInitTick(tickArrayCurrent, state.tick, tickSpacing, zeroForOne);\n\n  //     let nextInitTick: Tick | null = tickState ? tickState : null; // TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne)\n  //     let tickArrayAddress: PublicKey | null = null;\n\n  //     if (!nextInitTick?.liquidityGross.gtn(0)) {\n  //       const nextInitTickArrayIndex = PoolUtils.nextInitializedTickArrayStartIndex(\n  //         {\n  //           tickCurrent: state.tick,\n  //           tickSpacing,\n  //           tickArrayBitmap,\n  //           exBitmapInfo: tickarrayBitmapExtension,\n  //         },\n  //         tickAarrayStartIndex,\n  //         zeroForOne,\n  //       );\n  //       if (!nextInitTickArrayIndex.isExist) {\n  //         throw Error(\"swapCompute LiquidityInsufficient\");\n  //       }\n  //       tickAarrayStartIndex = nextInitTickArrayIndex.nextStartIndex;\n\n  //       const { publicKey: expectedNextTickArrayAddress } = getPdaTickArrayAddress(\n  //         programId,\n  //         poolId,\n  //         tickAarrayStartIndex,\n  //       );\n  //       tickArrayAddress = expectedNextTickArrayAddress;\n  //       tickArrayCurrent = tickArrayCache[tickAarrayStartIndex];\n\n  //       nextInitTick = TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne);\n  //     }\n\n  //     step.tickNext = nextInitTick.tick;\n  //     step.initialized = nextInitTick.liquidityGross.gtn(0);\n  //     if (lastSavedTickArrayStartIndex !== tickAarrayStartIndex && tickArrayAddress) {\n  //       state.accounts.push(tickArrayAddress);\n  //       lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n  //     }\n  //     if (step.tickNext < MIN_TICK) {\n  //       step.tickNext = MIN_TICK;\n  //     } else if (step.tickNext > MAX_TICK) {\n  //       step.tickNext = MAX_TICK;\n  //     }\n\n  //     step.sqrtPriceNextX64 = SqrtPriceMath.getSqrtPriceX64FromTick(step.tickNext);\n  //     let targetPrice: BN;\n  //     if (\n  //       (zeroForOne && step.sqrtPriceNextX64.lt(sqrtPriceLimitX64)) ||\n  //       (!zeroForOne && step.sqrtPriceNextX64.gt(sqrtPriceLimitX64))\n  //     ) {\n  //       targetPrice = sqrtPriceLimitX64;\n  //     } else {\n  //       targetPrice = step.sqrtPriceNextX64;\n  //     }\n  //     [state.sqrtPriceX64, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.swapStepCompute(\n  //       state.sqrtPriceX64,\n  //       targetPrice,\n  //       state.liquidity,\n  //       state.amountSpecifiedRemaining,\n  //       fee,\n  //     );\n\n  //     state.feeAmount = state.feeAmount.add(step.feeAmount);\n\n  //     if (baseInput) {\n  //       state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.sub(step.amountIn.add(step.feeAmount));\n  //       state.amountCalculated = state.amountCalculated.sub(step.amountOut);\n  //     } else {\n  //       state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.add(step.amountOut);\n  //       state.amountCalculated = state.amountCalculated.add(step.amountIn.add(step.feeAmount));\n  //     }\n  //     if (state.sqrtPriceX64.eq(step.sqrtPriceNextX64)) {\n  //       if (step.initialized) {\n  //         let liquidityNet = nextInitTick.liquidityNet;\n  //         if (zeroForOne) liquidityNet = liquidityNet.mul(NEGATIVE_ONE);\n  //         state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n  //       }\n  //       state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n  //     } else if (state.sqrtPriceX64 != step.sqrtPriceStartX64) {\n  //       state.tick = SqrtPriceMath.getTickFromSqrtPriceX64(state.sqrtPriceX64);\n  //     }\n  //     ++loopCount;\n  //   }\n\n  //   // try {\n  //   //   console.log('state.tick', state.tick)\n  //   //   const { nextStartIndex: tickAarrayStartIndex } = TickQuery.nextInitializedTickArray(\n  //   //     state.tick,\n  //   //     tickSpacing,\n  //   //     zeroForOne,\n  //   //     tickArrayBitmap,\n  //   //     tickarrayBitmapExtension,\n  //   //   );\n  //   //   if (\n  //   //     lastSavedTickArrayStartIndex !== tickAarrayStartIndex\n  //   //   ) {\n  //   //     state.accounts.push(getPdaTickArrayAddress(\n  //   //       programId,\n  //   //       poolId,\n  //   //       tickAarrayStartIndex,\n  //   //     ).publicKey)\n  //   //     lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n  //   //   }\n  //   // } catch (e) { /* empty */ }\n\n  //   return {\n  //     amountCalculated: state.amountCalculated,\n  //     feeAmount: state.feeAmount,\n  //     sqrtPriceX64: state.sqrtPriceX64,\n  //     liquidity: state.liquidity,\n  //     tickCurrent: state.tick,\n  //     accounts: state.accounts,\n  //   };\n  // }\n\n  private static swapStepCompute(\n    sqrtPriceX64Current: BN,\n    sqrtPriceX64Target: BN,\n    liquidity: BN,\n    amountRemaining: BN,\n    feeRate: Fee,\n    zeroForOne: boolean,\n  ): [BN, BN, BN, BN] {\n    const swapStep: SwapStep = {\n      sqrtPriceX64Next: new BN(0),\n      amountIn: new BN(0),\n      amountOut: new BN(0),\n      feeAmount: new BN(0),\n    };\n\n    const baseInput = amountRemaining.gte(ZERO);\n\n    if (baseInput) {\n      const amountRemainingSubtractFee = MathUtil.mulDivFloor(\n        amountRemaining,\n        FEE_RATE_DENOMINATOR.sub(new BN(feeRate.toString())),\n        FEE_RATE_DENOMINATOR,\n      );\n      swapStep.amountIn = zeroForOne\n        ? LiquidityMath.getTokenAmountAFromLiquidity(sqrtPriceX64Target, sqrtPriceX64Current, liquidity, true)\n        : LiquidityMath.getTokenAmountBFromLiquidity(sqrtPriceX64Current, sqrtPriceX64Target, liquidity, true);\n      if (amountRemainingSubtractFee.gte(swapStep.amountIn)) {\n        swapStep.sqrtPriceX64Next = sqrtPriceX64Target;\n      } else {\n        swapStep.sqrtPriceX64Next = SqrtPriceMath.getNextSqrtPriceX64FromInput(\n          sqrtPriceX64Current,\n          liquidity,\n          amountRemainingSubtractFee,\n          zeroForOne,\n        );\n      }\n    } else {\n      swapStep.amountOut = zeroForOne\n        ? LiquidityMath.getTokenAmountBFromLiquidity(sqrtPriceX64Target, sqrtPriceX64Current, liquidity, false)\n        : LiquidityMath.getTokenAmountAFromLiquidity(sqrtPriceX64Current, sqrtPriceX64Target, liquidity, false);\n      if (amountRemaining.mul(NEGATIVE_ONE).gte(swapStep.amountOut)) {\n        swapStep.sqrtPriceX64Next = sqrtPriceX64Target;\n      } else {\n        swapStep.sqrtPriceX64Next = SqrtPriceMath.getNextSqrtPriceX64FromOutput(\n          sqrtPriceX64Current,\n          liquidity,\n          amountRemaining.mul(NEGATIVE_ONE),\n          zeroForOne,\n        );\n      }\n    }\n\n    const reachTargetPrice = sqrtPriceX64Target.eq(swapStep.sqrtPriceX64Next);\n\n    if (zeroForOne) {\n      if (!(reachTargetPrice && baseInput)) {\n        swapStep.amountIn = LiquidityMath.getTokenAmountAFromLiquidity(\n          swapStep.sqrtPriceX64Next,\n          sqrtPriceX64Current,\n          liquidity,\n          true,\n        );\n      }\n\n      if (!(reachTargetPrice && !baseInput)) {\n        swapStep.amountOut = LiquidityMath.getTokenAmountBFromLiquidity(\n          swapStep.sqrtPriceX64Next,\n          sqrtPriceX64Current,\n          liquidity,\n          false,\n        );\n      }\n    } else {\n      swapStep.amountIn =\n        reachTargetPrice && baseInput\n          ? swapStep.amountIn\n          : LiquidityMath.getTokenAmountBFromLiquidity(sqrtPriceX64Current, swapStep.sqrtPriceX64Next, liquidity, true);\n      swapStep.amountOut =\n        reachTargetPrice && !baseInput\n          ? swapStep.amountOut\n          : LiquidityMath.getTokenAmountAFromLiquidity(\n            sqrtPriceX64Current,\n            swapStep.sqrtPriceX64Next,\n            liquidity,\n            false,\n          );\n    }\n\n    if (!baseInput && swapStep.amountOut.gt(amountRemaining.mul(NEGATIVE_ONE))) {\n      swapStep.amountOut = amountRemaining.mul(NEGATIVE_ONE);\n    }\n    if (baseInput && !swapStep.sqrtPriceX64Next.eq(sqrtPriceX64Target)) {\n      swapStep.feeAmount = amountRemaining.sub(swapStep.amountIn);\n    } else {\n      swapStep.feeAmount = MathUtil.mulDivCeil(\n        swapStep.amountIn,\n        new BN(feeRate),\n        FEE_RATE_DENOMINATOR.sub(new BN(feeRate)),\n      );\n    }\n    return [swapStep.sqrtPriceX64Next, swapStep.amountIn, swapStep.amountOut, swapStep.feeAmount];\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { findProgramAddress, METADATA_PROGRAM_ID } from \"../../../common\";\n\nimport { i32ToBytes, u16ToBytes } from \"./util\";\n\nexport const AMM_CONFIG_SEED = Buffer.from(\"amm_config\", \"utf8\");\nexport const POOL_SEED = Buffer.from(\"pool\", \"utf8\");\nexport const POOL_VAULT_SEED = Buffer.from(\"pool_vault\", \"utf8\");\nexport const POOL_REWARD_VAULT_SEED = Buffer.from(\"pool_reward_vault\", \"utf8\");\nexport const POSITION_SEED = Buffer.from(\"position\", \"utf8\");\nexport const TICK_ARRAY_SEED = Buffer.from(\"tick_array\", \"utf8\");\nexport const OPERATION_SEED = Buffer.from(\"operation\", \"utf8\");\nexport const POOL_TICK_ARRAY_BITMAP_SEED = Buffer.from(\"pool_tick_array_bitmap_extension\", \"utf8\");\nexport const OBSERVATION_SEED = Buffer.from(\"observation\", \"utf8\");\n\nexport function getPdaAmmConfigId(\n  programId: PublicKey,\n  index: number,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([AMM_CONFIG_SEED, u16ToBytes(index)], programId);\n}\n\nexport function getPdaPoolId(\n  programId: PublicKey,\n  ammConfigId: PublicKey,\n  mintA: PublicKey,\n  mintB: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_SEED, ammConfigId.toBuffer(), mintA.toBuffer(), mintB.toBuffer()], programId);\n}\n\nexport function getPdaPoolVaultId(\n  programId: PublicKey,\n  poolId: PublicKey,\n  vaultMint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_VAULT_SEED, poolId.toBuffer(), vaultMint.toBuffer()], programId);\n}\n\nexport function getPdaPoolRewardVaulId(\n  programId: PublicKey,\n  poolId: PublicKey,\n  rewardMint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_REWARD_VAULT_SEED, poolId.toBuffer(), rewardMint.toBuffer()], programId);\n}\n\nexport function getPdaTickArrayAddress(\n  programId: PublicKey,\n  poolId: PublicKey,\n  startIndex: number,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([TICK_ARRAY_SEED, poolId.toBuffer(), i32ToBytes(startIndex)], programId);\n}\n\nexport function getPdaProtocolPositionAddress(\n  programId: PublicKey,\n  poolId: PublicKey,\n  tickLower: number,\n  tickUpper: number,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress(\n    [POSITION_SEED, poolId.toBuffer(), i32ToBytes(tickLower), i32ToBytes(tickUpper)],\n    programId,\n  );\n}\n\nexport function getPdaPersonalPositionAddress(\n  programId: PublicKey,\n  nftMint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POSITION_SEED, nftMint.toBuffer()], programId);\n}\n\nexport function getPdaMetadataKey(mint: PublicKey): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress(\n    [Buffer.from(\"metadata\", \"utf8\"), METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n    METADATA_PROGRAM_ID,\n  );\n}\n\nexport function getPdaOperationAccount(programId: PublicKey): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([OPERATION_SEED], programId);\n}\n\nexport function getPdaExBitmapAccount(\n  programId: PublicKey,\n  poolId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_TICK_ARRAY_BITMAP_SEED, poolId.toBuffer()], programId);\n}\n\nexport function getPdaObservationAccount(\n  programId: PublicKey,\n  poolId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([OBSERVATION_SEED, poolId.toBuffer()], programId);\n}\n\nexport const POOL_LOCK_ID_SEED = Buffer.from(\"locked_position\", \"utf8\");\nexport function getPdaLockPositionId(\n  programId: PublicKey,\n  positionId: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_LOCK_ID_SEED, positionId.toBuffer()], programId);\n}\n\nexport function getPdaLockClPositionIdV2(\n  programId: PublicKey,\n  lockNftMint: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([POOL_LOCK_ID_SEED, lockNftMint.toBuffer()], programId);\n}\n\nexport const SUPPORT_MINT_SEED = Buffer.from(\"support_mint\", \"utf8\");\nexport function getPdaMintExAccount(\n  programId: PublicKey,\n  mintAddress: PublicKey,\n): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([SUPPORT_MINT_SEED, mintAddress.toBuffer()], programId);\n}\n","import { Connection, EpochInfo, PublicKey } from \"@solana/web3.js\";\nimport { TOKEN_2022_PROGRAM_ID } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport {\n  ClmmPoolInfo,\n  ClmmPoolRewardInfo,\n  ClmmPoolRewardLayoutInfo,\n  ComputeClmmPoolInfo,\n  ReturnTypeComputeAmountOut,\n  ReturnTypeComputeAmountOutBaseOut,\n  ReturnTypeComputeAmountOutFormat,\n  ReturnTypeFetchExBitmaps,\n  ReturnTypeFetchMultiplePoolTickArrays,\n  ReturnTypeGetLiquidityAmountOut,\n  SDKParsedConcentratedInfo,\n  TickArrayBitmapExtensionType,\n} from \"../type\";\n\nimport { ApiV3PoolInfoConcentratedItem, ApiV3Token } from \"@/api/type\";\n\nimport Decimal from \"decimal.js\";\nimport {\n  getMultipleAccountsInfo,\n  getMultipleAccountsInfoWithCustomFlags,\n  getTransferAmountFeeV2,\n  minExpirationTime,\n  solToWSol,\n} from \"@/common\";\nimport { Percent, Price, Token, TokenAmount } from \"@/module\";\nimport { TokenAccountRaw } from \"@/raydium/account/types\";\nimport { PoolInfoLayout, PositionInfoLayout, TickArrayBitmapExtensionLayout, TickArrayLayout } from \"../layout\";\nimport { MAX_SQRT_PRICE_X64, MAX_TICK, MIN_SQRT_PRICE_X64, MIN_TICK, NEGATIVE_ONE, Q64, ZERO } from \"./constants\";\nimport { LiquidityMath, MathUtil, SqrtPriceMath, SwapMath } from \"./math\";\nimport { getPdaExBitmapAccount, getPdaPersonalPositionAddress, getPdaTickArrayAddress } from \"./pda\";\nimport { PositionUtils } from \"./position\";\nimport { TICK_ARRAY_BITMAP_SIZE, Tick, TickArray, TickUtils } from \"./tick\";\nimport { TickArrayBitmap, TickArrayBitmapExtensionUtils } from \"./tickarrayBitmap\";\nimport { TickQuery } from \"./tickQuery\";\n\nexport class PoolUtils {\n  public static getOutputAmountAndRemainAccounts(\n    poolInfo: ComputeClmmPoolInfo,\n    tickArrayCache: { [key: string]: TickArray },\n    inputTokenMint: PublicKey,\n    inputAmount: BN,\n    sqrtPriceLimitX64?: BN,\n    catchLiquidityInsufficient = false,\n  ): {\n    allTrade: boolean;\n    expectedAmountOut: BN;\n    remainingAccounts: PublicKey[];\n    executionPrice: BN;\n    feeAmount: BN;\n  } {\n    const zeroForOne = inputTokenMint.toBase58() === poolInfo.mintA.address;\n\n    const allNeededAccounts: PublicKey[] = [];\n    const {\n      isExist,\n      startIndex: firstTickArrayStartIndex,\n      nextAccountMeta,\n    } = this.getFirstInitializedTickArray(poolInfo, zeroForOne);\n    if (!isExist || firstTickArrayStartIndex === undefined || !nextAccountMeta) throw new Error(\"Invalid tick array\");\n\n    // try {\n    //   const preTick = this.preInitializedTickArrayStartIndex(poolInfo, !zeroForOne)\n    //   if (preTick.isExist) {\n    //     const { publicKey: address } = getPdaTickArrayAddress(\n    //       poolInfo.programId,\n    //       poolInfo.id,\n    //       preTick.nextStartIndex\n    //     );\n    //     allNeededAccounts.push(address)\n    //   }\n    // } catch (e) { /* empty */ }\n\n    allNeededAccounts.push(nextAccountMeta);\n    const {\n      allTrade,\n      amountCalculated: outputAmount,\n      accounts: reaminAccounts,\n      sqrtPriceX64: executionPrice,\n      feeAmount,\n    } = SwapMath.swapCompute(\n      poolInfo.programId,\n      poolInfo.id,\n      tickArrayCache,\n      poolInfo.tickArrayBitmap,\n      poolInfo.exBitmapInfo,\n      zeroForOne,\n      poolInfo.ammConfig.tradeFeeRate,\n      poolInfo.liquidity,\n      poolInfo.tickCurrent,\n      poolInfo.tickSpacing,\n      poolInfo.sqrtPriceX64,\n      inputAmount,\n      firstTickArrayStartIndex,\n      sqrtPriceLimitX64,\n      catchLiquidityInsufficient,\n    );\n    allNeededAccounts.push(...reaminAccounts);\n    return {\n      allTrade,\n      expectedAmountOut: outputAmount.mul(NEGATIVE_ONE),\n      remainingAccounts: allNeededAccounts,\n      executionPrice,\n      feeAmount,\n    };\n  }\n\n  public static getInputAmountAndRemainAccounts(\n    poolInfo: ComputeClmmPoolInfo,\n    tickArrayCache: { [key: string]: TickArray },\n    outputTokenMint: PublicKey,\n    outputAmount: BN,\n    sqrtPriceLimitX64?: BN,\n  ): { expectedAmountIn: BN; remainingAccounts: PublicKey[]; executionPrice: BN; feeAmount: BN } {\n    const zeroForOne = outputTokenMint.toBase58() === poolInfo.mintB.address;\n\n    const allNeededAccounts: PublicKey[] = [];\n    const {\n      isExist,\n      startIndex: firstTickArrayStartIndex,\n      nextAccountMeta,\n    } = this.getFirstInitializedTickArray(poolInfo, zeroForOne);\n    if (!isExist || firstTickArrayStartIndex === undefined || !nextAccountMeta) throw new Error(\"Invalid tick array\");\n\n    try {\n      const preTick = this.preInitializedTickArrayStartIndex(poolInfo, zeroForOne);\n      if (preTick.isExist) {\n        const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, preTick.nextStartIndex);\n        allNeededAccounts.push(address);\n      }\n    } catch (e) {\n      /* empty */\n    }\n\n    allNeededAccounts.push(nextAccountMeta);\n    const {\n      amountCalculated: inputAmount,\n      accounts: reaminAccounts,\n      sqrtPriceX64: executionPrice,\n      feeAmount,\n    } = SwapMath.swapCompute(\n      poolInfo.programId,\n      poolInfo.id,\n      tickArrayCache,\n      poolInfo.tickArrayBitmap,\n      poolInfo.exBitmapInfo,\n      zeroForOne,\n      poolInfo.ammConfig.tradeFeeRate,\n      poolInfo.liquidity,\n      poolInfo.tickCurrent,\n      poolInfo.tickSpacing,\n      poolInfo.sqrtPriceX64,\n      outputAmount.mul(NEGATIVE_ONE),\n      firstTickArrayStartIndex,\n      sqrtPriceLimitX64,\n    );\n    allNeededAccounts.push(...reaminAccounts);\n    return { expectedAmountIn: inputAmount, remainingAccounts: allNeededAccounts, executionPrice, feeAmount };\n  }\n\n  public static getFirstInitializedTickArray(\n    poolInfo: ComputeClmmPoolInfo,\n    zeroForOne: boolean,\n  ):\n    | { isExist: true; startIndex: number; nextAccountMeta: PublicKey }\n    | { isExist: false; startIndex: undefined; nextAccountMeta: undefined } {\n    const { isInitialized, startIndex } = PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.tickSpacing, [\n      poolInfo.tickCurrent,\n    ])\n      ? TickArrayBitmapExtensionUtils.checkTickArrayIsInit(\n        TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing),\n        poolInfo.tickSpacing,\n        poolInfo.exBitmapInfo,\n      )\n      : TickUtils.checkTickArrayIsInitialized(\n        TickUtils.mergeTickArrayBitmap(poolInfo.tickArrayBitmap),\n        poolInfo.tickCurrent,\n        poolInfo.tickSpacing,\n      );\n\n    if (isInitialized) {\n      const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, startIndex);\n      return {\n        isExist: true,\n        startIndex,\n        nextAccountMeta: address,\n      };\n    }\n    const { isExist, nextStartIndex } = this.nextInitializedTickArrayStartIndex(\n      poolInfo,\n      TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing),\n      zeroForOne,\n    );\n    if (isExist) {\n      const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, nextStartIndex);\n      return {\n        isExist: true,\n        startIndex: nextStartIndex,\n        nextAccountMeta: address,\n      };\n    }\n    return { isExist: false, nextAccountMeta: undefined, startIndex: undefined };\n  }\n\n  public static preInitializedTickArrayStartIndex(\n    poolInfo: ComputeClmmPoolInfo,\n    zeroForOne: boolean,\n  ): { isExist: boolean; nextStartIndex: number } {\n    const currentOffset = Math.floor(poolInfo.tickCurrent / TickQuery.tickCount(poolInfo.tickSpacing));\n\n    const result: number[] = !zeroForOne\n      ? TickUtils.searchLowBitFromStart(\n        poolInfo.tickArrayBitmap,\n        poolInfo.exBitmapInfo,\n        currentOffset - 1,\n        1,\n        poolInfo.tickSpacing,\n      )\n      : TickUtils.searchHightBitFromStart(\n        poolInfo.tickArrayBitmap,\n        poolInfo.exBitmapInfo,\n        currentOffset + 1,\n        1,\n        poolInfo.tickSpacing,\n      );\n\n    return result.length > 0 ? { isExist: true, nextStartIndex: result[0] } : { isExist: false, nextStartIndex: 0 };\n  }\n\n  public static nextInitializedTickArrayStartIndex(\n    poolInfo:\n      | {\n        tickCurrent: number;\n        tickSpacing: number;\n        tickArrayBitmap: BN[];\n        exBitmapInfo: TickArrayBitmapExtensionType;\n      }\n      | ClmmPoolInfo,\n    lastTickArrayStartIndex: number,\n    zeroForOne: boolean,\n  ): { isExist: boolean; nextStartIndex: number } {\n    lastTickArrayStartIndex = TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing);\n\n    // eslint-disable-next-line no-constant-condition\n    while (true) {\n      const { isInit: startIsInit, tickIndex: startIndex } = TickArrayBitmap.nextInitializedTickArrayStartIndex(\n        TickUtils.mergeTickArrayBitmap(poolInfo.tickArrayBitmap),\n        lastTickArrayStartIndex,\n        poolInfo.tickSpacing,\n        zeroForOne,\n      );\n      if (startIsInit) {\n        return { isExist: true, nextStartIndex: startIndex };\n      }\n      lastTickArrayStartIndex = startIndex;\n\n      const { isInit, tickIndex } = TickArrayBitmapExtensionUtils.nextInitializedTickArrayFromOneBitmap(\n        lastTickArrayStartIndex,\n        poolInfo.tickSpacing,\n        zeroForOne,\n        poolInfo.exBitmapInfo,\n      );\n      if (isInit) return { isExist: true, nextStartIndex: tickIndex };\n\n      lastTickArrayStartIndex = tickIndex;\n\n      if (lastTickArrayStartIndex < MIN_TICK || lastTickArrayStartIndex > MAX_TICK)\n        return { isExist: false, nextStartIndex: 0 };\n    }\n\n    // const tickArrayBitmap = TickUtils.mergeTickArrayBitmap(\n    //   poolInfo.tickArrayBitmap\n    // );\n    // const currentOffset = TickUtils.getTickArrayOffsetInBitmapByTick(\n    //   poolInfo.tickCurrent,\n    //   poolInfo.tickSpacing\n    // );\n    // const result: number[] = zeroForOne ? TickUtils.searchLowBitFromStart(\n    //   tickArrayBitmap,\n    //   currentOffset - 1,\n    //   0,\n    //   1,\n    //   poolInfo.tickSpacing\n    // ) : TickUtils.searchHightBitFromStart(\n    //   tickArrayBitmap,\n    //   currentOffset,\n    //   1024,\n    //   1,\n    //   poolInfo.tickSpacing\n    // );\n\n    // return result.length > 0 ? { isExist: true, nextStartIndex: result[0] } : { isExist: false, nextStartIndex: 0 }\n  }\n\n  public static async updatePoolRewardInfos({\n    connection,\n    apiPoolInfo,\n    chainTime,\n    poolLiquidity,\n    rewardInfos,\n  }: {\n    connection: Connection;\n    apiPoolInfo: ApiV3PoolInfoConcentratedItem;\n    chainTime: number;\n    poolLiquidity: BN;\n    rewardInfos: ClmmPoolRewardLayoutInfo[];\n  }): Promise<ClmmPoolRewardInfo[]> {\n    const nRewardInfo: ClmmPoolRewardInfo[] = [];\n    for (let i = 0; i < rewardInfos.length; i++) {\n      const _itemReward = rewardInfos[i];\n      const apiRewardProgram =\n        apiPoolInfo.rewardDefaultInfos[i]?.mint.programId ??\n        (await connection.getAccountInfo(_itemReward.tokenMint))?.owner;\n      if (apiRewardProgram === undefined) throw Error(\"get new reward mint info error\");\n\n      const itemReward: ClmmPoolRewardInfo = {\n        ..._itemReward,\n        perSecond: MathUtil.x64ToDecimal(_itemReward.emissionsPerSecondX64),\n        remainingRewards: undefined,\n        tokenProgramId: new PublicKey(apiRewardProgram),\n      };\n\n      if (itemReward.tokenMint.equals(PublicKey.default)) continue;\n      if (chainTime <= itemReward.openTime.toNumber() || poolLiquidity.eq(ZERO)) {\n        nRewardInfo.push(itemReward);\n        continue;\n      }\n\n      const latestUpdateTime = new BN(Math.min(itemReward.endTime.toNumber(), chainTime));\n      const timeDelta = latestUpdateTime.sub(itemReward.lastUpdateTime);\n      const rewardGrowthDeltaX64 = MathUtil.mulDivFloor(timeDelta, itemReward.emissionsPerSecondX64, poolLiquidity);\n      const rewardGrowthGlobalX64 = itemReward.rewardGrowthGlobalX64.add(rewardGrowthDeltaX64);\n      const rewardEmissionedDelta = MathUtil.mulDivFloor(timeDelta, itemReward.emissionsPerSecondX64, Q64);\n      const rewardTotalEmissioned = itemReward.rewardTotalEmissioned.add(rewardEmissionedDelta);\n      nRewardInfo.push({\n        ...itemReward,\n        rewardGrowthGlobalX64,\n        rewardTotalEmissioned,\n        lastUpdateTime: latestUpdateTime,\n      });\n    }\n    return nRewardInfo;\n  }\n\n  public static isOverflowDefaultTickarrayBitmap(tickSpacing: number, tickarrayStartIndexs: number[]): boolean {\n    const { maxTickBoundary, minTickBoundary } = this.tickRange(tickSpacing);\n\n    for (const tickIndex of tickarrayStartIndexs) {\n      const tickarrayStartIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n\n      if (tickarrayStartIndex >= maxTickBoundary || tickarrayStartIndex < minTickBoundary) {\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  public static tickRange(tickSpacing: number): {\n    maxTickBoundary: number;\n    minTickBoundary: number;\n  } {\n    let maxTickBoundary = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n    let minTickBoundary = -maxTickBoundary;\n\n    if (maxTickBoundary > MAX_TICK) {\n      maxTickBoundary = TickQuery.getArrayStartIndex(MAX_TICK, tickSpacing) + TickQuery.tickCount(tickSpacing);\n    }\n    if (minTickBoundary < MIN_TICK) {\n      minTickBoundary = TickQuery.getArrayStartIndex(MIN_TICK, tickSpacing);\n    }\n    return { maxTickBoundary, minTickBoundary };\n  }\n\n  public static get_tick_array_offset(tickarrayStartIndex: number, tickSpacing: number): number {\n    if (!TickQuery.checkIsValidStartIndex(tickarrayStartIndex, tickSpacing)) {\n      throw new Error(\"No enough initialized tickArray\");\n    }\n\n    return (tickarrayStartIndex / TickQuery.tickCount(tickSpacing)) * TICK_ARRAY_BITMAP_SIZE;\n  }\n\n  static async fetchExBitmaps({\n    connection,\n    exBitmapAddress,\n    batchRequest,\n  }: {\n    connection: Connection;\n    exBitmapAddress: PublicKey[];\n    batchRequest: boolean;\n  }): Promise<ReturnTypeFetchExBitmaps> {\n    const fetchedBitmapAccount = await getMultipleAccountsInfoWithCustomFlags(\n      connection,\n      exBitmapAddress.map((i) => ({ pubkey: i })),\n      { batchRequest },\n    );\n\n    const returnTypeFetchExBitmaps: ReturnTypeFetchExBitmaps = {};\n    for (const item of fetchedBitmapAccount) {\n      if (item.accountInfo === null) continue;\n\n      returnTypeFetchExBitmaps[item.pubkey.toString()] = TickArrayBitmapExtensionLayout.decode(item.accountInfo.data);\n    }\n    return returnTypeFetchExBitmaps;\n  }\n\n  static async fetchMultiplePoolTickArrays({\n    connection,\n    poolKeys,\n    batchRequest,\n  }: {\n    connection: Connection;\n    poolKeys: Omit<ComputeClmmPoolInfo, \"ammConfig\">[];\n    batchRequest?: boolean;\n  }): Promise<ReturnTypeFetchMultiplePoolTickArrays> {\n    const tickArraysToPoolId: { [key: string]: PublicKey } = {};\n    const tickArrays: { pubkey: PublicKey }[] = [];\n    for (const itemPoolInfo of poolKeys) {\n      const currentTickArrayStartIndex = TickUtils.getTickArrayStartIndexByTick(\n        itemPoolInfo.tickCurrent,\n        itemPoolInfo.tickSpacing,\n      );\n      const startIndexArray = TickUtils.getInitializedTickArrayInRange(\n        itemPoolInfo.tickArrayBitmap,\n        itemPoolInfo.exBitmapInfo,\n        itemPoolInfo.tickSpacing,\n        currentTickArrayStartIndex,\n        7,\n      );\n      for (const itemIndex of startIndexArray) {\n        const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(\n          itemPoolInfo.programId,\n          itemPoolInfo.id,\n          itemIndex,\n        );\n        tickArrays.push({ pubkey: tickArrayAddress });\n        tickArraysToPoolId[tickArrayAddress.toString()] = itemPoolInfo.id;\n      }\n    }\n\n    const fetchedTickArrays = await getMultipleAccountsInfoWithCustomFlags(connection, tickArrays, { batchRequest });\n\n    const tickArrayCache: ReturnTypeFetchMultiplePoolTickArrays = {};\n\n    for (const itemAccountInfo of fetchedTickArrays) {\n      if (!itemAccountInfo.accountInfo) continue;\n      const poolId = tickArraysToPoolId[itemAccountInfo.pubkey.toString()];\n      if (!poolId) continue;\n      if (tickArrayCache[poolId.toString()] === undefined) tickArrayCache[poolId.toString()] = {};\n\n      const accountLayoutData = TickArrayLayout.decode(itemAccountInfo.accountInfo.data);\n\n      tickArrayCache[poolId.toString()][accountLayoutData.startTickIndex] = {\n        ...accountLayoutData,\n        address: itemAccountInfo.pubkey,\n      };\n    }\n    return tickArrayCache;\n  }\n\n  // deprecated, new api doesn't need\n  static async fetchPoolsAccountPosition({\n    pools,\n    connection,\n    ownerInfo,\n    batchRequest = false,\n    updateOwnerRewardAndFee = true,\n  }: {\n    pools: SDKParsedConcentratedInfo[];\n    connection: Connection;\n    ownerInfo: { wallet: PublicKey; tokenAccounts: TokenAccountRaw[] };\n    batchRequest?: boolean;\n    updateOwnerRewardAndFee?: boolean;\n  }): Promise<SDKParsedConcentratedInfo[]> {\n    const programIds: PublicKey[] = [];\n\n    for (let index = 0; index < pools.length; index++) {\n      const accountInfo = pools[index];\n\n      if (accountInfo === null) continue;\n\n      if (!programIds.find((i) => i.equals(accountInfo.state.programId))) programIds.push(accountInfo.state.programId);\n    }\n\n    if (ownerInfo) {\n      const allMint = ownerInfo.tokenAccounts.map((i) => i.accountInfo.mint);\n      const allPositionKey: PublicKey[] = [];\n      for (const itemMint of allMint) {\n        for (const itemProgramId of programIds) {\n          allPositionKey.push(getPdaPersonalPositionAddress(itemProgramId, itemMint).publicKey);\n        }\n      }\n      const positionAccountInfos = await getMultipleAccountsInfo(connection, allPositionKey, { batchRequest });\n      const keyToTickArrayAddress: { [key: string]: PublicKey } = {};\n      for (const itemAccountInfo of positionAccountInfos) {\n        if (itemAccountInfo === null) continue;\n        // TODO: add check\n\n        const position = PositionInfoLayout.decode(itemAccountInfo.data);\n        const itemPoolId = position.poolId.toString();\n        const poolInfoA = pools.find((pool) => pool.state.id.toBase58() === itemPoolId);\n        if (poolInfoA === undefined) continue;\n\n        const poolInfo = poolInfoA.state;\n\n        const priceLower = TickUtils._getTickPriceLegacy({\n          poolInfo,\n          tick: position.tickLower,\n          baseIn: true,\n        });\n        const priceUpper = TickUtils._getTickPriceLegacy({\n          poolInfo,\n          tick: position.tickUpper,\n          baseIn: true,\n        });\n        const { amountA, amountB } = LiquidityMath.getAmountsFromLiquidity(\n          poolInfo.sqrtPriceX64,\n          priceLower.tickSqrtPriceX64,\n          priceUpper.tickSqrtPriceX64,\n          position.liquidity,\n          false,\n        );\n\n        const leverage = 1 / (1 - Math.sqrt(Math.sqrt(priceLower.price.div(priceUpper.price).toNumber())));\n\n        poolInfoA.positionAccount = [\n          ...(poolInfoA.positionAccount ?? []),\n          {\n            poolId: position.poolId,\n            nftMint: position.nftMint,\n\n            priceLower: priceLower.price,\n            priceUpper: priceUpper.price,\n            amountA,\n            amountB,\n            tickLower: position.tickLower,\n            tickUpper: position.tickUpper,\n            liquidity: position.liquidity,\n            feeGrowthInsideLastX64A: position.feeGrowthInsideLastX64A,\n            feeGrowthInsideLastX64B: position.feeGrowthInsideLastX64B,\n            tokenFeesOwedA: position.tokenFeesOwedA,\n            tokenFeesOwedB: position.tokenFeesOwedB,\n            rewardInfos: position.rewardInfos.map((i) => ({\n              ...i,\n              pendingReward: new BN(0),\n            })),\n\n            leverage,\n            tokenFeeAmountA: new BN(0),\n            tokenFeeAmountB: new BN(0),\n          },\n        ];\n\n        const tickArrayLowerAddress = await TickUtils.getTickArrayAddressByTick(\n          poolInfoA.state.programId,\n          position.poolId,\n          position.tickLower,\n          poolInfoA.state.tickSpacing,\n        );\n        const tickArrayUpperAddress = await TickUtils.getTickArrayAddressByTick(\n          poolInfoA.state.programId,\n          position.poolId,\n          position.tickUpper,\n          poolInfoA.state.tickSpacing,\n        );\n        keyToTickArrayAddress[\n          `${poolInfoA.state.programId.toString()}-${position.poolId.toString()}-${position.tickLower}`\n        ] = tickArrayLowerAddress;\n        keyToTickArrayAddress[\n          `${poolInfoA.state.programId.toString()}-${position.poolId.toString()}-${position.tickUpper}`\n        ] = tickArrayUpperAddress;\n      }\n\n      if (updateOwnerRewardAndFee) {\n        const tickArrayKeys = Object.values(keyToTickArrayAddress);\n        const tickArrayDatas = await getMultipleAccountsInfo(connection, tickArrayKeys, { batchRequest });\n        const tickArrayLayout = {};\n        for (let index = 0; index < tickArrayKeys.length; index++) {\n          const tickArrayData = tickArrayDatas[index];\n          if (tickArrayData === null) continue;\n          const key = tickArrayKeys[index].toString();\n          tickArrayLayout[key] = TickArrayLayout.decode(tickArrayData.data);\n        }\n\n        for (const { state, positionAccount } of pools) {\n          if (!positionAccount) continue;\n          for (const itemPA of positionAccount) {\n            const keyLower = `${state.programId.toString()}-${state.id.toString()}-${itemPA.tickLower}`;\n            const keyUpper = `${state.programId.toString()}-${state.id.toString()}-${itemPA.tickUpper}`;\n            const tickArrayLower = tickArrayLayout[keyToTickArrayAddress[keyLower].toString()];\n            const tickArrayUpper = tickArrayLayout[keyToTickArrayAddress[keyUpper].toString()];\n            const tickLowerState: Tick =\n              tickArrayLower.ticks[TickUtils.getTickOffsetInArray(itemPA.tickLower, state.tickSpacing)];\n            const tickUpperState: Tick =\n              tickArrayUpper.ticks[TickUtils.getTickOffsetInArray(itemPA.tickUpper, state.tickSpacing)];\n            const { tokenFeeAmountA, tokenFeeAmountB } = await PositionUtils.GetPositionFees(\n              state,\n              itemPA,\n              tickLowerState,\n              tickUpperState,\n            );\n            const rewardInfos = await PositionUtils.GetPositionRewards(state, itemPA, tickLowerState, tickUpperState);\n            itemPA.tokenFeeAmountA = tokenFeeAmountA.gte(new BN(0)) ? tokenFeeAmountA : new BN(0);\n            itemPA.tokenFeeAmountB = tokenFeeAmountB.gte(new BN(0)) ? tokenFeeAmountB : new BN(0);\n            for (let i = 0; i < rewardInfos.length; i++) {\n              itemPA.rewardInfos[i].pendingReward = rewardInfos[i].gte(new BN(0)) ? rewardInfos[i] : new BN(0);\n            }\n          }\n        }\n      }\n    }\n    return pools;\n  }\n\n  static computeAmountOut({\n    poolInfo,\n    tickArrayCache,\n    baseMint,\n    epochInfo,\n    amountIn,\n    slippage,\n    priceLimit = new Decimal(0),\n    catchLiquidityInsufficient = false,\n  }: {\n    poolInfo: ComputeClmmPoolInfo;\n    tickArrayCache: { [key: string]: TickArray };\n    baseMint: PublicKey;\n\n    epochInfo: EpochInfo;\n\n    amountIn: BN;\n    slippage: number;\n    priceLimit?: Decimal;\n    catchLiquidityInsufficient: boolean;\n  }): ReturnTypeComputeAmountOut {\n    let sqrtPriceLimitX64: BN;\n    const isBaseIn = baseMint.toBase58() === poolInfo.mintA.address;\n    const [baseFeeConfig, outFeeConfig] = isBaseIn\n      ? [poolInfo.mintA.extensions.feeConfig, poolInfo.mintB.extensions.feeConfig]\n      : [poolInfo.mintB.extensions.feeConfig, poolInfo.mintA.extensions.feeConfig];\n\n    if (priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 = isBaseIn ? MIN_SQRT_PRICE_X64.add(new BN(1)) : MAX_SQRT_PRICE_X64.sub(new BN(1));\n    } else {\n      sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n        priceLimit,\n        poolInfo.mintA.decimals,\n        poolInfo.mintB.decimals,\n      );\n    }\n\n    const realAmountIn = getTransferAmountFeeV2(amountIn, baseFeeConfig, epochInfo, false);\n\n    const {\n      allTrade,\n      expectedAmountOut: _expectedAmountOut,\n      remainingAccounts,\n      executionPrice: _executionPriceX64,\n      feeAmount,\n    } = PoolUtils.getOutputAmountAndRemainAccounts(\n      poolInfo,\n      tickArrayCache,\n      baseMint,\n      realAmountIn.amount.sub(realAmountIn.fee ?? ZERO),\n      sqrtPriceLimitX64,\n      catchLiquidityInsufficient,\n    );\n\n    const amountOut = getTransferAmountFeeV2(_expectedAmountOut, outFeeConfig, epochInfo, false);\n\n    const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      _executionPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const executionPrice = isBaseIn ? _executionPrice : new Decimal(1).div(_executionPrice);\n\n    const _minAmountOut = _expectedAmountOut\n      .mul(new BN(Math.floor((1 - slippage) * 10000000000)))\n      .div(new BN(10000000000));\n    const minAmountOut = getTransferAmountFeeV2(_minAmountOut, outFeeConfig, epochInfo, false);\n\n    const poolPrice = isBaseIn ? poolInfo.currentPrice : new Decimal(1).div(poolInfo.currentPrice);\n\n    const _numerator = new Decimal(executionPrice).sub(poolPrice).abs();\n    const _denominator = poolPrice;\n    const priceImpact = new Percent(\n      new Decimal(_numerator).mul(10 ** 15).toFixed(0),\n      new Decimal(_denominator).mul(10 ** 15).toFixed(0),\n    );\n\n    return {\n      allTrade,\n      realAmountIn,\n      amountOut,\n      minAmountOut,\n      expirationTime: minExpirationTime(realAmountIn.expirationTime, amountOut.expirationTime),\n      currentPrice: poolInfo.currentPrice,\n      executionPrice,\n      priceImpact,\n      fee: feeAmount,\n      remainingAccounts,\n      executionPriceX64: _executionPriceX64,\n    };\n  }\n\n  static computeAmountOutFormat({\n    poolInfo,\n    tickArrayCache,\n    amountIn,\n    tokenOut: _tokenOut,\n    slippage,\n    epochInfo,\n    catchLiquidityInsufficient = false,\n  }: {\n    poolInfo: ComputeClmmPoolInfo;\n    tickArrayCache: { [key: string]: TickArray };\n    amountIn: BN;\n    tokenOut: ApiV3Token;\n    slippage: number;\n    epochInfo: EpochInfo;\n    catchLiquidityInsufficient?: boolean;\n  }): ReturnTypeComputeAmountOutFormat {\n    const baseIn = _tokenOut.address === poolInfo.mintB.address;\n    const [inputMint, outMint] = baseIn ? [poolInfo.mintA, poolInfo.mintB] : [poolInfo.mintB, poolInfo.mintA];\n    const [baseToken, outToken] = [\n      new Token({\n        ...inputMint,\n        mint: inputMint.address,\n        isToken2022: inputMint.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n      }),\n      new Token({\n        ...outMint,\n        mint: outMint.address,\n        isToken2022: outMint.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n      }),\n    ];\n\n    const {\n      allTrade,\n      realAmountIn: _realAmountIn,\n      amountOut: _amountOut,\n      minAmountOut: _minAmountOut,\n      expirationTime,\n      currentPrice,\n      executionPrice,\n      priceImpact,\n      fee,\n      remainingAccounts,\n      executionPriceX64,\n    } = PoolUtils.computeAmountOut({\n      poolInfo,\n      tickArrayCache,\n      baseMint: new PublicKey(inputMint.address),\n      amountIn,\n      slippage,\n      epochInfo,\n      catchLiquidityInsufficient,\n    });\n\n    const realAmountIn = {\n      ..._realAmountIn,\n      amount: new TokenAmount(baseToken, _realAmountIn.amount),\n      fee: _realAmountIn.fee === undefined ? undefined : new TokenAmount(baseToken, _realAmountIn.fee),\n    };\n\n    const amountOut = {\n      ..._amountOut,\n      amount: new TokenAmount(outToken, _amountOut.amount),\n      fee: _amountOut.fee === undefined ? undefined : new TokenAmount(outToken, _amountOut.fee),\n    };\n    const minAmountOut = {\n      ..._minAmountOut,\n      amount: new TokenAmount(outToken, _minAmountOut.amount),\n      fee: _minAmountOut.fee === undefined ? undefined : new TokenAmount(outToken, _minAmountOut.fee),\n    };\n\n    const _currentPrice = new Price({\n      baseToken,\n      denominator: new BN(10).pow(new BN(20 + baseToken.decimals)),\n      quoteToken: outToken,\n      numerator: currentPrice.mul(new Decimal(10 ** (20 + outToken.decimals))).toFixed(0),\n    });\n    const _executionPrice = new Price({\n      baseToken,\n      denominator: new BN(10).pow(new BN(20 + baseToken.decimals)),\n      quoteToken: outToken,\n      numerator: executionPrice.mul(new Decimal(10 ** (20 + outToken.decimals))).toFixed(0),\n    });\n    const _fee = new TokenAmount(baseToken, fee);\n\n    return {\n      allTrade,\n      realAmountIn,\n      amountOut,\n      minAmountOut,\n      expirationTime,\n      currentPrice: _currentPrice,\n      executionPrice: _executionPrice,\n      priceImpact,\n      fee: _fee,\n      remainingAccounts,\n      executionPriceX64,\n    };\n  }\n\n  static computeAmountIn({\n    poolInfo,\n    tickArrayCache,\n    baseMint,\n    epochInfo,\n    amountOut,\n    slippage,\n    priceLimit = new Decimal(0),\n  }: {\n    poolInfo: ComputeClmmPoolInfo;\n    tickArrayCache: { [key: string]: TickArray };\n    baseMint: PublicKey;\n\n    epochInfo: EpochInfo;\n\n    amountOut: BN;\n    slippage: number;\n    priceLimit?: Decimal;\n  }): ReturnTypeComputeAmountOutBaseOut {\n    const isBaseIn = baseMint.toBase58() === poolInfo.mintA.address;\n    const feeConfigs = {\n      [poolInfo.mintA.address]: poolInfo.mintA.extensions.feeConfig,\n      [poolInfo.mintB.address]: poolInfo.mintB.extensions.feeConfig,\n    };\n\n    let sqrtPriceLimitX64: BN;\n    if (priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 = !isBaseIn ? MIN_SQRT_PRICE_X64.add(new BN(1)) : MAX_SQRT_PRICE_X64.sub(new BN(1));\n    } else {\n      sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n        priceLimit,\n        poolInfo.mintA.decimals,\n        poolInfo.mintB.decimals,\n      );\n    }\n\n    const realAmountOut = getTransferAmountFeeV2(amountOut, feeConfigs[baseMint.toString()], epochInfo, true);\n\n    const {\n      expectedAmountIn: _expectedAmountIn,\n      remainingAccounts,\n      executionPrice: _executionPriceX64,\n      feeAmount,\n    } = PoolUtils.getInputAmountAndRemainAccounts(\n      poolInfo,\n      tickArrayCache,\n      baseMint,\n      realAmountOut.amount.sub(realAmountOut.fee ?? ZERO),\n      sqrtPriceLimitX64,\n    );\n\n    const inMint = isBaseIn ? poolInfo.mintB.address : poolInfo.mintA.address;\n\n    const amountIn = getTransferAmountFeeV2(_expectedAmountIn, feeConfigs[inMint], epochInfo, false);\n    // const amountIn = getTransferAmountFee(\n    //   _expectedAmountIn,\n    //   token2022Infos[inMint.toString()]?.feeConfig,\n    //   epochInfo,\n    //   true,\n    // );\n\n    const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      _executionPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const executionPrice = isBaseIn ? _executionPrice : new Decimal(1).div(_executionPrice);\n\n    const _maxAmountIn = _expectedAmountIn\n      .mul(new BN(Math.floor((1 + slippage) * 10000000000)))\n      .div(new BN(10000000000));\n    // const maxAmountIn = getTransferAmountFee(\n    //   _maxAmountIn,\n    //   token2022Infos[inMint.toString()]?.feeConfig,\n    //   epochInfo,\n    //   true,\n    // );\n    const maxAmountIn = getTransferAmountFeeV2(_maxAmountIn, feeConfigs[inMint], epochInfo, true);\n\n    const poolPrice = isBaseIn ? poolInfo.currentPrice : new Decimal(1).div(poolInfo.currentPrice);\n\n    const _numerator = new Decimal(executionPrice).sub(poolPrice).abs();\n    const _denominator = poolPrice;\n    const priceImpact = new Percent(\n      new Decimal(_numerator).mul(10 ** 15).toFixed(0),\n      new Decimal(_denominator).mul(10 ** 15).toFixed(0),\n    );\n\n    return {\n      amountIn,\n      maxAmountIn,\n      realAmountOut,\n      expirationTime: minExpirationTime(amountIn.expirationTime, realAmountOut.expirationTime),\n      currentPrice: poolInfo.currentPrice,\n      executionPrice,\n      priceImpact,\n      fee: feeAmount,\n\n      remainingAccounts,\n    };\n  }\n\n  static estimateAprsForPriceRangeMultiplier({\n    poolInfo,\n    aprType,\n    positionTickLowerIndex,\n    positionTickUpperIndex,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    aprType: \"day\" | \"week\" | \"month\";\n\n    positionTickLowerIndex: number;\n    positionTickUpperIndex: number;\n  }): {\n    feeApr: number;\n    rewardsApr: number[];\n    apr: number;\n  } {\n    const aprInfo = poolInfo[aprType];\n\n    const priceLower = TickUtils.getTickPrice({\n      poolInfo,\n      tick: positionTickLowerIndex,\n      baseIn: true,\n    }).price.toNumber();\n    const priceUpper = TickUtils.getTickPrice({\n      poolInfo,\n      tick: positionTickUpperIndex,\n      baseIn: true,\n    }).price.toNumber();\n\n    const _minPrice = Math.max(priceLower, aprInfo.priceMin);\n    const _maxPrice = Math.min(priceUpper, aprInfo.priceMax);\n\n    const sub = _maxPrice - _minPrice;\n\n    const userRange = priceUpper - priceLower;\n    const tradeRange = aprInfo.priceMax - aprInfo.priceMin;\n\n    let p: number;\n\n    if (sub <= 0) p = 0;\n    else if (userRange === sub) p = tradeRange / sub;\n    else if (tradeRange === sub) p = sub / userRange;\n    else p = (sub / tradeRange) * (sub / userRange);\n\n    return {\n      feeApr: aprInfo.feeApr * p,\n      rewardsApr: [(aprInfo.rewardApr[0] ?? 0) * p, (aprInfo.rewardApr[1] ?? 0) * p, (aprInfo.rewardApr[2] ?? 0) * p],\n      apr: aprInfo.apr * p,\n    };\n  }\n\n  static estimateAprsForPriceRangeDelta({\n    poolInfo,\n    poolLiquidity,\n    aprType,\n    mintPrice,\n    liquidity,\n    positionTickLowerIndex,\n    positionTickUpperIndex,\n    chainTime,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolLiquidity: BN;\n    aprType: \"day\" | \"week\" | \"month\";\n\n    mintPrice: { [mint: string]: { value: number } };\n\n    liquidity: BN;\n    positionTickLowerIndex: number;\n    positionTickUpperIndex: number;\n\n    chainTime: number;\n  }): {\n    feeApr: number;\n    rewardsApr: number[];\n    apr: number;\n  } {\n    const aprTypeDay = aprType === \"day\" ? 1 : aprType === \"week\" ? 7 : aprType === \"month\" ? 30 : 0;\n    const aprInfo = poolInfo[aprType];\n    const mintPriceA = mintPrice[solToWSol(poolInfo.mintA.address).toString()];\n    const mintPriceB = mintPrice[solToWSol(poolInfo.mintB.address).toString()];\n    const mintDecimalsA = poolInfo.mintA.decimals;\n    const mintDecimalsB = poolInfo.mintB.decimals;\n\n    if (!aprInfo || !mintPriceA || !mintPriceB) return { feeApr: 0, rewardsApr: [0, 0, 0], apr: 0 };\n\n    const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n      new Decimal(poolInfo.price),\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n\n    const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(positionTickLowerIndex);\n    const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(positionTickUpperIndex);\n\n    const { amountSlippageA: poolLiquidityA, amountSlippageB: poolLiquidityB } =\n      LiquidityMath.getAmountsFromLiquidityWithSlippage(\n        sqrtPriceX64,\n        sqrtPriceX64A,\n        sqrtPriceX64B,\n        poolLiquidity,\n        false,\n        false,\n        0,\n      );\n\n    const { amountSlippageA: userLiquidityA, amountSlippageB: userLiquidityB } =\n      LiquidityMath.getAmountsFromLiquidityWithSlippage(\n        sqrtPriceX64,\n        sqrtPriceX64A,\n        sqrtPriceX64B,\n        liquidity,\n        false,\n        false,\n        0,\n      );\n\n    const poolTvl = new Decimal(poolLiquidityA.toString())\n      .div(new Decimal(10).pow(mintDecimalsA))\n      .mul(mintPriceA.value)\n      .add(new Decimal(poolLiquidityB.toString()).div(new Decimal(10).pow(mintDecimalsB)).mul(mintPriceB.value));\n    const userTvl = new Decimal(userLiquidityA.toString())\n      .div(new Decimal(10).pow(mintDecimalsA))\n      .mul(mintPriceA.value)\n      .add(new Decimal(userLiquidityB.toString()).div(new Decimal(10).pow(mintDecimalsB)).mul(mintPriceB.value));\n\n    const p = new Decimal(1).div(poolTvl.add(userTvl));\n\n    const feesPerYear = new Decimal(aprInfo.volumeFee).mul(365).div(aprTypeDay);\n    const feeApr = feesPerYear.mul(p).mul(100).toNumber();\n\n    const SECONDS_PER_YEAR = 3600 * 24 * 365;\n\n    const rewardsApr = poolInfo.rewardDefaultInfos.map((i) => {\n      const iDecimal = i.mint.decimals;\n      const iPrice = mintPrice[i.mint.address];\n\n      if (\n        chainTime < ((i as any).startTime ?? 0) ||\n        chainTime > ((i as any).endTime ?? 0) ||\n        !i.perSecond ||\n        !iPrice ||\n        iDecimal === undefined\n      )\n        return 0;\n\n      return new Decimal(iPrice.value)\n        .mul(new Decimal(i.perSecond).mul(SECONDS_PER_YEAR))\n        .div(new Decimal(10).pow(iDecimal))\n        .mul(p)\n        .mul(100)\n        .toNumber();\n    });\n\n    return {\n      feeApr,\n      rewardsApr,\n      apr: feeApr + rewardsApr.reduce((a, b) => a + b, 0),\n    };\n  }\n\n  static async getLiquidityAmountOutFromAmountIn({\n    poolInfo,\n    inputA,\n    tickLower,\n    tickUpper,\n    amount,\n    slippage,\n    add,\n    epochInfo,\n    amountHasFee,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    inputA: boolean;\n    tickLower: number;\n    tickUpper: number;\n    amount: BN;\n    slippage: number;\n    add: boolean;\n    epochInfo: EpochInfo;\n    amountHasFee: boolean;\n  }): Promise<ReturnTypeGetLiquidityAmountOut> {\n    const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n      new Decimal(poolInfo.price),\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(tickLower);\n    const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(tickUpper);\n\n    // const coefficient = add ? 1 - slippage : 1 + slippage;\n    const addFeeAmount = getTransferAmountFeeV2(\n      amount,\n      poolInfo[inputA ? \"mintA\" : \"mintB\"].extensions?.feeConfig,\n      epochInfo,\n      !amountHasFee,\n    );\n    const _amount = new BN(\n      new Decimal(addFeeAmount.amount.sub(addFeeAmount.fee ?? ZERO).toString()).toFixed(0) // .mul(coefficient).toFixed(0),\n    );\n\n    let liquidity: BN;\n    if (sqrtPriceX64.lte(sqrtPriceX64A)) {\n      liquidity = inputA\n        ? LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceX64A, sqrtPriceX64B, _amount, !add)\n        : new BN(0);\n    } else if (sqrtPriceX64.lte(sqrtPriceX64B)) {\n      const liquidity0 = LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceX64, sqrtPriceX64B, _amount, !add);\n      const liquidity1 = LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceX64, _amount);\n      liquidity = inputA ? liquidity0 : liquidity1;\n    } else {\n      liquidity = inputA\n        ? new BN(0)\n        : LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceX64B, _amount);\n    }\n\n    const amountFromLiquidity = await PoolUtils.getAmountsFromLiquidity({\n      epochInfo,\n      poolInfo,\n      tickLower,\n      tickUpper,\n      liquidity,\n      slippage,\n      add,\n    });\n    return {\n      liquidity,\n      amountA: inputA ? addFeeAmount : amountFromLiquidity.amountA,\n      amountB: inputA ? amountFromLiquidity.amountB : addFeeAmount,\n      amountSlippageA: inputA ? addFeeAmount : amountFromLiquidity.amountSlippageA,\n      amountSlippageB: inputA ? amountFromLiquidity.amountSlippageB : addFeeAmount,\n      expirationTime: amountFromLiquidity.expirationTime,\n    }\n  }\n\n  static async getAmountsFromLiquidity({\n    epochInfo,\n    poolInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    slippage,\n    add,\n  }: {\n    epochInfo: EpochInfo;\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    tickLower: number;\n    tickUpper: number;\n    liquidity: BN;\n    slippage: number;\n    add: boolean;\n  }): Promise<ReturnTypeGetLiquidityAmountOut> {\n    const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(tickLower);\n    const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(tickUpper);\n\n    const coefficientRe = add ? 1 + slippage : 1 - slippage;\n\n    const amounts = LiquidityMath.getAmountsFromLiquidity(\n      SqrtPriceMath.priceToSqrtPriceX64(new Decimal(poolInfo.price), poolInfo.mintA.decimals, poolInfo.mintB.decimals),\n      sqrtPriceX64A,\n      sqrtPriceX64B,\n      liquidity,\n      add,\n    );\n    const [amountA, amountB] = [\n      getTransferAmountFeeV2(amounts.amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, true),\n      getTransferAmountFeeV2(amounts.amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, true),\n    ];\n    const [amountSlippageA, amountSlippageB] = [\n      getTransferAmountFeeV2(\n        amounts.amountA.muln(coefficientRe),\n        poolInfo.mintA.extensions?.feeConfig,\n        epochInfo,\n        true,\n      ),\n      getTransferAmountFeeV2(\n        amounts.amountB.muln(coefficientRe),\n        poolInfo.mintB.extensions?.feeConfig,\n        epochInfo,\n        true,\n      ),\n    ];\n\n    return {\n      liquidity,\n      amountA,\n      amountB,\n      amountSlippageA,\n      amountSlippageB,\n      expirationTime: minExpirationTime(amountA.expirationTime, amountB.expirationTime),\n    };\n  }\n\n  static async fetchComputeMultipleClmmInfo({\n    connection,\n    poolList,\n    rpcDataMap = {},\n  }: {\n    rpcDataMap?: Record<string, ReturnType<typeof PoolInfoLayout.decode>>;\n    connection: Connection;\n    poolList: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\" | \"price\">[];\n  }): Promise<Record<string, ComputeClmmPoolInfo>> {\n    const fetchRpcList = poolList.filter((p) => !rpcDataMap[p.id]).map((p) => new PublicKey(p.id));\n    const rpcRes = await getMultipleAccountsInfo(connection, fetchRpcList);\n    rpcRes.forEach((r, idx) => {\n      if (!r) return;\n      rpcDataMap[fetchRpcList[idx].toBase58()] = PoolInfoLayout.decode(r.data);\n    });\n\n    const pdaList = poolList.map(\n      (poolInfo) => getPdaExBitmapAccount(new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)).publicKey,\n    );\n\n    const exBitData = await PoolUtils.fetchExBitmaps({\n      connection,\n      exBitmapAddress: pdaList,\n      batchRequest: false,\n    });\n\n    return poolList.reduce(\n      (acc, cur) => ({\n        ...acc,\n        [cur.id]: {\n          ...rpcDataMap[cur.id],\n          id: new PublicKey(cur.id),\n          version: 6,\n          programId: new PublicKey(cur.programId),\n          mintA: cur.mintA,\n          mintB: cur.mintB,\n          ammConfig: {\n            ...cur.config,\n            id: new PublicKey(cur.config.id),\n            fundOwner: \"\",\n          },\n          currentPrice: new Decimal(cur.price),\n          exBitmapAccount: getPdaExBitmapAccount(new PublicKey(cur.programId), new PublicKey(cur.id)).publicKey,\n          exBitmapInfo:\n            exBitData[getPdaExBitmapAccount(new PublicKey(cur.programId), new PublicKey(cur.id)).publicKey.toBase58()],\n          startTime: rpcDataMap[cur.id].startTime.toNumber(),\n          rewardInfos: rpcDataMap[cur.id].rewardInfos,\n        },\n      }),\n      {} as Record<string, ComputeClmmPoolInfo>,\n    );\n  }\n\n  static async fetchComputeClmmInfo({\n    connection,\n    poolInfo,\n    rpcData,\n  }: {\n    connection: Connection;\n    poolInfo: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\" | \"price\">;\n    rpcData?: ReturnType<typeof PoolInfoLayout.decode>;\n  }): Promise<ComputeClmmPoolInfo> {\n    return (\n      await this.fetchComputeMultipleClmmInfo({\n        connection,\n        rpcDataMap: rpcData ? { [poolInfo.id]: rpcData } : undefined,\n        poolList: [poolInfo],\n      })\n    )[poolInfo.id];\n  }\n}\n\nexport function getLiquidityFromAmounts({\n  poolInfo,\n  tickLower,\n  tickUpper,\n  amountA,\n  amountB,\n  slippage,\n  add,\n  epochInfo,\n  amountHasFee,\n}: {\n  poolInfo: ApiV3PoolInfoConcentratedItem;\n  tickLower: number;\n  tickUpper: number;\n  amountA: BN;\n  amountB: BN;\n  slippage: number;\n  add: boolean;\n  epochInfo: EpochInfo;\n  amountHasFee: boolean;\n}): ReturnTypeGetLiquidityAmountOut {\n  const [_tickLower, _tickUpper, _amountA, _amountB] =\n    tickLower < tickUpper ? [tickLower, tickUpper, amountA, amountB] : [tickUpper, tickLower, amountB, amountA];\n  const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n    new Decimal(poolInfo.price),\n    poolInfo.mintA.decimals,\n    poolInfo.mintB.decimals,\n  );\n  const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(_tickLower);\n  const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(_tickUpper);\n\n  const [amountFeeA, amountFeeB] = [\n    getTransferAmountFeeV2(_amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, !amountHasFee),\n    getTransferAmountFeeV2(_amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, !amountHasFee),\n  ];\n\n  const liquidity = LiquidityMath.getLiquidityFromTokenAmounts(\n    sqrtPriceX64,\n    sqrtPriceX64A,\n    sqrtPriceX64B,\n    amountFeeA.amount.sub(amountFeeA.fee ?? ZERO),\n    amountFeeB.amount.sub(amountFeeB.fee ?? ZERO),\n  );\n\n  return LiquidityMath.getAmountsOutFromLiquidity({\n    poolInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    slippage,\n    add,\n    epochInfo,\n    amountAddFee: !amountHasFee,\n  });\n}\n\nconst mockRewardData = {\n  volume: 0,\n  volumeQuote: 0,\n  volumeFee: 0,\n  apr: 0,\n  feeApr: 0,\n  priceMin: 0,\n  priceMax: 0,\n  rewardApr: [],\n};\n\nexport function clmmComputeInfoToApiInfo(pool: ComputeClmmPoolInfo): ApiV3PoolInfoConcentratedItem {\n  return {\n    ...pool,\n    type: \"Concentrated\",\n    programId: pool.programId.toString(),\n    id: pool.id.toString(),\n    rewardDefaultInfos: [],\n    rewardDefaultPoolInfos: \"Clmm\",\n    price: pool.currentPrice.toNumber(),\n    mintAmountA: 0,\n    mintAmountB: 0,\n    feeRate: pool.ammConfig.tradeFeeRate,\n    openTime: pool.startTime.toString(),\n    tvl: 0,\n\n    day: mockRewardData,\n    week: mockRewardData,\n    month: mockRewardData,\n    pooltype: [],\n\n    farmUpcomingCount: 0,\n    farmOngoingCount: 0,\n    farmFinishedCount: 0,\n    burnPercent: 0,\n    config: {\n      ...pool.ammConfig,\n      id: pool.ammConfig.id.toString(),\n      defaultRange: 0,\n      defaultRangePoint: [],\n    },\n  };\n}\n","import BN from \"bn.js\";\n\nimport Decimal from \"decimal.js\";\nimport { getTransferAmountFeeV2, minExpirationTime } from \"../../../common\";\nimport { ClmmPositionLayout } from \"../layout\";\nimport { ClmmPoolInfo, ClmmPoolPersonalPosition, ClmmPoolRewardInfo, GetAmountParams, ReturnTypeGetLiquidityAmountOut } from \"../type\";\nimport { Q64 } from \"./constants\";\nimport { LiquidityMath, MathUtil, SqrtPriceMath } from \"./math\";\nimport { Tick } from \"./tick\";\n\nexport class PositionUtils {\n  static getfeeGrowthInside(\n    poolState: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64A\" | \"feeGrowthGlobalX64B\">,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n  ): { feeGrowthInsideX64A: BN; feeGrowthInsideBX64: BN } {\n    let feeGrowthBelowX64A = new BN(0);\n    let feeGrowthBelowX64B = new BN(0);\n    if (poolState.tickCurrent >= tickLowerState.tick) {\n      feeGrowthBelowX64A = tickLowerState.feeGrowthOutsideX64A;\n      feeGrowthBelowX64B = tickLowerState.feeGrowthOutsideX64B;\n    } else {\n      feeGrowthBelowX64A = poolState.feeGrowthGlobalX64A.sub(tickLowerState.feeGrowthOutsideX64A);\n      feeGrowthBelowX64B = poolState.feeGrowthGlobalX64B.sub(tickLowerState.feeGrowthOutsideX64B);\n    }\n\n    let feeGrowthAboveX64A = new BN(0);\n    let feeGrowthAboveX64B = new BN(0);\n    if (poolState.tickCurrent < tickUpperState.tick) {\n      feeGrowthAboveX64A = tickUpperState.feeGrowthOutsideX64A;\n      feeGrowthAboveX64B = tickUpperState.feeGrowthOutsideX64B;\n    } else {\n      feeGrowthAboveX64A = poolState.feeGrowthGlobalX64A.sub(tickUpperState.feeGrowthOutsideX64A);\n      feeGrowthAboveX64B = poolState.feeGrowthGlobalX64B.sub(tickUpperState.feeGrowthOutsideX64B);\n    }\n\n    const feeGrowthInsideX64A = MathUtil.wrappingSubU128(\n      MathUtil.wrappingSubU128(poolState.feeGrowthGlobalX64A, feeGrowthBelowX64A),\n      feeGrowthAboveX64A,\n    );\n    const feeGrowthInsideBX64 = MathUtil.wrappingSubU128(\n      MathUtil.wrappingSubU128(poolState.feeGrowthGlobalX64B, feeGrowthBelowX64B),\n      feeGrowthAboveX64B,\n    );\n    return { feeGrowthInsideX64A, feeGrowthInsideBX64 };\n  }\n\n  static GetPositionFees(\n    ammPool: ClmmPoolInfo,\n    positionState: ClmmPoolPersonalPosition,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n  ): { tokenFeeAmountA: BN; tokenFeeAmountB: BN } {\n    const { feeGrowthInsideX64A, feeGrowthInsideBX64 } = this.getfeeGrowthInside(\n      ammPool,\n      tickLowerState,\n      tickUpperState,\n    );\n\n    const feeGrowthdeltaA = MathUtil.mulDivFloor(\n      MathUtil.wrappingSubU128(feeGrowthInsideX64A, positionState.feeGrowthInsideLastX64A),\n      positionState.liquidity,\n      Q64,\n    );\n    const tokenFeeAmountA = positionState.tokenFeesOwedA.add(feeGrowthdeltaA);\n\n    const feeGrowthdelta1 = MathUtil.mulDivFloor(\n      MathUtil.wrappingSubU128(feeGrowthInsideBX64, positionState.feeGrowthInsideLastX64B),\n      positionState.liquidity,\n      Q64,\n    );\n    const tokenFeeAmountB = positionState.tokenFeesOwedB.add(feeGrowthdelta1);\n\n    return { tokenFeeAmountA, tokenFeeAmountB };\n  }\n\n  static GetPositionFeesV2(\n    ammPool: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64A\" | \"feeGrowthGlobalX64B\">,\n    positionState: ClmmPositionLayout,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n  ): { tokenFeeAmountA: BN; tokenFeeAmountB: BN } {\n    const { feeGrowthInsideX64A, feeGrowthInsideBX64 } = this.getfeeGrowthInside(\n      ammPool,\n      tickLowerState,\n      tickUpperState,\n    );\n\n    const feeGrowthdeltaA = MathUtil.mulDivFloor(\n      MathUtil.wrappingSubU128(feeGrowthInsideX64A, positionState.feeGrowthInsideLastX64A),\n      positionState.liquidity,\n      Q64,\n    );\n    const tokenFeeAmountA = positionState.tokenFeesOwedA.add(feeGrowthdeltaA);\n\n    const feeGrowthdelta1 = MathUtil.mulDivFloor(\n      MathUtil.wrappingSubU128(feeGrowthInsideBX64, positionState.feeGrowthInsideLastX64B),\n      positionState.liquidity,\n      Q64,\n    );\n    const tokenFeeAmountB = positionState.tokenFeesOwedB.add(feeGrowthdelta1);\n\n    return { tokenFeeAmountA, tokenFeeAmountB };\n  }\n\n  static GetPositionRewardsV2(\n    ammPool: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64B\"> & {\n      rewardInfos: { rewardGrowthGlobalX64: BN }[];\n    },\n    positionState: ClmmPositionLayout,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n  ): BN[] {\n    const rewards: BN[] = [];\n\n    const rewardGrowthsInside = this.getRewardGrowthInsideV2(\n      ammPool.tickCurrent,\n      tickLowerState,\n      tickUpperState,\n      ammPool.rewardInfos,\n    );\n    for (let i = 0; i < rewardGrowthsInside.length; i++) {\n      const rewardGrowthInside = rewardGrowthsInside[i];\n      const currRewardInfo = positionState.rewardInfos[i];\n\n      const rewardGrowthDelta = MathUtil.wrappingSubU128(rewardGrowthInside, currRewardInfo.growthInsideLastX64);\n      const amountOwedDelta = MathUtil.mulDivFloor(rewardGrowthDelta, positionState.liquidity, Q64);\n      const rewardAmountOwed = currRewardInfo.rewardAmountOwed.add(amountOwedDelta);\n      rewards.push(rewardAmountOwed);\n    }\n    return rewards;\n  }\n\n  static GetPositionRewards(\n    ammPool: ClmmPoolInfo,\n    positionState: ClmmPoolPersonalPosition,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n  ): BN[] {\n    const rewards: BN[] = [];\n\n    const rewardGrowthsInside = this.getRewardGrowthInside(\n      ammPool.tickCurrent,\n      tickLowerState,\n      tickUpperState,\n      ammPool.rewardInfos,\n    );\n    for (let i = 0; i < rewardGrowthsInside.length; i++) {\n      const rewardGrowthInside = rewardGrowthsInside[i];\n      const currRewardInfo = positionState.rewardInfos[i];\n\n      const rewardGrowthDelta = MathUtil.wrappingSubU128(rewardGrowthInside, currRewardInfo.growthInsideLastX64);\n      const amountOwedDelta = MathUtil.mulDivFloor(rewardGrowthDelta, positionState.liquidity, Q64);\n      const rewardAmountOwed = currRewardInfo.rewardAmountOwed.add(amountOwedDelta);\n      rewards.push(rewardAmountOwed);\n    }\n    return rewards;\n  }\n\n  static getRewardGrowthInside(\n    tickCurrentIndex: number,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n    rewardInfos: ClmmPoolRewardInfo[],\n  ): BN[] {\n    const rewardGrowthsInside: BN[] = [];\n    for (let i = 0; i < rewardInfos.length; i++) {\n      let rewardGrowthsBelow = new BN(0);\n      if (tickLowerState.liquidityGross.eqn(0)) {\n        rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64;\n      } else if (tickCurrentIndex < tickLowerState.tick) {\n        rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64.sub(tickLowerState.rewardGrowthsOutsideX64[i]);\n      } else {\n        rewardGrowthsBelow = tickLowerState.rewardGrowthsOutsideX64[i];\n      }\n\n      let rewardGrowthsAbove = new BN(0);\n      if (tickUpperState.liquidityGross.eqn(0)) {\n        //\n      } else if (tickCurrentIndex < tickUpperState.tick) {\n        rewardGrowthsAbove = tickUpperState.rewardGrowthsOutsideX64[i];\n      } else {\n        rewardGrowthsAbove = rewardInfos[i].rewardGrowthGlobalX64.sub(tickUpperState.rewardGrowthsOutsideX64[i]);\n      }\n\n      rewardGrowthsInside.push(\n        MathUtil.wrappingSubU128(\n          MathUtil.wrappingSubU128(rewardInfos[i].rewardGrowthGlobalX64, rewardGrowthsBelow),\n          rewardGrowthsAbove,\n        ),\n      );\n    }\n\n    return rewardGrowthsInside;\n  }\n\n  static getRewardGrowthInsideV2(\n    tickCurrentIndex: number,\n    tickLowerState: Tick,\n    tickUpperState: Tick,\n    rewardInfos: Pick<ClmmPoolRewardInfo, \"rewardGrowthGlobalX64\">[],\n  ): BN[] {\n    const rewardGrowthsInside: BN[] = [];\n    for (let i = 0; i < rewardInfos.length; i++) {\n      let rewardGrowthsBelow = new BN(0);\n      if (tickLowerState.liquidityGross.eqn(0)) {\n        rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64;\n      } else if (tickCurrentIndex < tickLowerState.tick) {\n        rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64.sub(tickLowerState.rewardGrowthsOutsideX64[i]);\n      } else {\n        rewardGrowthsBelow = tickLowerState.rewardGrowthsOutsideX64[i];\n      }\n\n      let rewardGrowthsAbove = new BN(0);\n      if (tickUpperState.liquidityGross.eqn(0)) {\n        //\n      } else if (tickCurrentIndex < tickUpperState.tick) {\n        rewardGrowthsAbove = tickUpperState.rewardGrowthsOutsideX64[i];\n      } else {\n        rewardGrowthsAbove = rewardInfos[i].rewardGrowthGlobalX64.sub(tickUpperState.rewardGrowthsOutsideX64[i]);\n      }\n\n      rewardGrowthsInside.push(\n        MathUtil.wrappingSubU128(\n          MathUtil.wrappingSubU128(rewardInfos[i].rewardGrowthGlobalX64, rewardGrowthsBelow),\n          rewardGrowthsAbove,\n        ),\n      );\n    }\n\n    return rewardGrowthsInside;\n  }\n\n  static getAmountsFromLiquidity({\n    poolInfo,\n    ownerPosition,\n    liquidity,\n    slippage,\n    add,\n    epochInfo,\n  }: GetAmountParams): ReturnTypeGetLiquidityAmountOut {\n    const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n      new Decimal(poolInfo.price),\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(ownerPosition.tickLower);\n    const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(ownerPosition.tickUpper);\n\n    const coefficientRe = add ? 1 + slippage : 1 - slippage;\n\n    const amounts = LiquidityMath.getAmountsFromLiquidity(sqrtPriceX64, sqrtPriceX64A, sqrtPriceX64B, liquidity, add);\n\n    const [amountA, amountB] = [\n      getTransferAmountFeeV2(amounts.amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, true),\n      getTransferAmountFeeV2(amounts.amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, true),\n    ];\n    const [amountSlippageA, amountSlippageB] = [\n      getTransferAmountFeeV2(\n        new BN(new Decimal(amounts.amountA.toString()).mul(coefficientRe).toFixed(0)),\n        poolInfo.mintA.extensions?.feeConfig,\n        epochInfo,\n        true,\n      ),\n      getTransferAmountFeeV2(\n        new BN(new Decimal(amounts.amountB.toString()).mul(coefficientRe).toFixed(0)),\n        poolInfo.mintB.extensions?.feeConfig,\n        epochInfo,\n        true,\n      ),\n    ];\n\n    return {\n      liquidity,\n      amountA,\n      amountB,\n      amountSlippageA,\n      amountSlippageB,\n      expirationTime: minExpirationTime(amountA.expirationTime, amountB.expirationTime),\n    };\n  }\n}\n","import BN from \"bn.js\";\n\nimport { TickArrayBitmapExtensionType } from \"../type\";\n\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { TICK_ARRAY_BITMAP_SIZE, TICK_ARRAY_SIZE, TickUtils } from \"./tick\";\nimport { TickQuery } from \"./tickQuery\";\nimport { isZero, leadingZeros, leastSignificantBit, mostSignificantBit, trailingZeros } from \"./util\";\n\nexport const EXTENSION_TICKARRAY_BITMAP_SIZE = 14;\n\nexport class TickArrayBitmap {\n  public static maxTickInTickarrayBitmap(tickSpacing: number): number {\n    return tickSpacing * TICK_ARRAY_SIZE * TICK_ARRAY_BITMAP_SIZE;\n  }\n\n  public static getBitmapTickBoundary(\n    tickarrayStartIndex: number,\n    tickSpacing: number,\n  ): {\n    minValue: number;\n    maxValue: number;\n  } {\n    const ticksInOneBitmap = this.maxTickInTickarrayBitmap(tickSpacing);\n    let m = Math.floor(Math.abs(tickarrayStartIndex) / ticksInOneBitmap);\n    if (tickarrayStartIndex < 0 && Math.abs(tickarrayStartIndex) % ticksInOneBitmap != 0) m += 1;\n\n    const minValue = ticksInOneBitmap * m;\n\n    return tickarrayStartIndex < 0\n      ? { minValue: -minValue, maxValue: -minValue + ticksInOneBitmap }\n      : { minValue, maxValue: minValue + ticksInOneBitmap };\n  }\n\n  public static nextInitializedTickArrayStartIndex(\n    bitMap: BN,\n    lastTickArrayStartIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n  ): { isInit: boolean; tickIndex: number } {\n    if (!TickQuery.checkIsValidStartIndex(lastTickArrayStartIndex, tickSpacing))\n      throw Error(\"nextInitializedTickArrayStartIndex check error\");\n\n    const tickBoundary = this.maxTickInTickarrayBitmap(tickSpacing);\n    const nextTickArrayStartIndex = zeroForOne\n      ? lastTickArrayStartIndex - TickQuery.tickCount(tickSpacing)\n      : lastTickArrayStartIndex + TickQuery.tickCount(tickSpacing);\n\n    if (nextTickArrayStartIndex < -tickBoundary || nextTickArrayStartIndex >= tickBoundary) {\n      return { isInit: false, tickIndex: lastTickArrayStartIndex };\n    }\n\n    const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n    let compressed = nextTickArrayStartIndex / multiplier + 512;\n\n    if (nextTickArrayStartIndex < 0 && nextTickArrayStartIndex % multiplier != 0) {\n      compressed--;\n    }\n\n    const bitPos = Math.abs(compressed);\n\n    if (zeroForOne) {\n      const offsetBitMap = bitMap.shln(1024 - bitPos - 1);\n      const nextBit = mostSignificantBit(1024, offsetBitMap);\n      if (nextBit !== null) {\n        const nextArrayStartIndex = (bitPos - nextBit - 512) * multiplier;\n        return { isInit: true, tickIndex: nextArrayStartIndex };\n      } else {\n        return { isInit: false, tickIndex: -tickBoundary };\n      }\n    } else {\n      const offsetBitMap = bitMap.shrn(bitPos);\n      const nextBit = leastSignificantBit(1024, offsetBitMap);\n      if (nextBit !== null) {\n        const nextArrayStartIndex = (bitPos + nextBit - 512) * multiplier;\n        return { isInit: true, tickIndex: nextArrayStartIndex };\n      } else {\n        return { isInit: false, tickIndex: tickBoundary - TickQuery.tickCount(tickSpacing) };\n      }\n    }\n  }\n}\n\nexport class TickArrayBitmapExtensionUtils {\n  public static getBitmapOffset(tickIndex: number, tickSpacing: number): number {\n    if (!TickQuery.checkIsValidStartIndex(tickIndex, tickSpacing)) {\n      throw new Error(\"No enough initialized tickArray\");\n    }\n    this.checkExtensionBoundary(tickIndex, tickSpacing);\n\n    const ticksInOneBitmap = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n    let offset = Math.floor(Math.abs(tickIndex) / ticksInOneBitmap) - 1;\n\n    if (tickIndex < 0 && Math.abs(tickIndex) % ticksInOneBitmap === 0) offset--;\n    return offset;\n  }\n\n  public static getBitmap(\n    tickIndex: number,\n    tickSpacing: number,\n    tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n  ): { offset: number; tickarrayBitmap: BN[] } {\n    const offset = this.getBitmapOffset(tickIndex, tickSpacing);\n    if (tickIndex < 0) {\n      return { offset, tickarrayBitmap: tickArrayBitmapExtension.negativeTickArrayBitmap[offset] };\n    } else {\n      return { offset, tickarrayBitmap: tickArrayBitmapExtension.positiveTickArrayBitmap[offset] };\n    }\n  }\n\n  public static checkExtensionBoundary(tickIndex: number, tickSpacing: number) {\n    const { positiveTickBoundary, negativeTickBoundary } = this.extensionTickBoundary(tickSpacing);\n\n    if (tickIndex >= negativeTickBoundary && tickIndex < positiveTickBoundary) {\n      throw Error(\"checkExtensionBoundary -> InvalidTickArrayBoundary\");\n    }\n  }\n\n  public static extensionTickBoundary(tickSpacing: number): {\n    positiveTickBoundary: number;\n    negativeTickBoundary: number;\n  } {\n    const positiveTickBoundary = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n\n    const negativeTickBoundary = -positiveTickBoundary;\n\n    if (MAX_TICK <= positiveTickBoundary)\n      throw Error(`extensionTickBoundary check error: ${MAX_TICK}, ${positiveTickBoundary}`);\n    if (negativeTickBoundary <= MIN_TICK)\n      throw Error(`extensionTickBoundary check error: ${negativeTickBoundary}, ${MIN_TICK}`);\n\n    return { positiveTickBoundary, negativeTickBoundary };\n  }\n\n  public static checkTickArrayIsInit(\n    tickArrayStartIndex: number,\n    tickSpacing: number,\n    tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n  ): { isInitialized: boolean; startIndex: number } {\n    const { tickarrayBitmap } = this.getBitmap(tickArrayStartIndex, tickSpacing, tickArrayBitmapExtension);\n\n    const tickArrayOffsetInBitmap = this.tickArrayOffsetInBitmap(tickArrayStartIndex, tickSpacing);\n\n    return {\n      isInitialized: TickUtils.mergeTickArrayBitmap(tickarrayBitmap).testn(tickArrayOffsetInBitmap),\n      startIndex: tickArrayStartIndex,\n    };\n  }\n\n  public static nextInitializedTickArrayFromOneBitmap(\n    lastTickArrayStartIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n    tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n  ): {\n    isInit: boolean;\n    tickIndex: number;\n  } {\n    const multiplier = TickQuery.tickCount(tickSpacing);\n    const nextTickArrayStartIndex = zeroForOne\n      ? lastTickArrayStartIndex - multiplier\n      : lastTickArrayStartIndex + multiplier;\n    const { tickarrayBitmap } = this.getBitmap(nextTickArrayStartIndex, tickSpacing, tickArrayBitmapExtension);\n\n    return this.nextInitializedTickArrayInBitmap(tickarrayBitmap, nextTickArrayStartIndex, tickSpacing, zeroForOne);\n  }\n\n  public static nextInitializedTickArrayInBitmap(\n    tickarrayBitmap: BN[],\n    nextTickArrayStartIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n  ): {\n    isInit: boolean;\n    tickIndex: number;\n  } {\n    const { minValue: bitmapMinTickBoundary, maxValue: bitmapMaxTickBoundary } = TickArrayBitmap.getBitmapTickBoundary(\n      nextTickArrayStartIndex,\n      tickSpacing,\n    );\n\n    const tickArrayOffsetInBitmap = this.tickArrayOffsetInBitmap(nextTickArrayStartIndex, tickSpacing);\n    if (zeroForOne) {\n      // tick from upper to lower\n      // find from highter bits to lower bits\n      const offsetBitMap = TickUtils.mergeTickArrayBitmap(tickarrayBitmap).shln(\n        TICK_ARRAY_BITMAP_SIZE - 1 - tickArrayOffsetInBitmap,\n      );\n\n      const nextBit = isZero(512, offsetBitMap) ? null : leadingZeros(512, offsetBitMap);\n\n      if (nextBit !== null) {\n        const nextArrayStartIndex = nextTickArrayStartIndex - nextBit * TickQuery.tickCount(tickSpacing);\n        return { isInit: true, tickIndex: nextArrayStartIndex };\n      } else {\n        // not found til to the end\n        return { isInit: false, tickIndex: bitmapMinTickBoundary };\n      }\n    } else {\n      // tick from lower to upper\n      // find from lower bits to highter bits\n      const offsetBitMap = TickUtils.mergeTickArrayBitmap(tickarrayBitmap).shrn(tickArrayOffsetInBitmap);\n\n      const nextBit = isZero(512, offsetBitMap) ? null : trailingZeros(512, offsetBitMap);\n\n      if (nextBit !== null) {\n        const nextArrayStartIndex = nextTickArrayStartIndex + nextBit * TickQuery.tickCount(tickSpacing);\n        return { isInit: true, tickIndex: nextArrayStartIndex };\n      } else {\n        // not found til to the end\n        return { isInit: false, tickIndex: bitmapMaxTickBoundary - TickQuery.tickCount(tickSpacing) };\n      }\n    }\n  }\n\n  public static tickArrayOffsetInBitmap(tickArrayStartIndex: number, tickSpacing: number): number {\n    const m = Math.abs(tickArrayStartIndex) % TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n    let tickArrayOffsetInBitmap = Math.floor(m / TickQuery.tickCount(tickSpacing));\n    if (tickArrayStartIndex < 0 && m != 0) {\n      tickArrayOffsetInBitmap = TICK_ARRAY_BITMAP_SIZE - tickArrayOffsetInBitmap;\n    }\n    return tickArrayOffsetInBitmap;\n  }\n}\n","import { blob, bool, i128, i64, publicKey, s32, seq, struct, u128, u16, u32, u64, u8 } from \"../../marshmallow\";\n\nimport { TICK_ARRAY_SIZE } from \"./utils/tick\";\nimport { EXTENSION_TICKARRAY_BITMAP_SIZE } from \"./utils/tickarrayBitmap\";\n\nexport const ClmmConfigLayout = struct([\n  blob(8),\n  u8(\"bump\"),\n  u16(\"index\"),\n  publicKey(\"\"),\n  u32(\"protocolFeeRate\"),\n  u32(\"tradeFeeRate\"),\n  u16(\"tickSpacing\"),\n  seq(u64(), 8, \"\"),\n]);\n\nexport const ObservationLayout = struct([u32(\"blockTimestamp\"), i64(\"tickCumulative\"), seq(u64(), 4)]);\nexport const ObservationInfoLayout = struct([\n  blob(8),\n  bool(\"initialized\"),\n  u64(\"recentEpoch\"),\n  u16(\"observationIndex\"),\n  publicKey(\"poolId\"),\n  seq(ObservationLayout, 100, \"observations\"),\n  seq(u64(), 4),\n]);\n\nexport const RewardInfo = struct([\n  u8(\"rewardState\"),\n  u64(\"openTime\"),\n  u64(\"endTime\"),\n  u64(\"lastUpdateTime\"),\n  u128(\"emissionsPerSecondX64\"),\n  u64(\"rewardTotalEmissioned\"),\n  u64(\"rewardClaimed\"),\n  publicKey(\"tokenMint\"),\n  publicKey(\"tokenVault\"),\n  publicKey(\"creator\"),\n  u128(\"rewardGrowthGlobalX64\"),\n]);\nexport const PoolInfoLayout = struct([\n  blob(8),\n  u8(\"bump\"),\n  publicKey(\"ammConfig\"),\n  publicKey(\"creator\"),\n  publicKey(\"mintA\"),\n  publicKey(\"mintB\"),\n  publicKey(\"vaultA\"),\n  publicKey(\"vaultB\"),\n  publicKey(\"observationId\"),\n  u8(\"mintDecimalsA\"),\n  u8(\"mintDecimalsB\"),\n  u16(\"tickSpacing\"),\n  u128(\"liquidity\"),\n  u128(\"sqrtPriceX64\"),\n  s32(\"tickCurrent\"),\n  u32(),\n  u128(\"feeGrowthGlobalX64A\"),\n  u128(\"feeGrowthGlobalX64B\"),\n  u64(\"protocolFeesTokenA\"),\n  u64(\"protocolFeesTokenB\"),\n\n  u128(\"swapInAmountTokenA\"),\n  u128(\"swapOutAmountTokenB\"),\n  u128(\"swapInAmountTokenB\"),\n  u128(\"swapOutAmountTokenA\"),\n\n  u8(\"status\"),\n\n  seq(u8(), 7, \"\"),\n\n  seq(RewardInfo, 3, \"rewardInfos\"),\n  seq(u64(), 16, \"tickArrayBitmap\"),\n\n  u64(\"totalFeesTokenA\"),\n  u64(\"totalFeesClaimedTokenA\"),\n  u64(\"totalFeesTokenB\"),\n  u64(\"totalFeesClaimedTokenB\"),\n\n  u64(\"fundFeesTokenA\"),\n  u64(\"fundFeesTokenB\"),\n\n  u64(\"startTime\"),\n\n  seq(u64(), 15 * 4 - 3, \"padding\"),\n]);\n\nexport const PositionRewardInfoLayout = struct([u128(\"growthInsideLastX64\"), u64(\"rewardAmountOwed\")]);\nexport const PositionInfoLayout = struct([\n  blob(8),\n  u8(\"bump\"),\n  publicKey(\"nftMint\"),\n  publicKey(\"poolId\"),\n\n  s32(\"tickLower\"),\n  s32(\"tickUpper\"),\n  u128(\"liquidity\"),\n  u128(\"feeGrowthInsideLastX64A\"),\n  u128(\"feeGrowthInsideLastX64B\"),\n  u64(\"tokenFeesOwedA\"),\n  u64(\"tokenFeesOwedB\"),\n\n  seq(PositionRewardInfoLayout, 3, \"rewardInfos\"),\n\n  seq(u64(), 8, \"\"),\n]);\n\nexport type ClmmPositionLayout = ReturnType<typeof PositionInfoLayout.decode>;\n\nexport const ProtocolPositionLayout = struct([\n  blob(8),\n  u8(\"bump\"),\n  publicKey(\"poolId\"),\n  s32(\"tickLowerIndex\"),\n  s32(\"tickUpperIndex\"),\n  u128(\"liquidity\"),\n  u128(\"feeGrowthInsideLastX64A\"),\n  u128(\"feeGrowthInsideLastX64B\"),\n  u64(\"tokenFeesOwedA\"),\n  u64(\"tokenFeesOwedB\"),\n  seq(u128(), 3, \"rewardGrowthInside\"),\n\n  seq(u64(), 8, \"\"),\n]);\n\nexport const TickLayout = struct([\n  s32(\"tick\"),\n  i128(\"liquidityNet\"),\n  u128(\"liquidityGross\"),\n  u128(\"feeGrowthOutsideX64A\"),\n  u128(\"feeGrowthOutsideX64B\"),\n  seq(u128(), 3, \"rewardGrowthsOutsideX64\"),\n\n  seq(u32(), 13, \"\"),\n]);\n\nexport const TickArrayLayout = struct([\n  blob(8),\n  publicKey(\"poolId\"),\n  s32(\"startTickIndex\"),\n  seq(TickLayout, TICK_ARRAY_SIZE, \"ticks\"),\n  u8(\"initializedTickCount\"),\n\n  seq(u8(), 115, \"\"),\n]);\n\nexport const OperationLayout = struct([blob(329), seq(publicKey(), 100, \"whitelistMints\")]);\n\nexport const TickArrayBitmapExtensionLayout = struct([\n  blob(8),\n  publicKey(\"poolId\"),\n  seq(seq(u64(), 8), EXTENSION_TICKARRAY_BITMAP_SIZE, \"positiveTickArrayBitmap\"),\n  seq(seq(u64(), 8), EXTENSION_TICKARRAY_BITMAP_SIZE, \"negativeTickArrayBitmap\"),\n]);\n\nexport const LockPositionLayout = struct([\n  u64(),\n  u8(\"bump\"),\n  publicKey(\"owner\"),\n  publicKey(\"poolId\"),\n  publicKey(\"positionId\"),\n  publicKey(\"nftAccount\"),\n  seq(u64(), 8),\n]);\n\nexport const LockClPositionLayoutV2 = struct([\n  blob(8),\n  u8(\"bump\"),\n  publicKey(\"lockOwner\"),\n  publicKey(\"poolId\"),\n  publicKey(\"positionId\"),\n  publicKey(\"nftAccount\"),\n  publicKey(\"lockNftMint\"),\n  u64(\"recentEpoch\"),\n  seq(u64(), 8),\n]);\n","import { blob, bool, publicKey, seq, struct, u16, u64, u8, u128 } from \"../../marshmallow\";\n\nexport const CpmmConfigInfoLayout = struct([\n  blob(8),\n  u8(\"bump\"),\n  bool(\"disableCreatePool\"),\n  u16(\"index\"),\n  u64(\"tradeFeeRate\"),\n  u64(\"protocolFeeRate\"),\n  u64(\"fundFeeRate\"),\n  u64(\"createPoolFee\"),\n\n  publicKey(\"protocolOwner\"),\n  publicKey(\"fundOwner\"),\n  seq(u64(), 16),\n]);\n\nexport const CpmmPoolInfoLayout = struct([\n  blob(8),\n\n  publicKey(\"configId\"),\n  publicKey(\"poolCreator\"),\n  publicKey(\"vaultA\"),\n  publicKey(\"vaultB\"),\n\n  publicKey(\"mintLp\"),\n  publicKey(\"mintA\"),\n  publicKey(\"mintB\"),\n\n  publicKey(\"mintProgramA\"),\n  publicKey(\"mintProgramB\"),\n\n  publicKey(\"observationId\"),\n\n  u8(\"bump\"),\n  u8(\"status\"),\n\n  u8(\"lpDecimals\"),\n  u8(\"mintDecimalA\"),\n  u8(\"mintDecimalB\"),\n\n  u64(\"lpAmount\"),\n  u64(\"protocolFeesMintA\"),\n  u64(\"protocolFeesMintB\"),\n  u64(\"fundFeesMintA\"),\n  u64(\"fundFeesMintB\"),\n  u64(\"openTime\"),\n\n  seq(u64(), 32),\n]);\n"],"mappings":"AAAA,OAAS,aAAAA,MAAiB,kBAE1B,OAAS,iBAAAC,GAAe,eAAAC,GAAa,oBAAAC,OAAwB,oBCF7D,OAAOC,OAAQ,QACf,OAAOC,OAAa,aCDpB,OAAOC,OAAU,SACjB,OAAOC,OAAQ,QCDf,OAAS,OAAAC,GAAK,OAAAC,OAAW,SAUlB,IAAMC,GAAN,KAAa,CAGlB,YAAYC,EAA+C,CACzD,KAAK,SAAWA,EAAO,WAAa,OAAYA,EAAO,SAAW,EAClE,KAAK,KAAOA,EAAO,IACrB,CAEA,IAAI,MAAMC,EAAoB,CAC5B,KAAK,SAAWA,CAClB,CACA,IAAI,MAAe,CACjB,OAAO,KAAK,IAAI,EAAE,SAAS,CAC7B,CACA,IAAI,YAAqB,CACvB,OAAO,KAAK,IACd,CAEQ,WAAWC,EAA0B,CAC3C,OAAOA,GAAS,KAAK,QACvB,CAEO,SAASC,EAAe,CAC7B,OAAK,KAAK,WAAW,CAAc,GACnC,QAAQ,MAAM,KAAK,KAAM,KAAK,KAAM,mBAAoB,GAAGA,CAAK,EACzD,MAFsC,IAG/C,CAEO,gBAAgBA,EAAe,CAEpC,IAAMC,EAAMD,EAAM,IAAKE,GAAS,OAAOA,GAAQ,SAAW,KAAK,UAAUA,CAAG,EAAIA,C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0D,EAASG,EAAS,QAAU,SAAS,WAAW,UAChDyB,EACA,EACF,EAEA,YAAK,SACH,iBACA+C,EAAiB,OAAO,SAAS,EACjC,qBACAN,GAAA9B,EAAAoC,EAAiB,MAAjB,YAAApC,EAAsB,aAAtB,KAAA8B,EAAoC,EACpC,oBACAW,EAAuB,OAAO,SAAS,EACvC,wBACAT,GAAAD,EAAAU,EAAuB,MAAvB,YAAAV,EAA4B,aAA5B,KAAAC,EAA0C,CAC5C,EAEO,CACL,eAAA5D,EACA,cAAegE,EACf,iBAAkBK,EAClB,iBAAkBC,EAClB,UAAAvE,CACF,CACF,CACF,EAEA,SAASoE,GAAWI,EAAQC,EAAiBC,EAAiBC,EAA0C,CACtG,IAAIC,EAAUJ,EAAG,IAAIC,CAAW,EAAE,IAAIE,CAAM,EACxC,CAACC,EAAQ,OAAO,GAAK,CAACJ,EAAG,IAAIC,CAAW,EAAE,IAAIE,CAAM,EAAE,OAAO,IAAGC,EAAUA,EAAQ,IAAI,IAAIhJ,EAAG,CAAC,CAAC,GACnG,IAAIiJ,EAAUL,EAAG,IAAIE,CAAW,EAAE,IAAIC,CAAM,EAC5C,MAAI,CAACE,EAAQ,OAAO,GAAK,CAACL,EAAG,IAAIE,CAAW,EAAE,IAAIC,CAAM,EAAE,OAAO,IAAGE,EAAUA,EAAQ,IAAI,IAAIjJ,EAAG,CAAC,CAAC,GAE5F,CACL,QAAAgJ,EACA,QAAAC,CACF,CACF","names":["PublicKey","AccountLayout","NATIVE_MINT","TOKEN_PROGRAM_ID","BN","Decimal","_Big","BN","get","set","Logger","params","logLevel","level","props","msg","arg","moduleLoggers","moduleLevels","createLogger","moduleName","logger","get","set","PublicKey","MINT_SIZE","TOKEN_PROGRAM_ID","getTransferFeeConfig","unpackMint","logger","createLogger","getMultipleAccountsInfo","connection","publicKeys","config","batchRequest","commitment","chunkCount","chunkedKeys","chunkArray","results","batch","keys","args","key","_batch","i","unsafeRes","accountInfo","data","executable","lamports","owner","rentEpoch","PublicKey","error","getMultipleAccountsInfoWithCustomFlags","publicKeysWithCustomFlag","multipleAccountsInfo","o","idx","fetchMultipleMintInfos","connection","mints","config","_a","_b","_c","mintInfos","getMultipleAccountsInfoWithCustomFlags","i","solToWSol","mintK","MINT_SIZE","t","unpackMint","TOKEN_PROGRAM_ID","getTransferFeeConfig","PublicKey","WSOLMint","BN","MAX_SAFE","parseBigNumberish","value","logger","createLogger","BN","PublicKey","TOKEN_PROGRAM_ID","SOL_INFO","TOKEN_WSOL","PublicKey","PublicKey","SystemProgram","SYSVAR_RENT_PUBKEY","TOKEN_PROGRAM_ID","accountMeta","pubkey","isSigner","isWritable","commonSystemAccountMeta","validateAndParsePublicKey","orgPubKey","transformSol","publicKey","tryParsePublicKey","SOLMint","WSOLMint","v","MEMO_PROGRAM_ID","MEMO_PROGRAM_ID2","RENT_PROGRAM_ID","CLOCK_PROGRAM_ID","METADATA_PROGRAM_ID","INSTRUCTION_PROGRAM_ID","SYSTEM_PROGRAM_ID","RAYMint","PAIMint","SRMMint","USDCMint","USDTMint","mSOLMint","stSOLMint","USDHMint","NRVMint","ANAMint","ETHMint","solToWSol","mint","_Token","mint","decimals","symbol","name","skipMint","isToken2022","SOLMint","PublicKey","TOKEN_WSOL","validateAndParsePublicKey","other","Token","_Currency","decimals","symbol","name","other","Currency","SOL_INFO","_toFarmat","toFormat","formatter_default","_Big","BN","_Decimal","logger","createLogger","Big","formatter_default","_Big","Decimal","_Decimal","toSignificantRounding","toFixedRounding","Fraction","numerator","denominator","BN","parseBigNumberish","other","otherParsed","significantDigits","format","rounding","quotient","decimalPlaces","BN","_100_PERCENT","Fraction","BN","Percent","significantDigits","format","rounding","decimalPlaces","logger","createLogger","chunkArray","arr","chunkSize","cache","tmp","PublicKey","TOKEN_PROGRAM_ID","ComputeBudgetProgram","Keypair","PublicKey","Transaction","TransactionMessage","VersionedTransaction","InstructionType","TOKEN_PROGRAM_ID","logger","createLogger","MAX_BASE64_SIZE","addComputeBudget","config","ins","insTypes","ComputeBudgetProgram","InstructionType","getRecentBlockHash","connection","propsCommitment","_a","_b","commitment","confirmTransaction","txId","resolve","reject","id","signatureResult","forecastTransactionSize","instructions","signers","transaction","Transaction","findProgramAddress","seeds","programId","publicKey","nonce","PublicKey","checkLegacyTxSize","instructions","payer","signers","forecastTransactionSize","checkV0TxSize","lookupTableAddressAccount","recentBlockhash","Keypair","messageV0","TransactionMessage","VersionedTransaction","MAX_BASE64_SIZE","toBuffer","arr","txToBase64","transaction","serialized","VersionedTransaction","printSimulate","transactions","allBase64","Transaction","TOKEN_PROGRAM_ID","Keypair","getATAAddress","owner","mint","programId","findProgramAddress","TOKEN_PROGRAM_ID","PublicKey","PublicKey","FARM_PROGRAM_ID_V3","FARM_PROGRAM_ID_V4","FARM_PROGRAM_ID_V5","FARM_PROGRAM_ID_V6","UTIL1216","OPEN_BOOK_PROGRAM","SERUM_PROGRAM_ID_V3","AMM_V4","AMM_STABLE","LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL","CLMM_PROGRAM_ID","CLMM_LOCK_PROGRAM_ID","CLMM_LOCK_AUTH_ID","Router","FEE_DESTINATION_ID","IDO_PROGRAM_ID_V1","IDO_PROGRAM_ID_V2","IDO_PROGRAM_ID_V3","IDO_PROGRAM_ID_V4","CREATE_CPMM_POOL_PROGRAM","CREATE_CPMM_POOL_AUTH","CREATE_CPMM_POOL_FEE_ACC","DEV_CREATE_CPMM_POOL_PROGRAM","DEV_CREATE_CPMM_POOL_AUTH","DEV_CREATE_CPMM_POOL_FEE_ACC","LOCK_CPMM_PROGRAM","DEV_LOCK_CPMM_PROGRAM","LOCK_CPMM_AUTH","DEV_LOCK_CPMM_AUTH","LAUNCHPAD_PROGRAM","LAUNCHPAD_AUTH","DEV_LAUNCHPAD_PROGRAM","DEV_LAUNCHPAD_AUTH","DEVNET_PROGRAM_ID","PublicKey","DEV_CREATE_CPMM_POOL_PROGRAM","DEV_CREATE_CPMM_POOL_AUTH","DEV_CREATE_CPMM_POOL_FEE_ACC","DEV_LOCK_CPMM_PROGRAM","DEV_LOCK_CPMM_AUTH","DEV_LAUNCHPAD_PROGRAM","DEV_LAUNCHPAD_AUTH","BN","POINT","getTransferAmountFeeV2","amount","_feeConfig","epochInfo","addFee","feeConfig","nowFeeConfig","maxFee","BN","expirationTime","POINT","nowMaxFee","_TAmount","BNDivCeil","TAmount","_fee","fee","BNDivCeil","bn1","bn2","div","mod","BN","PublicKey","AddressLookupTableAccount","getMultipleLookupTableInfo","connection","address","dataInfos","getMultipleAccountsInfo","i","PublicKey","outDict","info","key","lookupAccount","AddressLookupTableAccount","LOOKUP_TABLE_CACHE","PublicKey","sendAndConfirmTransaction","SystemProgram","Transaction","TransactionMessage","VersionedTransaction","axios","LOOP_INTERVAL","TxBuilder","params","_a","json","axios","avg","config","instructions","instructionTypes","addComputeBudget","tipConfig","SystemProgram","PublicKey","InstructionType","propConfig","defaultIns","endInstructions","signers","endInstructionTypes","lookupTableAddress","address","txVersion","extInfo","transaction","Transaction","s","propBlockHash","skipPreflight","sendAndConfirm","notSendToRpc","recentBlockHash","getRecentBlockHash","printSimulate","sendAndConfirmTransaction","txs","item","extraPreBuildData","filterExtraBuildData","data","allTransactions","allSigners","allInstructionTypes","executeParams","sequentially","onTxUpdate","skipTxCount","txIds","i","tx","txId","partialSignedTxs","idx","signedTxs","processedTxs","checkSendTx","confirmed","intervalId","subSignatureId","cbk","signatureResult","targetTxIdx","r","e","result","d","props","lookupTableCache","forerunCreate","propRecentBlockhash","lookupTableAddressAccount","LOOKUP_TABLE_CACHE","allLTA","needCacheLTA","newCacheLTA","getMultipleLookupTableInfo","key","value","recentBlockhash","messageV0","TransactionMessage","VersionedTransaction","confirmTransaction","buildProps","splitIns","computeBudgetConfig","computeBudgetData","signerKey","acc","cur","instructionQueue","splitInsIdx","_itemIns","_itemInsWithCompute","_signer","ii","checkLegacyTxSize","_signers","needSignedTx","blockHash","checkV0TxSize","PublicKey","BN","BN","FEE_RATE_DENOMINATOR_VALUE","logger","createLogger","Big","formatter_default","_Big","BN_ZERO","BN","BN_ONE","BN_TWO","BN_THREE","BN_FIVE","BN_TEN","BN_100","BN_1000","BN_10000","ceilDiv","tokenAmount","feeNumerator","feeDenominator","BN","floorDiv","BN","Decimal","BN","checkedRem","dividend","divisor","checkedCeilDiv","rhs","quotient","remainder","ZERO","BN","ConstantProductCurve","sourceAmount","swapSourceAmount","swapDestinationAmount","invariant","newSwapSourceAmount","newSwapDestinationAmount","destinationAmountSwapped","lpTokenAmount","lpTokenSupply","swapTokenAmount0","swapTokenAmount1","roundDirection","tokenAmount0","tokenAmount1","CpmmFee","amount","tradeFeeRate","ceilDiv","FEE_RATE_DENOMINATOR_VALUE","protocolFeeRate","floorDiv","fundFeeRate","CurveCalculator","tokenAmount0","tokenAmount1","sourceAmount","swapSourceAmount","swapDestinationAmount","tradeFeeRate","tradeFee","CpmmFee","sourceAmountLessFees","destinationAmountSwapped","ConstantProductCurve","poolMintA","poolMintB","baseReserve","quoteReserve","outputMint","outputAmount","reserveInAmount","reserveOutAmount","reserveInDecimals","reserveOutDecimals","inputMint","currentPrice","Decimal","amountRealOut","BN","denominator","amountInWithoutFee","BNDivCeil","amountIn","fee","executionPrice","priceImpact","BN","Decimal","joinMsg","args","arg","ModuleBase","scope","moduleName","createLogger","feePayer","TxBuilder","message","PublicKey","BN","isBN","_bits","_BitStructure","_blob","_Blob","_cstr","_f32","_f32be","_f64","_f64be","_greedy","_Layout","_ns64","_ns64be","_nu64","_nu64be","_offset","_s16","_s16be","_s24","_s24be","_s32","_s32be","_s40","_s40be","_s48","_s48be","_s8","_seq","_struct","_Structure","_u16","_u16be","_u24","_u24be","_u32","_u32be","_u40","_u40be","_u48","_u48be","_u8","_UInt","_union","_Union","_unionLayoutDiscriminator","_utf8","Layout","Structure","UInt","_UInt","u8","_u8","u16","_u16","s32","_s32","seq","_seq","blob","_blob","BNLayout","Layout","span","signed","property","blob","b","offset","num","BN","src","u8","property","UInt","u32","u64","BNLayout","u128","i64","property","BNLayout","i128","WrappedLayout","Layout","layout","decoder","encoder","b","offset","src","publicKey","blob","PublicKey","key","bool","property","WrappedLayout","u8","decodeBool","encodeBool","value","Structure","b","offset","struct","fields","property","decodePrefixes","seq","elementLayout","count","property","parsedCount","superCount","isBN","target","countProperty","value","SPL_MINT_LAYOUT","struct","u32","publicKey","u64","u8","PublicKey","MintLayout","TOKEN_PROGRAM_ID","toApiV3Token","address","programId","decimals","props","solToWSol","toFeeConfig","config","PublicKey","TransactionInstruction","Keypair","SystemProgram","ASSOCIATED_TOKEN_PROGRAM_ID","TOKEN_2022_PROGRAM_ID","TOKEN_PROGRAM_ID","AUTH_SEED","AMM_CONFIG_SEED","POOL_SEED","POOL_LP_MINT_SEED","POOL_VAULT_SEED","OBSERVATION_SEED","getPdaPoolAuthority","programId","findProgramAddress","getCpmmPdaPoolId","programId","ammConfigId","mintA","mintB","findProgramAddress","POOL_SEED","getPdaLpMint","poolId","POOL_LP_MINT_SEED","getPdaVault","mint","POOL_VAULT_SEED","getPdaObservationId","OBSERVATION_SEED","getCreatePoolKeys","propPoolId","programId","configId","mintA","mintB","authority","getPdaPoolAuthority","poolId","getCpmmPdaPoolId","lpMint","getPdaLpMint","vaultA","getPdaVault","vaultB","observationId","getPdaObservationId","LOCK_LIQUIDITY_SEED","getCpLockPda","mint","findProgramAddress","PublicKey","BN","Decimal","AccountLayout","TOKEN_2022_PROGRAM_ID","TOKEN_PROGRAM_ID","Keypair","PublicKey","SystemProgram","TransactionInstruction","BN","ASSOCIATED_TOKEN_PROGRAM_ID","TOKEN_2022_PROGRAM_ID","TOKEN_PROGRAM_ID","BN","Decimal","BN","ZERO","ONE","NEGATIVE_ONE","Q64","Q128","MaxU64","MaxUint128","Q128","MIN_TICK","MAX_TICK","MIN_SQRT_PRICE_X64","BN","MAX_SQRT_PRICE_X64","MIN_SQRT_PRICE_X64_ADD_ONE","MAX_SQRT_PRICE_X64_SUB_ONE","FEE_RATE_DENOMINATOR","BN","U64_IGNORE_RANGE","BN","BN","Decimal","AMM_CONFIG_SEED","POOL_SEED","POOL_VAULT_SEED","POOL_REWARD_VAULT_SEED","POSITION_SEED","TICK_ARRAY_SEED","OPERATION_SEED","POOL_TICK_ARRAY_BITMAP_SEED","OBSERVATION_SEED","getPdaMetadataKey","mint","findProgramAddress","METADATA_PROGRAM_ID","POOL_LOCK_ID_SEED","SUPPORT_MINT_SEED","PublicKey","TOKEN_2022_PROGRAM_ID","BN","Decimal","BN","Decimal","EXTENSION_TICKARRAY_BITMAP_SIZE","TICK_ARRAY_SIZE","ClmmConfigLayout","struct","blob","u8","u16","publicKey","u32","seq","u64","ObservationLayout","i64","ObservationInfoLayout","bool","RewardInfo","u128","PoolInfoLayout","s32","PositionRewardInfoLayout","PositionInfoLayout","ProtocolPositionLayout","TickLayout","i128","TickArrayLayout","TICK_ARRAY_SIZE","OperationLayout","TickArrayBitmapExtensionLayout","EXTENSION_TICKARRAY_BITMAP_SIZE","LockPositionLayout","LockClPositionLayoutV2","ObservationInfoLayout","logger","createLogger","logger","createLogger","anchorDataBuf","makeCreateCpmmPoolInInstruction","programId","creator","configId","authority","poolId","mintA","mintB","lpMint","userVaultA","userVaultB","userLpAccount","vaultA","vaultB","createPoolFeeAccount","mintProgramA","mintProgramB","observationId","amountMaxA","amountMaxB","openTime","dataLayout","struct","u64","pdaPoolId","getCpmmPdaPoolId","keys","TOKEN_PROGRAM_ID","ASSOCIATED_TOKEN_PROGRAM_ID","SYSTEM_PROGRAM_ID","RENT_PROGRAM_ID","data","TransactionInstruction","makeDepositCpmmInInstruction","owner","lpAmount","TOKEN_2022_PROGRAM_ID","makeWithdrawCpmmInInstruction","amountMinA","amountMinB","MEMO_PROGRAM_ID2","makeSwapCpmmBaseInInstruction","payer","userInputAccount","userOutputAccount","inputVault","outputVault","inputTokenProgram","outputTokenProgram","inputMint","outputMint","amountIn","amounOutMin","makeSwapCpmmBaseOutInstruction","amountInMax","amountOut","makeCpmmLockInstruction","props","_a","ownerInfo","poolInfo","poolKeys","feeNftOwner","getEphemeralSigners","signers","PublicKey","nftMintAccount","_k","Keypair","nftAccount","getATAAddress","metadataAccount","getPdaMetadataKey","lockPda","getCpLockPda","userLpVault","lockLpVault","ins","cpmmLockPositionInstruction","InstructionType","auth","liquidityOwner","nftOwner","nftMint","mintLp","poolVaultA","poolVaultB","withMetadata","SystemProgram","METADATA_PROGRAM_ID","bool","aData","collectCpFeeInstruction","lpFeeAmount","cpmmProgram","cpmmAuthProgram","CREATE_CPMM_POOL_PROGRAM","CREATE_CPMM_POOL_AUTH","CpmmConfigInfoLayout","struct","blob","u8","bool","u16","u64","publicKey","seq","CpmmPoolInfoLayout","CpmmModule","ModuleBase","params","poolId","fetchConfigInfo","poolIds","accounts","getMultipleAccountsInfoWithCustomFlags","i","PublicKey","poolInfos","needFetchConfigId","needFetchVaults","item","rpc","CpmmPoolInfoLayout","configInfo","configIds","configState","configItemInfo","CpmmConfigInfoLayout","vaultInfo","vaultAccountInfo","vaultItemInfo","BN","AccountLayout","returnData","id","info","baseReserve","quoteReserve","Decimal","pools","mintInfos","acc","cur","_a","_b","_c","_d","pool","mintA","mintB","getPdaPoolAuthority","toApiV3Token","toFeeConfig","rpcData","fetchMultipleMintInfos","lpMint","TOKEN_PROGRAM_ID","mockRewardData","getPdaObservationId","programId","poolFeeAccount","startTime","ownerInfo","associatedOnly","checkCreateATAOwner","txVersion","feeConfig","computeBudgetConfig","txTipConfig","feePayer","payer","isFront","mintAAmount","mintBAmount","mintAUseSOLBalance","NATIVE_MINT","mintBUseSOLBalance","mintAPubkey","mintBPubkey","txBuilder","userVaultA","userVaultAInstruction","userVaultB","userVaultBInstruction","poolKeys","getCreatePoolKeys","makeCreateCpmmPoolInInstruction","getATAAddress","InstructionType","poolInfo","propPoolKeys","inputAmount","baseIn","slippage","computeResult","config","account","bypassAssociatedCheck","rpcPoolData","liquidity","inputAmountFee","_anotherAmount","Percent","anotherAmount","tokenAccountA","_tokenAccountAInstruction","tokenAccountB","_tokenAccountBInstruction","lpTokenAccount","_lpTokenAccount","lpInstruction","_slippage","makeDepositCpmmInInstruction","lpAmount","closeWsol","amountMintA","amountMintB","epochInfo","mintAAmountFee","mintBAmountFee","getTransferAmountFeeV2","WSOLMint","_ownerTokenAccountA","accountAInstructions","_ownerTokenAccountB","accountBInstructions","makeWithdrawCpmmInInstruction","_e","_f","fixedOut","swapResult","mintATokenAcc","mintATokenAccInstruction","mintBTokenAcc","mintBTokenAccInstruction","makeSwapCpmmBaseOutInstruction","makeSwapCpmmBaseInInstruction","feeNftOwner","insData","makeCpmmLockInstruction","LOCK_CPMM_PROGRAM","LOCK_CPMM_AUTH","lpFeeAmount","nftMint","authProgram","cpmmProgram","nftAccount","lockPda","getCpLockPda","lockLpVault","collectCpFeeInstruction","amountIn","outputMint","isBaseIn","CurveCalculator","executionPrice","minAmountOut","amount","_g","_h","_i","coefficient","_inputAmountWithoutFee","input","anotherAmountFee","BN_ZERO","lpAmountData","lpToAmount","_slippageMin","slippageAdjustedAmount","slippageAdjustedMinAmount","lp","poolAmountA","poolAmountB","supply","amountA","amountB"]}