{"version":3,"sources":["../../src/raydium/raydium.ts","../../src/api/api.ts","../../src/common/logger.ts","../../src/common/utility.ts","../../src/module/amount.ts","../../src/common/bignumber.ts","../../node_modules/decimal.js/decimal.mjs","../../src/module/token.ts","../../src/common/pubKey.ts","../../src/raydium/token/constant.ts","../../src/module/fraction.ts","../../src/module/formatter.ts","../../src/module/price.ts","../../src/module/currency.ts","../../src/module/percent.ts","../../src/common/txTool/txTool.ts","../../src/common/txTool/txType.ts","../../src/common/txTool/txUtils.ts","../../src/common/txTool/lookupTable.ts","../../src/common/accountInfo.ts","../../src/common/owner.ts","../../src/common/lodash.ts","../../src/common/programId.ts","../../src/common/pda.ts","../../src/common/transfer.ts","../../src/api/url.ts","../../src/api/utils.ts","../../src/common/error.ts","../../src/raydium/account/account.ts","../../src/raydium/moduleBase.ts","../../src/raydium/account/instruction.ts","../../src/raydium/account/util.ts","../../src/marshmallow/index.ts","../../src/marshmallow/buffer-layout.ts","../../src/raydium/account/layout.ts","../../node_modules/@noble/hashes/src/_assert.ts","../../node_modules/@noble/hashes/src/utils.ts","../../node_modules/@noble/hashes/src/_md.ts","../../node_modules/@noble/hashes/src/sha256.ts","../../src/raydium/farm/farm.ts","../../src/raydium/farm/config.ts","../../src/raydium/farm/layout.ts","../../src/raydium/farm/instruction.ts","../../src/raydium/farm/util.ts","../../src/raydium/liquidity/liquidity.ts","../../src/raydium/token/layout.ts","../../src/raydium/token/utils.ts","../../src/raydium/liquidity/instruction.ts","../../src/raydium/liquidity/layout.ts","../../src/raydium/liquidity/stable.ts","../../src/raydium/clmm/instrument.ts","../../src/raydium/clmm/utils/tick.ts","../../src/raydium/clmm/utils/util.ts","../../src/raydium/clmm/utils/pda.ts","../../src/raydium/clmm/utils/constants.ts","../../src/raydium/clmm/utils/tickQuery.ts","../../src/raydium/clmm/utils/math.ts","../../src/raydium/clmm/utils/pool.ts","../../src/raydium/clmm/utils/tickarrayBitmap.ts","../../src/raydium/clmm/utils/position.ts","../../src/raydium/clmm/layout.ts","../../src/raydium/liquidity/utils.ts","../../src/raydium/liquidity/serum.ts","../../src/raydium/liquidity/constant.ts","../../src/raydium/clmm/clmm.ts","../../src/raydium/tradeV2/trade.ts","../../src/raydium/tradeV2/instrument.ts","../../src/raydium/utils1216/utils1216.ts","../../src/raydium/marketV2/createMarket.ts","../../src/raydium/marketV2/instrument.ts","../../src/raydium/marketV2/layout.ts","../../src/raydium/ido/ido.ts","../../src/raydium/ido/instruction.ts","../../src/raydium/ido/layout.ts","../../src/raydium/token/token.ts"],"sourcesContent":["import { Connection, Keypair, PublicKey, EpochInfo } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { merge } from \"lodash\";\n\nimport { Api, API_URL_CONFIG, ApiV3TokenRes, ApiV3Token, JupTokenType, AvailabilityCheckAPI3 } from \"../api\";\nimport { EMPTY_CONNECTION, EMPTY_OWNER } from \"../common/error\";\nimport { createLogger, Logger } from \"../common/logger\";\nimport { Owner } from \"../common/owner\";\nimport { PublicKeyish, WSOLMint, SOLMint } from \"../common/pubKey\";\nimport { TokenAmount } from \"../module/amount\";\nimport { Token } from \"../module/token\";\nimport { Cluster } from \"../solana\";\n\nimport Account, { TokenAccountDataProp } from \"./account/account\";\nimport Farm from \"./farm/farm\";\nimport Liquidity from \"./liquidity/liquidity\";\nimport { Clmm } from \"./clmm\";\nimport TradeV2 from \"./tradeV2/trade\";\nimport Utils1216 from \"./utils1216\";\nimport MarketV2 from \"./marketV2\";\nimport Ido from \"./ido\";\n\nimport TokenModule, { MintToTokenAmount } from \"./token/token\";\nimport { SignAllTransactions, TransferAmountFee } from \"./type\";\nimport { TokenInfo } from \"./token\";\n\nexport interface RaydiumLoadParams extends TokenAccountDataProp, Omit<RaydiumApiBatchRequestParams, \"api\"> {\n  /* ================= solana ================= */\n  // solana web3 connection\n  connection: Connection;\n  // solana cluster/network/env\n  cluster?: Cluster;\n  // user public key\n  owner?: PublicKey | Keypair;\n  /* ================= api ================= */\n  // api request interval in ms, -1 means never request again, 0 means always use fresh data, default is 5 mins (5 * 60 * 1000)\n  apiRequestInterval?: number;\n  // api request timeout in ms, default is 10 secs (10 * 1000)\n  apiRequestTimeout?: number;\n  apiCacheTime?: number;\n  signAllTransactions?: SignAllTransactions;\n  urlConfigs?: API_URL_CONFIG;\n  logRequests?: boolean;\n  logCount?: number;\n  jupTokenType?: JupTokenType;\n  preloadTokenPrice?: boolean;\n  disableFeatureCheck?: boolean;\n}\n\nexport interface RaydiumApiBatchRequestParams {\n  api: Api;\n  defaultChainTimeOffset?: number;\n  defaultChainTime?: number;\n}\n\nexport type RaydiumConstructorParams = Required<RaydiumLoadParams> & RaydiumApiBatchRequestParams;\n\ninterface DataBase<T> {\n  fetched: number;\n  data: T;\n  extInfo?: Record<string, any>;\n}\ninterface ApiData {\n  tokens?: DataBase<ApiV3Token[]>;\n\n  // v3 data\n  tokenList?: DataBase<ApiV3TokenRes>;\n  jupTokenList?: {\n    [JupTokenType.ALL]?: DataBase<ApiV3Token[]>;\n    [JupTokenType.Strict]?: DataBase<ApiV3Token[]>;\n  };\n}\n\nexport class Raydium {\n  public cluster: Cluster;\n  public farm: Farm;\n  public account: Account;\n  public liquidity: Liquidity;\n  public clmm: Clmm;\n  public tradeV2: TradeV2;\n  public utils1216: Utils1216;\n  public marketV2: MarketV2;\n  public ido: Ido;\n  public token: TokenModule;\n  public rawBalances: Map<string, string> = new Map();\n  public apiData: ApiData;\n  public availability: Partial<AvailabilityCheckAPI3>;\n\n  private _connection: Connection;\n  private _owner: Owner | undefined;\n  public api: Api;\n  private _apiCacheTime: number;\n  private _signAllTransactions?: SignAllTransactions;\n  private logger: Logger;\n  private _chainTime?: {\n    fetched: number;\n    value: {\n      chainTime: number;\n      offset: number;\n    };\n  };\n  private _epochInfo?: {\n    fetched: number;\n    value: EpochInfo;\n  };\n\n  constructor(config: RaydiumConstructorParams) {\n    const { connection, cluster, owner, api, defaultChainTime, defaultChainTimeOffset, apiCacheTime } = config;\n\n    this._connection = connection;\n    this.cluster = cluster;\n    this._owner = owner ? new Owner(owner) : undefined;\n    this._signAllTransactions = config.signAllTransactions;\n\n    this.api = api;\n    this._apiCacheTime = apiCacheTime || 5 * 60 * 1000;\n    this.logger = createLogger(\"Raydium\");\n    this.farm = new Farm({ scope: this, moduleName: \"Raydium_Farm\" });\n    this.account = new Account({\n      scope: this,\n      moduleName: \"Raydium_Account\",\n      tokenAccounts: config.tokenAccounts,\n      tokenAccountRawInfos: config.tokenAccountRawInfos,\n    });\n    this.liquidity = new Liquidity({ scope: this, moduleName: \"Raydium_LiquidityV2\" });\n    this.token = new TokenModule({ scope: this, moduleName: \"Raydium_tokenV2\" });\n    this.tradeV2 = new TradeV2({ scope: this, moduleName: \"Raydium_tradeV2\" });\n    this.clmm = new Clmm({ scope: this, moduleName: \"Raydium_clmm\" });\n    this.utils1216 = new Utils1216({ scope: this, moduleName: \"Raydium_utils1216\" });\n    this.marketV2 = new MarketV2({ scope: this, moduleName: \"Raydium_marketV2\" });\n    this.ido = new Ido({ scope: this, moduleName: \"Raydium_ido\" });\n\n    this.availability = {};\n    const now = new Date().getTime();\n    this.apiData = {};\n\n    if (defaultChainTimeOffset)\n      this._chainTime = {\n        fetched: now,\n        value: {\n          chainTime: defaultChainTime || Date.now() - defaultChainTimeOffset,\n          offset: defaultChainTimeOffset,\n        },\n      };\n  }\n\n  static async load(config: RaydiumLoadParams): Promise<Raydium> {\n    const custom: Required<RaydiumLoadParams> = merge(\n      // default\n      {\n        cluster: \"mainnet\",\n        owner: null,\n        apiRequestInterval: 5 * 60 * 1000,\n        apiRequestTimeout: 10 * 1000,\n      },\n      config,\n    );\n    const { cluster, apiRequestTimeout, logCount, logRequests, urlConfigs } = custom;\n\n    const api = new Api({ cluster, timeout: apiRequestTimeout, urlConfigs, logCount, logRequests });\n    const raydium = new Raydium({\n      ...custom,\n      api,\n    });\n\n    await raydium.fetchAvailabilityStatus(config.disableFeatureCheck);\n    await raydium.token.load({\n      type: config.jupTokenType,\n      fetchTokenPrice: config.preloadTokenPrice,\n    });\n\n    return raydium;\n  }\n\n  get owner(): Owner | undefined {\n    return this._owner;\n  }\n  get ownerPubKey(): PublicKey {\n    if (!this._owner) throw new Error(EMPTY_OWNER);\n    return this._owner.publicKey;\n  }\n  public setOwner(owner?: PublicKey | Keypair): Raydium {\n    this._owner = owner ? new Owner(owner) : undefined;\n    return this;\n  }\n  get connection(): Connection {\n    if (!this._connection) throw new Error(EMPTY_CONNECTION);\n    return this._connection;\n  }\n  public setConnection(connection: Connection): Raydium {\n    this._connection = connection;\n    return this;\n  }\n  get signAllTransactions(): SignAllTransactions | undefined {\n    return this._signAllTransactions;\n  }\n  public setSignAllTransactions(signAllTransactions?: SignAllTransactions): Raydium {\n    this._signAllTransactions = signAllTransactions;\n    return this;\n  }\n\n  public checkOwner(): void {\n    if (!this.owner) {\n      this.logger.error(EMPTY_OWNER);\n      throw new Error(EMPTY_OWNER);\n    }\n  }\n\n  private isCacheInvalidate(time: number): boolean {\n    return new Date().getTime() - time > this._apiCacheTime;\n  }\n\n  public async fetchChainTime(): Promise<void> {\n    try {\n      const data = await this.api.getChainTimeOffset();\n      this._chainTime = {\n        fetched: Date.now(),\n        value: {\n          chainTime: Date.now() - data.offset * 1000,\n          offset: data.offset * 1000,\n        },\n      };\n    } catch {\n      this._chainTime = undefined;\n    }\n  }\n\n  public async fetchV3TokenList(forceUpdate?: boolean): Promise<ApiV3TokenRes> {\n    if (this.apiData.tokenList && !this.isCacheInvalidate(this.apiData.tokenList.fetched) && !forceUpdate)\n      return this.apiData.tokenList.data;\n    const raydiumList = await this.api.getTokenList();\n    const dataObject = {\n      fetched: Date.now(),\n      data: raydiumList,\n    };\n    this.apiData.tokenList = dataObject;\n\n    return dataObject.data;\n  }\n\n  public async fetchJupTokenList(type: JupTokenType, forceUpdate?: boolean): Promise<ApiV3Token[]> {\n    const prevFetched = this.apiData.jupTokenList?.[type];\n    if (prevFetched && !this.isCacheInvalidate(prevFetched.fetched) && !forceUpdate) return prevFetched.data;\n    const jupList = await this.api.getJupTokenList(type);\n    this.apiData.jupTokenList = {\n      ...this.apiData.jupTokenList,\n      [type]: {\n        fetched: Date.now(),\n        data: jupList,\n      },\n    };\n\n    return this.apiData.jupTokenList[type]!.data;\n  }\n\n  get chainTimeData(): { offset: number; chainTime: number } | undefined {\n    return this._chainTime?.value;\n  }\n\n  public async chainTimeOffset(): Promise<number> {\n    if (this._chainTime && Date.now() - this._chainTime.fetched <= 1000 * 60 * 5) return this._chainTime.value.offset;\n    await this.fetchChainTime();\n    return this._chainTime?.value.offset || 0;\n  }\n\n  public async currentBlockChainTime(): Promise<number> {\n    if (this._chainTime && Date.now() - this._chainTime.fetched <= 1000 * 60 * 5)\n      return this._chainTime.value.chainTime;\n    await this.fetchChainTime();\n    return this._chainTime?.value.chainTime || Date.now();\n  }\n\n  public async fetchEpochInfo(): Promise<EpochInfo> {\n    if (this._epochInfo && Date.now() - this._epochInfo.fetched <= 1000 * 30) return this._epochInfo.value;\n    this._epochInfo = {\n      fetched: Date.now(),\n      value: await this.connection.getEpochInfo(),\n    };\n    return this._epochInfo.value;\n  }\n\n  public async getChainTokenInfo(mint: PublicKeyish): Promise<{ token: Token; tokenInfo: TokenInfo }> {\n    return this.token.getChainTokenInfo(mint);\n  }\n\n  public async fetchAvailabilityStatus(skipCheck?: boolean): Promise<Partial<AvailabilityCheckAPI3>> {\n    if (skipCheck) return {};\n    try {\n      const data = await this.api.fetchAvailabilityStatus();\n      const isAllDisabled = data.all === false;\n      this.availability = {\n        all: data.all,\n        swap: isAllDisabled ? false : data.swap,\n        createConcentratedPosition: isAllDisabled ? false : data.createConcentratedPosition,\n        addConcentratedPosition: isAllDisabled ? false : data.addConcentratedPosition,\n        addStandardPosition: isAllDisabled ? false : data.addStandardPosition,\n        removeConcentratedPosition: isAllDisabled ? false : data.removeConcentratedPosition,\n        removeStandardPosition: isAllDisabled ? false : data.removeStandardPosition,\n        addFarm: isAllDisabled ? false : data.addFarm,\n        removeFarm: isAllDisabled ? false : data.removeFarm,\n      };\n      return data;\n    } catch {\n      return {};\n    }\n  }\n\n  public mintToToken(mint: PublicKeyish): Token {\n    return this.token.mintToToken(mint);\n  }\n  public mintToTokenAmount(params: MintToTokenAmount): TokenAmount {\n    return this.token.mintToTokenAmount(params);\n  }\n  // export interface TransferAmountFee {amount: TokenAmount | CurrencyAmount, fee: TokenAmount | CurrencyAmount | undefined, expirationTime: number | undefined}\n  public solToWsolTokenAmount(tokenAmount: TokenAmount): TokenAmount {\n    if (!tokenAmount.token.mint.equals(SOLMint)) return tokenAmount;\n    return this.token.mintToTokenAmount({\n      mint: WSOLMint,\n      amount: tokenAmount.toExact(),\n    });\n  }\n  public solToWsolTransferAmountFee(tokenAmountFee: TransferAmountFee): TransferAmountFee {\n    if (!tokenAmountFee.amount.token.mint.equals(SOLMint)) return tokenAmountFee;\n    return {\n      amount: this.token.mintToTokenAmount({\n        mint: WSOLMint,\n        amount: tokenAmountFee.amount.toExact(),\n      }),\n      fee: tokenAmountFee.fee\n        ? this.token.mintToTokenAmount({\n            mint: WSOLMint,\n            amount: tokenAmountFee.fee.toExact(),\n          })\n        : tokenAmountFee.fee,\n      expirationTime: tokenAmountFee.expirationTime,\n    };\n  }\n  public decimalAmount(params: MintToTokenAmount): BN {\n    return this.token.decimalAmount(params);\n  }\n  public uiAmount(params: MintToTokenAmount): string {\n    return this.token.uiAmount(params);\n  }\n}\n","import axios, { AxiosInstance } from \"axios\";\n\nimport { createLogger, sleep } from \"../common\";\nimport { Cluster } from \"../solana\";\n\nimport {\n  ApiClmmConfigInfo,\n  ApiV3Token,\n  FetchPoolParams,\n  PoolsApiReturn,\n  SearchPoolsApiReturn,\n  JupTokenType,\n  PoolKeys,\n  FormatFarmKeyOut,\n  AvailabilityCheckAPI3,\n} from \"./type\";\nimport { API_URLS, API_URL_CONFIG, DEV_API_URLS } from \"./url\";\nimport { updateReqHistory } from \"./utils\";\nimport { PublicKey } from \"@solana/web3.js\";\n\nconst logger = createLogger(\"Raydium_Api\");\nconst poolKeysCache: Map<string, PoolKeys> = new Map();\nconst farmKeysCache: Map<string, FormatFarmKeyOut> = new Map();\n\nexport async function endlessRetry<T>(name: string, call: () => Promise<T>, interval = 1000): Promise<T> {\n  let result: T | undefined;\n\n  while (result == undefined) {\n    try {\n      logger.debug(`Request ${name} through endlessRetry`);\n      result = await call();\n    } catch (err) {\n      logger.error(`Request ${name} failed, retry after ${interval} ms`, err);\n      await sleep(interval);\n    }\n  }\n\n  return result;\n}\n\nexport interface ApiProps {\n  cluster: Cluster;\n  timeout: number;\n  logRequests?: boolean;\n  logCount?: number;\n  urlConfigs?: API_URL_CONFIG;\n}\n\nexport class Api {\n  public cluster: Cluster;\n\n  public api: AxiosInstance;\n  public logCount: number;\n\n  public urlConfigs: API_URL_CONFIG;\n\n  constructor({ cluster, timeout, logRequests, logCount, urlConfigs }: ApiProps) {\n    this.cluster = cluster;\n    this.urlConfigs = urlConfigs || {};\n    this.logCount = logCount || 1000;\n\n    this.api = axios.create({ baseURL: this.urlConfigs.BASE_HOST || API_URLS.BASE_HOST, timeout });\n\n    this.api.interceptors.request.use(\n      (config) => {\n        // before request\n        const { method, baseURL, url } = config;\n\n        logger.debug(`${method?.toUpperCase()} ${baseURL}${url}`);\n\n        return config;\n      },\n      (error) => {\n        // request error\n        logger.error(`Request failed`);\n\n        return Promise.reject(error);\n      },\n    );\n    this.api.interceptors.response.use(\n      (response) => {\n        // 2xx\n        const { config, data, status } = response;\n        const { method, baseURL, url } = config;\n\n        if (logRequests) {\n          updateReqHistory({\n            status,\n            url: `${baseURL}${url}`,\n            params: config.params,\n            data,\n            logCount: this.logCount,\n          });\n        }\n\n        logger.debug(`${method?.toUpperCase()} ${baseURL}${url}  ${status}`);\n\n        return data;\n      },\n      (error) => {\n        // https://axios-http.com/docs/handling_errors\n        // not 2xx\n        const { config, response = {} } = error;\n        const { status } = response;\n        const { method, baseURL, url } = config;\n\n        if (logRequests) {\n          updateReqHistory({\n            status,\n            url: `${baseURL}${url}`,\n            params: config.params,\n            data: error.message,\n            logCount: this.logCount,\n          });\n        }\n\n        logger.error(`${method.toUpperCase()} ${baseURL}${url} ${status || error.message}`);\n\n        return Promise.reject(error);\n      },\n    );\n  }\n\n  // async getTokens(): Promise<ApiTokens> {\n  //   return this.api.get(this.urlConfigs.TOKEN || API_URLS.TOKEN);\n  // }\n\n  async getClmmConfigs(): Promise<ApiClmmConfigInfo[]> {\n    const res = await this.api.get(this.urlConfigs.AMM_V3_CONFIG || API_URLS.AMM_V3_CONFIG);\n    return res.data;\n  }\n\n  async getClmmPoolLines(poolId: string): Promise<{ price: string; liquidity: string }[]> {\n    const res = await this.api.get(\n      `${this.urlConfigs.POOL_LIQUIDITY_LINE || API_URLS.POOL_LIQUIDITY_LINE}?pool_id=${poolId}`,\n    );\n    return res.data;\n  }\n\n  async getRaydiumTokenPrice(): Promise<Record<string, number>> {\n    return this.api.get(this.urlConfigs.PRICE || API_URLS.PRICE);\n  }\n\n  async getBlockSlotCountForSecond(endpointUrl?: string): Promise<number> {\n    if (!endpointUrl) return 2;\n    const res: {\n      id: string;\n      jsonrpc: string;\n      result: { numSlots: number; numTransactions: number; samplePeriodSecs: number; slot: number }[];\n    } = await this.api.post(endpointUrl, {\n      id: \"getRecentPerformanceSamples\",\n      jsonrpc: \"2.0\",\n      method: \"getRecentPerformanceSamples\",\n      params: [4],\n    });\n    const slotList = res.result.map((data) => data.numSlots);\n    return slotList.reduce((a, b) => a + b, 0) / slotList.length / 60;\n  }\n\n  async getChainTimeOffset(): Promise<{ offset: number }> {\n    return this.api.get(this.urlConfigs.CHAIN_TIME || API_URLS.CHAIN_TIME);\n  }\n\n  async getRpcs(): Promise<{\n    rpcs: { batch: boolean; name: string; url: string; weight: number }[];\n    strategy: string;\n  }> {\n    return this.api.get(this.urlConfigs.RPCS || API_URLS.RPCS);\n  }\n\n  async getTokenList(): Promise<{ mintList: ApiV3Token[]; blacklist: ApiV3Token[] }> {\n    const res = await this.api.get(this.urlConfigs.TOKEN_LIST || DEV_API_URLS.TOKEN_LIST, {});\n    return res.data;\n  }\n\n  async getJupTokenList(type?: JupTokenType): Promise<ApiV3Token[]> {\n    return this.api.get(\"/\", {\n      baseURL: (this.urlConfigs.JUP_TOKEN_LIST || DEV_API_URLS.JUP_TOKEN_LIST).replace(\n        \"{type}\",\n        type || JupTokenType.ALL,\n      ),\n    });\n  }\n\n  async getTokenInfo(mint: string | PublicKey): Promise<ApiV3Token | undefined> {\n    const res = await this.api.get(\n      (this.urlConfigs.TOKEN_INFO || DEV_API_URLS.TOKEN_INFO).replace(\"{mint}\", mint.toString()),\n    );\n    return res.data;\n  }\n\n  async getPoolList(props: FetchPoolParams = {}): Promise<PoolsApiReturn> {\n    const { type = \"all\", sort = \"liquidity\", order = \"desc\", page = 0 } = props;\n    const res = await this.api.get<PoolsApiReturn>(\n      (this.urlConfigs.POOL_LIST || DEV_API_URLS.POOL_LIST)\n        .replace(\"{type}\", type)\n        .replace(\"{sort}\", sort)\n        .replace(\"{order}\", order)\n        .replace(\"{page}\", String(page)),\n    );\n    return res.data;\n  }\n\n  async searchPoolById(props: { ids: string }): Promise<SearchPoolsApiReturn> {\n    const { ids } = props;\n    const res = await this.api.get(\n      (this.urlConfigs.POOL_SEARCH_BY_ID || DEV_API_URLS.POOL_SEARCH_BY_ID).replace(\"{ids}\", ids),\n    );\n    return res.data;\n  }\n\n  async searchPoolByMint(props: FetchPoolParams & { mint: string }): Promise<PoolsApiReturn> {\n    const { mint, type = \"all\", sort = \"liquidity\", order = \"desc\", page = 0 } = props;\n\n    const res = await this.api.get<PoolsApiReturn>(\n      (this.urlConfigs.POOL_SEARCH_MINT || DEV_API_URLS.POOL_SEARCH_MINT)\n        .replace(\"{mint1}\", mint)\n        .replace(\"{type}\", type)\n        .replace(\"{sort}\", sort)\n        .replace(\"{order}\", order)\n        .replace(\"{page}\", String(page)),\n    );\n    return res.data;\n  }\n\n  async searchPoolByMints(props: FetchPoolParams & { mint1: string; mint2: string }): Promise<PoolsApiReturn> {\n    const { mint1, mint2, type = \"all\", sort = \"liquidity\", order = \"desc\", page = 0 } = props;\n\n    const [mintA, mintB] = mint1 > mint2 ? [mint1, mint2] : [mint2, mint1];\n\n    const res = await this.api.get<PoolsApiReturn>(\n      (this.urlConfigs.POOL_SEARCH_MINT_2 || DEV_API_URLS.POOL_SEARCH_MINT_2)\n        .replace(\"{mint1}\", mintB)\n        .replace(\"{mint2}\", mintA)\n        .replace(\"{type}\", type)\n        .replace(\"{sort}\", sort)\n        .replace(\"{order}\", order)\n        .replace(\"{page}\", String(page)),\n    );\n    return res.data;\n  }\n\n  async fetchPoolKeysById(props: { id: string }): Promise<PoolKeys> {\n    const { id } = props;\n\n    if (poolKeysCache.has(id)) {\n      return poolKeysCache.get(id)!;\n    }\n\n    const res = await this.api.get<PoolKeys>(\n      (this.urlConfigs.POOL_KEY_BY_ID || DEV_API_URLS.POOL_KEY_BY_ID).replace(\"{id}\", id),\n    );\n    poolKeysCache.set(id, res.data);\n    return res.data;\n  }\n\n  async fetchFarmKeysById(props: { ids: string }): Promise<FormatFarmKeyOut[]> {\n    const { ids } = props;\n\n    const res = await this.api.get<FormatFarmKeyOut[]>(\n      (this.urlConfigs.FARM_KEYS || DEV_API_URLS.FARM_KEYS).replace(\"{ids}\", ids),\n    );\n    return res.data;\n  }\n\n  async fetchAvailabilityStatus(): Promise<AvailabilityCheckAPI3> {\n    const res = await this.api.get<AvailabilityCheckAPI3>(\n      this.urlConfigs.CHECK_AVAILABILITY || DEV_API_URLS.CHECK_AVAILABILITY,\n    );\n    return res.data;\n  }\n}\n","import { get, set } from \"lodash\";\nimport dayjs from \"dayjs\";\nimport utc from \"dayjs/plugin/utc\";\ndayjs.extend(utc);\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 dayjs().utc().format(\"YYYY/MM/DD HH:mm:ss UTC\");\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 { 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 _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN, parseBigNumberish, Rounding } from \"../common/bignumber\";\nimport { createLogger, Logger } from \"../common/logger\";\n\nimport toFormat, { WrappedBig } from \"./formatter\";\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\nimport { Currency } from \"./currency\";\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 BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { Token } from \"../module/token\";\nimport { Price } from \"../module/price\";\nimport { Currency } from \"../module/currency\";\nimport { TokenAmount, CurrencyAmount } from \"../module/amount\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { SplToken, TokenJson } from \"../raydium/token/type\";\nimport { ReplaceType } from \"../raydium/type\";\nimport { createLogger } from \"./logger\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\n\nexport enum Rounding {\n  ROUND_DOWN,\n  ROUND_HALF_UP,\n  ROUND_UP,\n}\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\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}\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\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","/*\r\n *  decimal.js v10.3.1\r\n *  An arbitrary-precision Decimal type for JavaScript.\r\n *  https://github.com/MikeMcl/decimal.js\r\n *  Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>\r\n *  MIT Licence\r\n */\r\n\r\n\r\n// -----------------------------------  EDITABLE DEFAULTS  ------------------------------------ //\r\n\r\n\r\n  // The maximum exponent magnitude.\r\n  // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\nvar EXP_LIMIT = 9e15,                      // 0 to 9e15\r\n\r\n  // The limit on the value of `precision`, and on the value of the first argument to\r\n  // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n  MAX_DIGITS = 1e9,                        // 0 to 1e9\r\n\r\n  // Base conversion alphabet.\r\n  NUMERALS = '0123456789abcdef',\r\n\r\n  // The natural logarithm of 10 (1025 digits).\r\n  LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n  // Pi (1025 digits).\r\n  PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n  // The initial configuration properties of the Decimal constructor.\r\n  DEFAULTS = {\r\n\r\n    // These values must be integers within the stated ranges (inclusive).\r\n    // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n    // The maximum number of significant digits of the result of a calculation or base conversion.\r\n    // E.g. `Decimal.config({ precision: 20 });`\r\n    precision: 20,                         // 1 to MAX_DIGITS\r\n\r\n    // The rounding mode used when rounding to `precision`.\r\n    //\r\n    // ROUND_UP         0 Away from zero.\r\n    // ROUND_DOWN       1 Towards zero.\r\n    // ROUND_CEIL       2 Towards +Infinity.\r\n    // ROUND_FLOOR      3 Towards -Infinity.\r\n    // ROUND_HALF_UP    4 Towards nearest neighbour. If equidistant, up.\r\n    // ROUND_HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.\r\n    // ROUND_HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n    // ROUND_HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n    // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n    //\r\n    // E.g.\r\n    // `Decimal.rounding = 4;`\r\n    // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n    rounding: 4,                           // 0 to 8\r\n\r\n    // The modulo mode used when calculating the modulus: a mod n.\r\n    // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n    // The remainder (r) is calculated as: r = a - n * q.\r\n    //\r\n    // UP         0 The remainder is positive if the dividend is negative, else is negative.\r\n    // DOWN       1 The remainder has the same sign as the dividend (JavaScript %).\r\n    // FLOOR      3 The remainder has the same sign as the divisor (Python %).\r\n    // HALF_EVEN  6 The IEEE 754 remainder function.\r\n    // EUCLID     9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n    //\r\n    // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n    // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n    // be used, but they may not give useful results.\r\n    modulo: 1,                             // 0 to 9\r\n\r\n    // The exponent value at and beneath which `toString` returns exponential notation.\r\n    // JavaScript numbers: -7\r\n    toExpNeg: -7,                          // 0 to -EXP_LIMIT\r\n\r\n    // The exponent value at and above which `toString` returns exponential notation.\r\n    // JavaScript numbers: 21\r\n    toExpPos:  21,                         // 0 to EXP_LIMIT\r\n\r\n    // The minimum exponent value, beneath which underflow to zero occurs.\r\n    // JavaScript numbers: -324  (5e-324)\r\n    minE: -EXP_LIMIT,                      // -1 to -EXP_LIMIT\r\n\r\n    // The maximum exponent value, above which overflow to Infinity occurs.\r\n    // JavaScript numbers: 308  (1.7976931348623157e+308)\r\n    maxE: EXP_LIMIT,                       // 1 to EXP_LIMIT\r\n\r\n    // Whether to use cryptographically-secure random number generation, if available.\r\n    crypto: false                          // true/false\r\n  },\r\n\r\n\r\n// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n  inexact, quadrant,\r\n  external = true,\r\n\r\n  decimalError = '[DecimalError] ',\r\n  invalidArgument = decimalError + 'Invalid argument: ',\r\n  precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n  cryptoUnavailable = decimalError + 'crypto unavailable',\r\n  tag = '[object Decimal]',\r\n\r\n  mathfloor = Math.floor,\r\n  mathpow = Math.pow,\r\n\r\n  isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n  isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n  isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n  isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n  BASE = 1e7,\r\n  LOG_BASE = 7,\r\n  MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n  LN10_PRECISION = LN10.length - 1,\r\n  PI_PRECISION = PI.length - 1,\r\n\r\n  // Decimal.prototype object\r\n  P = { toStringTag: tag };\r\n\r\n\r\n// Decimal prototype methods\r\n\r\n\r\n/*\r\n *  absoluteValue             abs\r\n *  ceil\r\n *  clampedTo                 clamp\r\n *  comparedTo                cmp\r\n *  cosine                    cos\r\n *  cubeRoot                  cbrt\r\n *  decimalPlaces             dp\r\n *  dividedBy                 div\r\n *  dividedToIntegerBy        divToInt\r\n *  equals                    eq\r\n *  floor\r\n *  greaterThan               gt\r\n *  greaterThanOrEqualTo      gte\r\n *  hyperbolicCosine          cosh\r\n *  hyperbolicSine            sinh\r\n *  hyperbolicTangent         tanh\r\n *  inverseCosine             acos\r\n *  inverseHyperbolicCosine   acosh\r\n *  inverseHyperbolicSine     asinh\r\n *  inverseHyperbolicTangent  atanh\r\n *  inverseSine               asin\r\n *  inverseTangent            atan\r\n *  isFinite\r\n *  isInteger                 isInt\r\n *  isNaN\r\n *  isNegative                isNeg\r\n *  isPositive                isPos\r\n *  isZero\r\n *  lessThan                  lt\r\n *  lessThanOrEqualTo         lte\r\n *  logarithm                 log\r\n *  [maximum]                 [max]\r\n *  [minimum]                 [min]\r\n *  minus                     sub\r\n *  modulo                    mod\r\n *  naturalExponential        exp\r\n *  naturalLogarithm          ln\r\n *  negated                   neg\r\n *  plus                      add\r\n *  precision                 sd\r\n *  round\r\n *  sine                      sin\r\n *  squareRoot                sqrt\r\n *  tangent                   tan\r\n *  times                     mul\r\n *  toBinary\r\n *  toDecimalPlaces           toDP\r\n *  toExponential\r\n *  toFixed\r\n *  toFraction\r\n *  toHexadecimal             toHex\r\n *  toNearest\r\n *  toNumber\r\n *  toOctal\r\n *  toPower                   pow\r\n *  toPrecision\r\n *  toSignificantDigits       toSD\r\n *  toString\r\n *  truncated                 trunc\r\n *  valueOf                   toJSON\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\nP.absoluteValue = P.abs = function () {\r\n  var x = new this.constructor(this);\r\n  if (x.s < 0) x.s = 1;\r\n  return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\nP.ceil = function () {\r\n  return finalise(new this.constructor(this), this.e + 1, 2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal clamped to the range\r\n * delineated by `min` and `max`.\r\n *\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nP.clampedTo = P.clamp = function (min, max) {\r\n  var k,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n  min = new Ctor(min);\r\n  max = new Ctor(max);\r\n  if (!min.s || !max.s) return new Ctor(NaN);\r\n  if (min.gt(max)) throw Error(invalidArgument + max);\r\n  k = x.cmp(min);\r\n  return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);\r\n};\r\n\r\n\r\n/*\r\n * Return\r\n *   1    if the value of this Decimal is greater than the value of `y`,\r\n *  -1    if the value of this Decimal is less than the value of `y`,\r\n *   0    if they have the same value,\r\n *   NaN  if the value of either Decimal is NaN.\r\n *\r\n */\r\nP.comparedTo = P.cmp = function (y) {\r\n  var i, j, xdL, ydL,\r\n    x = this,\r\n    xd = x.d,\r\n    yd = (y = new x.constructor(y)).d,\r\n    xs = x.s,\r\n    ys = y.s;\r\n\r\n  // Either NaN or ±Infinity?\r\n  if (!xd || !yd) {\r\n    return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n  }\r\n\r\n  // Either zero?\r\n  if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n  // Signs differ?\r\n  if (xs !== ys) return xs;\r\n\r\n  // Compare exponents.\r\n  if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n  xdL = xd.length;\r\n  ydL = yd.length;\r\n\r\n  // Compare digit by digit.\r\n  for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n    if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n  }\r\n\r\n  // Compare lengths.\r\n  return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0)         = 1\r\n * cos(-0)        = 1\r\n * cos(Infinity)  = NaN\r\n * cos(-Infinity) = NaN\r\n * cos(NaN)       = NaN\r\n *\r\n */\r\nP.cosine = P.cos = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.d) return new Ctor(NaN);\r\n\r\n  // cos(0) = cos(-0) = 1\r\n  if (!x.d[0]) return new Ctor(1);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n  Ctor.rounding = 1;\r\n\r\n  x = cosine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n *\r\n * Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n *  cbrt(0)  =  0\r\n *  cbrt(-0) = -0\r\n *  cbrt(1)  =  1\r\n *  cbrt(-1) = -1\r\n *  cbrt(N)  =  N\r\n *  cbrt(-I) = -I\r\n *  cbrt(I)  =  I\r\n *\r\n * Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))\r\n *\r\n */\r\nP.cubeRoot = P.cbrt = function () {\r\n  var e, m, n, r, rep, s, sd, t, t3, t3plusx,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n  external = false;\r\n\r\n  // Initial estimate.\r\n  s = x.s * mathpow(x.s * x, 1 / 3);\r\n\r\n   // Math.cbrt underflow/overflow?\r\n   // Pass x to Math.pow as integer, then adjust the exponent of the result.\r\n  if (!s || Math.abs(s) == 1 / 0) {\r\n    n = digitsToString(x.d);\r\n    e = x.e;\r\n\r\n    // Adjust n exponent so it is a multiple of 3 away from x exponent.\r\n    if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');\r\n    s = mathpow(n, 1 / 3);\r\n\r\n    // Rarely, e may be one less than the result exponent value.\r\n    e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));\r\n\r\n    if (s == 1 / 0) {\r\n      n = '5e' + e;\r\n    } else {\r\n      n = s.toExponential();\r\n      n = n.slice(0, n.indexOf('e') + 1) + e;\r\n    }\r\n\r\n    r = new Ctor(n);\r\n    r.s = x.s;\r\n  } else {\r\n    r = new Ctor(s.toString());\r\n  }\r\n\r\n  sd = (e = Ctor.precision) + 3;\r\n\r\n  // Halley's method.\r\n  // TODO? Compare Newton's method.\r\n  for (;;) {\r\n    t = r;\r\n    t3 = t.times(t).times(t);\r\n    t3plusx = t3.plus(x);\r\n    r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);\r\n\r\n    // TODO? Replace with for-loop and checkRoundingDigits.\r\n    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n      n = n.slice(sd - 3, sd + 1);\r\n\r\n      // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999\r\n      // , i.e. approaching a rounding boundary, continue the iteration.\r\n      if (n == '9999' || !rep && n == '4999') {\r\n\r\n        // On the first iteration only, check to see if rounding up gives the exact result as the\r\n        // nines may infinitely repeat.\r\n        if (!rep) {\r\n          finalise(t, e + 1, 0);\r\n\r\n          if (t.times(t).times(t).eq(x)) {\r\n            r = t;\r\n            break;\r\n          }\r\n        }\r\n\r\n        sd += 4;\r\n        rep = 1;\r\n      } else {\r\n\r\n        // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n        // If not, then there are further digits and m will be truthy.\r\n        if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n          // Truncate to the first rounding digit.\r\n          finalise(r, e + 1, 1);\r\n          m = !r.times(r).times(r).eq(x);\r\n        }\r\n\r\n        break;\r\n      }\r\n    }\r\n  }\r\n\r\n  external = true;\r\n\r\n  return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return the number of decimal places of the value of this Decimal.\r\n *\r\n */\r\nP.decimalPlaces = P.dp = function () {\r\n  var w,\r\n    d = this.d,\r\n    n = NaN;\r\n\r\n  if (d) {\r\n    w = d.length - 1;\r\n    n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n    // Subtract the number of trailing zeros of the last word.\r\n    w = d[w];\r\n    if (w) for (; w % 10 == 0; w /= 10) n--;\r\n    if (n < 0) n = 0;\r\n  }\r\n\r\n  return n;\r\n};\r\n\r\n\r\n/*\r\n *  n / 0 = I\r\n *  n / N = N\r\n *  n / I = 0\r\n *  0 / n = 0\r\n *  0 / 0 = N\r\n *  0 / N = N\r\n *  0 / I = 0\r\n *  N / n = N\r\n *  N / 0 = N\r\n *  N / N = N\r\n *  N / I = N\r\n *  I / n = I\r\n *  I / 0 = I\r\n *  I / N = N\r\n *  I / I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedBy = P.div = function (y) {\r\n  return divide(this, new this.constructor(y));\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the integer part of dividing the value of this Decimal\r\n * by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.dividedToIntegerBy = P.divToInt = function (y) {\r\n  var x = this,\r\n    Ctor = x.constructor;\r\n  return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.\r\n *\r\n */\r\nP.equals = P.eq = function (y) {\r\n  return this.cmp(y) === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of negative Infinity.\r\n *\r\n */\r\nP.floor = function () {\r\n  return finalise(new this.constructor(this), this.e + 1, 3);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than the value of `y`, otherwise return\r\n * false.\r\n *\r\n */\r\nP.greaterThan = P.gt = function (y) {\r\n  return this.cmp(y) > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is greater than or equal to the value of `y`,\r\n * otherwise return false.\r\n *\r\n */\r\nP.greaterThanOrEqualTo = P.gte = function (y) {\r\n  var k = this.cmp(y);\r\n  return k == 1 || k === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [1, Infinity]\r\n *\r\n * cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...\r\n *\r\n * cosh(0)         = 1\r\n * cosh(-0)        = 1\r\n * cosh(Infinity)  = Infinity\r\n * cosh(-Infinity) = Infinity\r\n * cosh(NaN)       = NaN\r\n *\r\n *  x        time taken (ms)   result\r\n * 1000      9                 9.8503555700852349694e+433\r\n * 10000     25                4.4034091128314607936e+4342\r\n * 100000    171               1.4033316802130615897e+43429\r\n * 1000000   3817              1.5166076984010437725e+434294\r\n * 10000000  abandoned after 2 minute wait\r\n *\r\n * TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))\r\n *\r\n */\r\nP.hyperbolicCosine = P.cosh = function () {\r\n  var k, n, pr, rm, len,\r\n    x = this,\r\n    Ctor = x.constructor,\r\n    one = new Ctor(1);\r\n\r\n  if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);\r\n  if (x.isZero()) return one;\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n  Ctor.rounding = 1;\r\n  len = x.d.length;\r\n\r\n  // Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1\r\n  // i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))\r\n\r\n  // Estimate the optimum number of times to use the argument reduction.\r\n  // TODO? Estimation reused from cosine() and may not be optimal here.\r\n  if (len < 32) {\r\n    k = Math.ceil(len / 3);\r\n    n = (1 / tinyPow(4, k)).toString();\r\n  } else {\r\n    k = 16;\r\n    n = '2.3283064365386962890625e-10';\r\n  }\r\n\r\n  x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);\r\n\r\n  // Reverse argument reduction\r\n  var cosh2_x,\r\n    i = k,\r\n    d8 = new Ctor(8);\r\n  for (; i--;) {\r\n    cosh2_x = x.times(x);\r\n    x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));\r\n  }\r\n\r\n  return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...\r\n *\r\n * sinh(0)         = 0\r\n * sinh(-0)        = -0\r\n * sinh(Infinity)  = Infinity\r\n * sinh(-Infinity) = -Infinity\r\n * sinh(NaN)       = NaN\r\n *\r\n * x        time taken (ms)\r\n * 10       2 ms\r\n * 100      5 ms\r\n * 1000     14 ms\r\n * 10000    82 ms\r\n * 100000   886 ms            1.4033316802130615897e+43429\r\n * 200000   2613 ms\r\n * 300000   5407 ms\r\n * 400000   8824 ms\r\n * 500000   13026 ms          8.7080643612718084129e+217146\r\n * 1000000  48543 ms\r\n *\r\n * TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))\r\n *\r\n */\r\nP.hyperbolicSine = P.sinh = function () {\r\n  var k, pr, rm, len,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;\r\n  Ctor.rounding = 1;\r\n  len = x.d.length;\r\n\r\n  if (len < 3) {\r\n    x = taylorSeries(Ctor, 2, x, x, true);\r\n  } else {\r\n\r\n    // Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))\r\n    // i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))\r\n    // 3 multiplications and 1 addition\r\n\r\n    // Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))\r\n    // i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))\r\n    // 4 multiplications and 2 additions\r\n\r\n    // Estimate the optimum number of times to use the argument reduction.\r\n    k = 1.4 * Math.sqrt(len);\r\n    k = k > 16 ? 16 : k | 0;\r\n\r\n    x = x.times(1 / tinyPow(5, k));\r\n    x = taylorSeries(Ctor, 2, x, x, true);\r\n\r\n    // Reverse argument reduction\r\n    var sinh2_x,\r\n      d5 = new Ctor(5),\r\n      d16 = new Ctor(16),\r\n      d20 = new Ctor(20);\r\n    for (; k--;) {\r\n      sinh2_x = x.times(x);\r\n      x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));\r\n    }\r\n  }\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return finalise(x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * tanh(x) = sinh(x) / cosh(x)\r\n *\r\n * tanh(0)         = 0\r\n * tanh(-0)        = -0\r\n * tanh(Infinity)  = 1\r\n * tanh(-Infinity) = -1\r\n * tanh(NaN)       = NaN\r\n *\r\n */\r\nP.hyperbolicTangent = P.tanh = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite()) return new Ctor(x.s);\r\n  if (x.isZero()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + 7;\r\n  Ctor.rounding = 1;\r\n\r\n  return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of\r\n * this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [0, pi]\r\n *\r\n * acos(x) = pi/2 - asin(x)\r\n *\r\n * acos(0)       = pi/2\r\n * acos(-0)      = pi/2\r\n * acos(1)       = 0\r\n * acos(-1)      = pi\r\n * acos(1/2)     = pi/3\r\n * acos(-1/2)    = 2*pi/3\r\n * acos(|x| > 1) = NaN\r\n * acos(NaN)     = NaN\r\n *\r\n */\r\nP.inverseCosine = P.acos = function () {\r\n  var halfPi,\r\n    x = this,\r\n    Ctor = x.constructor,\r\n    k = x.abs().cmp(1),\r\n    pr = Ctor.precision,\r\n    rm = Ctor.rounding;\r\n\r\n  if (k !== -1) {\r\n    return k === 0\r\n      // |x| is 1\r\n      ? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)\r\n      // |x| > 1 or x is NaN\r\n      : new Ctor(NaN);\r\n  }\r\n\r\n  if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n  // TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3\r\n\r\n  Ctor.precision = pr + 6;\r\n  Ctor.rounding = 1;\r\n\r\n  x = x.asin();\r\n  halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return halfPi.minus(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [1, Infinity]\r\n * Range: [0, Infinity]\r\n *\r\n * acosh(x) = ln(x + sqrt(x^2 - 1))\r\n *\r\n * acosh(x < 1)     = NaN\r\n * acosh(NaN)       = NaN\r\n * acosh(Infinity)  = Infinity\r\n * acosh(-Infinity) = NaN\r\n * acosh(0)         = NaN\r\n * acosh(-0)        = NaN\r\n * acosh(1)         = 0\r\n * acosh(-1)        = NaN\r\n *\r\n */\r\nP.inverseHyperbolicCosine = P.acosh = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);\r\n  if (!x.isFinite()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;\r\n  Ctor.rounding = 1;\r\n  external = false;\r\n\r\n  x = x.times(x).minus(1).sqrt().plus(x);\r\n\r\n  external = true;\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * asinh(x) = ln(x + sqrt(x^2 + 1))\r\n *\r\n * asinh(NaN)       = NaN\r\n * asinh(Infinity)  = Infinity\r\n * asinh(-Infinity) = -Infinity\r\n * asinh(0)         = 0\r\n * asinh(-0)        = -0\r\n *\r\n */\r\nP.inverseHyperbolicSine = P.asinh = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite() || x.isZero()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;\r\n  Ctor.rounding = 1;\r\n  external = false;\r\n\r\n  x = x.times(x).plus(1).sqrt().plus(x);\r\n\r\n  external = true;\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return x.ln();\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the\r\n * value of this Decimal.\r\n *\r\n * Domain: [-1, 1]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * atanh(x) = 0.5 * ln((1 + x) / (1 - x))\r\n *\r\n * atanh(|x| > 1)   = NaN\r\n * atanh(NaN)       = NaN\r\n * atanh(Infinity)  = NaN\r\n * atanh(-Infinity) = NaN\r\n * atanh(0)         = 0\r\n * atanh(-0)        = -0\r\n * atanh(1)         = Infinity\r\n * atanh(-1)        = -Infinity\r\n *\r\n */\r\nP.inverseHyperbolicTangent = P.atanh = function () {\r\n  var pr, rm, wpr, xsd,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite()) return new Ctor(NaN);\r\n  if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  xsd = x.sd();\r\n\r\n  if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);\r\n\r\n  Ctor.precision = wpr = xsd - x.e;\r\n\r\n  x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);\r\n\r\n  Ctor.precision = pr + 4;\r\n  Ctor.rounding = 1;\r\n\r\n  x = x.ln();\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return x.times(0.5);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this\r\n * Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))\r\n *\r\n * asin(0)       = 0\r\n * asin(-0)      = -0\r\n * asin(1/2)     = pi/6\r\n * asin(-1/2)    = -pi/6\r\n * asin(1)       = pi/2\r\n * asin(-1)      = -pi/2\r\n * asin(|x| > 1) = NaN\r\n * asin(NaN)     = NaN\r\n *\r\n * TODO? Compare performance of Taylor series.\r\n *\r\n */\r\nP.inverseSine = P.asin = function () {\r\n  var halfPi, k,\r\n    pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (x.isZero()) return new Ctor(x);\r\n\r\n  k = x.abs().cmp(1);\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n\r\n  if (k !== -1) {\r\n\r\n    // |x| is 1\r\n    if (k === 0) {\r\n      halfPi = getPi(Ctor, pr + 4, rm).times(0.5);\r\n      halfPi.s = x.s;\r\n      return halfPi;\r\n    }\r\n\r\n    // |x| > 1 or x is NaN\r\n    return new Ctor(NaN);\r\n  }\r\n\r\n  // TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6\r\n\r\n  Ctor.precision = pr + 6;\r\n  Ctor.rounding = 1;\r\n\r\n  x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return x.times(2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value\r\n * of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi/2, pi/2]\r\n *\r\n * atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n *\r\n * atan(0)         = 0\r\n * atan(-0)        = -0\r\n * atan(1)         = pi/4\r\n * atan(-1)        = -pi/4\r\n * atan(Infinity)  = pi/2\r\n * atan(-Infinity) = -pi/2\r\n * atan(NaN)       = NaN\r\n *\r\n */\r\nP.inverseTangent = P.atan = function () {\r\n  var i, j, k, n, px, t, r, wpr, x2,\r\n    x = this,\r\n    Ctor = x.constructor,\r\n    pr = Ctor.precision,\r\n    rm = Ctor.rounding;\r\n\r\n  if (!x.isFinite()) {\r\n    if (!x.s) return new Ctor(NaN);\r\n    if (pr + 4 <= PI_PRECISION) {\r\n      r = getPi(Ctor, pr + 4, rm).times(0.5);\r\n      r.s = x.s;\r\n      return r;\r\n    }\r\n  } else if (x.isZero()) {\r\n    return new Ctor(x);\r\n  } else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {\r\n    r = getPi(Ctor, pr + 4, rm).times(0.25);\r\n    r.s = x.s;\r\n    return r;\r\n  }\r\n\r\n  Ctor.precision = wpr = pr + 10;\r\n  Ctor.rounding = 1;\r\n\r\n  // TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);\r\n\r\n  // Argument reduction\r\n  // Ensure |x| < 0.42\r\n  // atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))\r\n\r\n  k = Math.min(28, wpr / LOG_BASE + 2 | 0);\r\n\r\n  for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));\r\n\r\n  external = false;\r\n\r\n  j = Math.ceil(wpr / LOG_BASE);\r\n  n = 1;\r\n  x2 = x.times(x);\r\n  r = new Ctor(x);\r\n  px = x;\r\n\r\n  // atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...\r\n  for (; i !== -1;) {\r\n    px = px.times(x2);\r\n    t = r.minus(px.div(n += 2));\r\n\r\n    px = px.times(x2);\r\n    r = t.plus(px.div(n += 2));\r\n\r\n    if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);\r\n  }\r\n\r\n  if (k) r = r.times(2 << (k - 1));\r\n\r\n  external = true;\r\n\r\n  return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is a finite number, otherwise return false.\r\n *\r\n */\r\nP.isFinite = function () {\r\n  return !!this.d;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is an integer, otherwise return false.\r\n *\r\n */\r\nP.isInteger = P.isInt = function () {\r\n  return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is NaN, otherwise return false.\r\n *\r\n */\r\nP.isNaN = function () {\r\n  return !this.s;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is negative, otherwise return false.\r\n *\r\n */\r\nP.isNegative = P.isNeg = function () {\r\n  return this.s < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is positive, otherwise return false.\r\n *\r\n */\r\nP.isPositive = P.isPos = function () {\r\n  return this.s > 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is 0 or -0, otherwise return false.\r\n *\r\n */\r\nP.isZero = function () {\r\n  return !!this.d && this.d[0] === 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThan = P.lt = function (y) {\r\n  return this.cmp(y) < 0;\r\n};\r\n\r\n\r\n/*\r\n * Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.\r\n *\r\n */\r\nP.lessThanOrEqualTo = P.lte = function (y) {\r\n  return this.cmp(y) < 1;\r\n};\r\n\r\n\r\n/*\r\n * Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * If no base is specified, return log[10](arg).\r\n *\r\n * log[base](arg) = ln(arg) / ln(base)\r\n *\r\n * The result will always be correctly rounded if the base of the log is 10, and 'almost always'\r\n * otherwise:\r\n *\r\n * Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen\r\n * rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error\r\n * between the result and the correctly rounded result will be one ulp (unit in the last place).\r\n *\r\n * log[-b](a)       = NaN\r\n * log[0](a)        = NaN\r\n * log[1](a)        = NaN\r\n * log[NaN](a)      = NaN\r\n * log[Infinity](a) = NaN\r\n * log[b](0)        = -Infinity\r\n * log[b](-0)       = -Infinity\r\n * log[b](-a)       = NaN\r\n * log[b](1)        = 0\r\n * log[b](Infinity) = Infinity\r\n * log[b](NaN)      = NaN\r\n *\r\n * [base] {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nP.logarithm = P.log = function (base) {\r\n  var isBase10, d, denominator, k, inf, num, sd, r,\r\n    arg = this,\r\n    Ctor = arg.constructor,\r\n    pr = Ctor.precision,\r\n    rm = Ctor.rounding,\r\n    guard = 5;\r\n\r\n  // Default base is 10.\r\n  if (base == null) {\r\n    base = new Ctor(10);\r\n    isBase10 = true;\r\n  } else {\r\n    base = new Ctor(base);\r\n    d = base.d;\r\n\r\n    // Return NaN if base is negative, or non-finite, or is 0 or 1.\r\n    if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);\r\n\r\n    isBase10 = base.eq(10);\r\n  }\r\n\r\n  d = arg.d;\r\n\r\n  // Is arg negative, non-finite, 0 or 1?\r\n  if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {\r\n    return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);\r\n  }\r\n\r\n  // The result will have a non-terminating decimal expansion if base is 10 and arg is not an\r\n  // integer power of 10.\r\n  if (isBase10) {\r\n    if (d.length > 1) {\r\n      inf = true;\r\n    } else {\r\n      for (k = d[0]; k % 10 === 0;) k /= 10;\r\n      inf = k !== 1;\r\n    }\r\n  }\r\n\r\n  external = false;\r\n  sd = pr + guard;\r\n  num = naturalLogarithm(arg, sd);\r\n  denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n\r\n  // The result will have 5 rounding digits.\r\n  r = divide(num, denominator, sd, 1);\r\n\r\n  // If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,\r\n  // calculate 10 further digits.\r\n  //\r\n  // If the result is known to have an infinite decimal expansion, repeat this until it is clear\r\n  // that the result is above or below the boundary. Otherwise, if after calculating the 10\r\n  // further digits, the last 14 are nines, round up and assume the result is exact.\r\n  // Also assume the result is exact if the last 14 are zero.\r\n  //\r\n  // Example of a result that will be incorrectly rounded:\r\n  // log[1048576](4503599627370502) = 2.60000000000000009610279511444746...\r\n  // The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it\r\n  // will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so\r\n  // the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal\r\n  // place is still 2.6.\r\n  if (checkRoundingDigits(r.d, k = pr, rm)) {\r\n\r\n    do {\r\n      sd += 10;\r\n      num = naturalLogarithm(arg, sd);\r\n      denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);\r\n      r = divide(num, denominator, sd, 1);\r\n\r\n      if (!inf) {\r\n\r\n        // Check for 14 nines from the 2nd rounding digit, as the first may be 4.\r\n        if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {\r\n          r = finalise(r, pr + 1, 0);\r\n        }\r\n\r\n        break;\r\n      }\r\n    } while (checkRoundingDigits(r.d, k += 10, rm));\r\n  }\r\n\r\n  external = true;\r\n\r\n  return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.max = function () {\r\n  Array.prototype.push.call(arguments, this);\r\n  return maxOrMin(this.constructor, arguments, 'lt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\nP.min = function () {\r\n  Array.prototype.push.call(arguments, this);\r\n  return maxOrMin(this.constructor, arguments, 'gt');\r\n};\r\n */\r\n\r\n\r\n/*\r\n *  n - 0 = n\r\n *  n - N = N\r\n *  n - I = -I\r\n *  0 - n = -n\r\n *  0 - 0 = 0\r\n *  0 - N = N\r\n *  0 - I = -I\r\n *  N - n = N\r\n *  N - 0 = N\r\n *  N - N = N\r\n *  N - I = N\r\n *  I - n = I\r\n *  I - 0 = I\r\n *  I - N = N\r\n *  I - I = N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.minus = P.sub = function (y) {\r\n  var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  y = new Ctor(y);\r\n\r\n  // If either is not finite...\r\n  if (!x.d || !y.d) {\r\n\r\n    // Return NaN if either is NaN.\r\n    if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n    // Return y negated if x is finite and y is ±Infinity.\r\n    else if (x.d) y.s = -y.s;\r\n\r\n    // Return x if y is finite and x is ±Infinity.\r\n    // Return x if both are ±Infinity with different signs.\r\n    // Return NaN if both are ±Infinity with the same sign.\r\n    else y = new Ctor(y.d || x.s !== y.s ? x : NaN);\r\n\r\n    return y;\r\n  }\r\n\r\n  // If signs differ...\r\n  if (x.s != y.s) {\r\n    y.s = -y.s;\r\n    return x.plus(y);\r\n  }\r\n\r\n  xd = x.d;\r\n  yd = y.d;\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n\r\n  // If either is zero...\r\n  if (!xd[0] || !yd[0]) {\r\n\r\n    // Return y negated if x is zero and y is non-zero.\r\n    if (yd[0]) y.s = -y.s;\r\n\r\n    // Return x if y is zero and x is non-zero.\r\n    else if (xd[0]) y = new Ctor(x);\r\n\r\n    // Return zero if both are zero.\r\n    // From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.\r\n    else return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n    return external ? finalise(y, pr, rm) : y;\r\n  }\r\n\r\n  // x and y are finite, non-zero numbers with the same sign.\r\n\r\n  // Calculate base 1e7 exponents.\r\n  e = mathfloor(y.e / LOG_BASE);\r\n  xe = mathfloor(x.e / LOG_BASE);\r\n\r\n  xd = xd.slice();\r\n  k = xe - e;\r\n\r\n  // If base 1e7 exponents differ...\r\n  if (k) {\r\n    xLTy = k < 0;\r\n\r\n    if (xLTy) {\r\n      d = xd;\r\n      k = -k;\r\n      len = yd.length;\r\n    } else {\r\n      d = yd;\r\n      e = xe;\r\n      len = xd.length;\r\n    }\r\n\r\n    // Numbers with massively different exponents would result in a very high number of\r\n    // zeros needing to be prepended, but this can be avoided while still ensuring correct\r\n    // rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.\r\n    i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;\r\n\r\n    if (k > i) {\r\n      k = i;\r\n      d.length = 1;\r\n    }\r\n\r\n    // Prepend zeros to equalise exponents.\r\n    d.reverse();\r\n    for (i = k; i--;) d.push(0);\r\n    d.reverse();\r\n\r\n  // Base 1e7 exponents equal.\r\n  } else {\r\n\r\n    // Check digits to determine which is the bigger number.\r\n\r\n    i = xd.length;\r\n    len = yd.length;\r\n    xLTy = i < len;\r\n    if (xLTy) len = i;\r\n\r\n    for (i = 0; i < len; i++) {\r\n      if (xd[i] != yd[i]) {\r\n        xLTy = xd[i] < yd[i];\r\n        break;\r\n      }\r\n    }\r\n\r\n    k = 0;\r\n  }\r\n\r\n  if (xLTy) {\r\n    d = xd;\r\n    xd = yd;\r\n    yd = d;\r\n    y.s = -y.s;\r\n  }\r\n\r\n  len = xd.length;\r\n\r\n  // Append zeros to `xd` if shorter.\r\n  // Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.\r\n  for (i = yd.length - len; i > 0; --i) xd[len++] = 0;\r\n\r\n  // Subtract yd from xd.\r\n  for (i = yd.length; i > k;) {\r\n\r\n    if (xd[--i] < yd[i]) {\r\n      for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;\r\n      --xd[j];\r\n      xd[i] += BASE;\r\n    }\r\n\r\n    xd[i] -= yd[i];\r\n  }\r\n\r\n  // Remove trailing zeros.\r\n  for (; xd[--len] === 0;) xd.pop();\r\n\r\n  // Remove leading zeros and adjust exponent accordingly.\r\n  for (; xd[0] === 0; xd.shift()) --e;\r\n\r\n  // Zero?\r\n  if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);\r\n\r\n  y.d = xd;\r\n  y.e = getBase10Exponent(xd, e);\r\n\r\n  return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n *   n % 0 =  N\r\n *   n % N =  N\r\n *   n % I =  n\r\n *   0 % n =  0\r\n *  -0 % n = -0\r\n *   0 % 0 =  N\r\n *   0 % N =  N\r\n *   0 % I =  0\r\n *   N % n =  N\r\n *   N % 0 =  N\r\n *   N % N =  N\r\n *   N % I =  N\r\n *   I % n =  N\r\n *   I % 0 =  N\r\n *   I % N =  N\r\n *   I % I =  N\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * The result depends on the modulo mode.\r\n *\r\n */\r\nP.modulo = P.mod = function (y) {\r\n  var q,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  y = new Ctor(y);\r\n\r\n  // Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.\r\n  if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);\r\n\r\n  // Return x if y is ±Infinity or x is ±0.\r\n  if (!y.d || x.d && !x.d[0]) {\r\n    return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);\r\n  }\r\n\r\n  // Prevent rounding of intermediate calculations.\r\n  external = false;\r\n\r\n  if (Ctor.modulo == 9) {\r\n\r\n    // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n    // result = x - q * y    where  0 <= result < abs(y)\r\n    q = divide(x, y.abs(), 0, 3, 1);\r\n    q.s *= y.s;\r\n  } else {\r\n    q = divide(x, y, 0, Ctor.modulo, 1);\r\n  }\r\n\r\n  q = q.times(y);\r\n\r\n  external = true;\r\n\r\n  return x.minus(q);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of the value of this Decimal,\r\n * i.e. the base e raised to the power the value of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalExponential = P.exp = function () {\r\n  return naturalExponential(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of the value of this Decimal,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.naturalLogarithm = P.ln = function () {\r\n  return naturalLogarithm(this);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by\r\n * -1.\r\n *\r\n */\r\nP.negated = P.neg = function () {\r\n  var x = new this.constructor(this);\r\n  x.s = -x.s;\r\n  return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n *  n + 0 = n\r\n *  n + N = N\r\n *  n + I = I\r\n *  0 + n = n\r\n *  0 + 0 = 0\r\n *  0 + N = N\r\n *  0 + I = I\r\n *  N + n = N\r\n *  N + 0 = N\r\n *  N + N = N\r\n *  N + I = N\r\n *  I + n = I\r\n *  I + 0 = I\r\n *  I + N = N\r\n *  I + I = I\r\n *\r\n * Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.plus = P.add = function (y) {\r\n  var carry, d, e, i, k, len, pr, rm, xd, yd,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  y = new Ctor(y);\r\n\r\n  // If either is not finite...\r\n  if (!x.d || !y.d) {\r\n\r\n    // Return NaN if either is NaN.\r\n    if (!x.s || !y.s) y = new Ctor(NaN);\r\n\r\n    // Return x if y is finite and x is ±Infinity.\r\n    // Return x if both are ±Infinity with the same sign.\r\n    // Return NaN if both are ±Infinity with different signs.\r\n    // Return y if x is finite and y is ±Infinity.\r\n    else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);\r\n\r\n    return y;\r\n  }\r\n\r\n   // If signs differ...\r\n  if (x.s != y.s) {\r\n    y.s = -y.s;\r\n    return x.minus(y);\r\n  }\r\n\r\n  xd = x.d;\r\n  yd = y.d;\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n\r\n  // If either is zero...\r\n  if (!xd[0] || !yd[0]) {\r\n\r\n    // Return x if y is zero.\r\n    // Return y if y is non-zero.\r\n    if (!yd[0]) y = new Ctor(x);\r\n\r\n    return external ? finalise(y, pr, rm) : y;\r\n  }\r\n\r\n  // x and y are finite, non-zero numbers with the same sign.\r\n\r\n  // Calculate base 1e7 exponents.\r\n  k = mathfloor(x.e / LOG_BASE);\r\n  e = mathfloor(y.e / LOG_BASE);\r\n\r\n  xd = xd.slice();\r\n  i = k - e;\r\n\r\n  // If base 1e7 exponents differ...\r\n  if (i) {\r\n\r\n    if (i < 0) {\r\n      d = xd;\r\n      i = -i;\r\n      len = yd.length;\r\n    } else {\r\n      d = yd;\r\n      e = k;\r\n      len = xd.length;\r\n    }\r\n\r\n    // Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.\r\n    k = Math.ceil(pr / LOG_BASE);\r\n    len = k > len ? k + 1 : len + 1;\r\n\r\n    if (i > len) {\r\n      i = len;\r\n      d.length = 1;\r\n    }\r\n\r\n    // Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.\r\n    d.reverse();\r\n    for (; i--;) d.push(0);\r\n    d.reverse();\r\n  }\r\n\r\n  len = xd.length;\r\n  i = yd.length;\r\n\r\n  // If yd is longer than xd, swap xd and yd so xd points to the longer array.\r\n  if (len - i < 0) {\r\n    i = len;\r\n    d = yd;\r\n    yd = xd;\r\n    xd = d;\r\n  }\r\n\r\n  // Only start adding at yd.length - 1 as the further digits of xd can be left as they are.\r\n  for (carry = 0; i;) {\r\n    carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;\r\n    xd[i] %= BASE;\r\n  }\r\n\r\n  if (carry) {\r\n    xd.unshift(carry);\r\n    ++e;\r\n  }\r\n\r\n  // Remove trailing zeros.\r\n  // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n  for (len = xd.length; xd[--len] == 0;) xd.pop();\r\n\r\n  y.d = xd;\r\n  y.e = getBase10Exponent(xd, e);\r\n\r\n  return external ? finalise(y, pr, rm) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return the number of significant digits of the value of this Decimal.\r\n *\r\n * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r\n *\r\n */\r\nP.precision = P.sd = function (z) {\r\n  var k,\r\n    x = this;\r\n\r\n  if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);\r\n\r\n  if (x.d) {\r\n    k = getPrecision(x.d);\r\n    if (z && x.e + 1 > k) k = x.e + 1;\r\n  } else {\r\n    k = NaN;\r\n  }\r\n\r\n  return k;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number using\r\n * rounding mode `rounding`.\r\n *\r\n */\r\nP.round = function () {\r\n  var x = this,\r\n    Ctor = x.constructor;\r\n\r\n  return finalise(new Ctor(x), x.e + 1, Ctor.rounding);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n *\r\n * sin(0)         = 0\r\n * sin(-0)        = -0\r\n * sin(Infinity)  = NaN\r\n * sin(-Infinity) = NaN\r\n * sin(NaN)       = NaN\r\n *\r\n */\r\nP.sine = P.sin = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite()) return new Ctor(NaN);\r\n  if (x.isZero()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;\r\n  Ctor.rounding = 1;\r\n\r\n  x = sine(Ctor, toLessThanHalfPi(Ctor, x));\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n *  sqrt(-n) =  N\r\n *  sqrt(N)  =  N\r\n *  sqrt(-I) =  N\r\n *  sqrt(I)  =  I\r\n *  sqrt(0)  =  0\r\n *  sqrt(-0) = -0\r\n *\r\n */\r\nP.squareRoot = P.sqrt = function () {\r\n  var m, n, sd, r, rep, t,\r\n    x = this,\r\n    d = x.d,\r\n    e = x.e,\r\n    s = x.s,\r\n    Ctor = x.constructor;\r\n\r\n  // Negative/NaN/Infinity/zero?\r\n  if (s !== 1 || !d || !d[0]) {\r\n    return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);\r\n  }\r\n\r\n  external = false;\r\n\r\n  // Initial estimate.\r\n  s = Math.sqrt(+x);\r\n\r\n  // Math.sqrt underflow/overflow?\r\n  // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n  if (s == 0 || s == 1 / 0) {\r\n    n = digitsToString(d);\r\n\r\n    if ((n.length + e) % 2 == 0) n += '0';\r\n    s = Math.sqrt(n);\r\n    e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n    if (s == 1 / 0) {\r\n      n = '5e' + e;\r\n    } else {\r\n      n = s.toExponential();\r\n      n = n.slice(0, n.indexOf('e') + 1) + e;\r\n    }\r\n\r\n    r = new Ctor(n);\r\n  } else {\r\n    r = new Ctor(s.toString());\r\n  }\r\n\r\n  sd = (e = Ctor.precision) + 3;\r\n\r\n  // Newton-Raphson iteration.\r\n  for (;;) {\r\n    t = r;\r\n    r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);\r\n\r\n    // TODO? Replace with for-loop and checkRoundingDigits.\r\n    if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {\r\n      n = n.slice(sd - 3, sd + 1);\r\n\r\n      // The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or\r\n      // 4999, i.e. approaching a rounding boundary, continue the iteration.\r\n      if (n == '9999' || !rep && n == '4999') {\r\n\r\n        // On the first iteration only, check to see if rounding up gives the exact result as the\r\n        // nines may infinitely repeat.\r\n        if (!rep) {\r\n          finalise(t, e + 1, 0);\r\n\r\n          if (t.times(t).eq(x)) {\r\n            r = t;\r\n            break;\r\n          }\r\n        }\r\n\r\n        sd += 4;\r\n        rep = 1;\r\n      } else {\r\n\r\n        // If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.\r\n        // If not, then there are further digits and m will be truthy.\r\n        if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n          // Truncate to the first rounding digit.\r\n          finalise(r, e + 1, 1);\r\n          m = !r.times(r).eq(x);\r\n        }\r\n\r\n        break;\r\n      }\r\n    }\r\n  }\r\n\r\n  external = true;\r\n\r\n  return finalise(r, e, Ctor.rounding, m);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-Infinity, Infinity]\r\n *\r\n * tan(0)         = 0\r\n * tan(-0)        = -0\r\n * tan(Infinity)  = NaN\r\n * tan(-Infinity) = NaN\r\n * tan(NaN)       = NaN\r\n *\r\n */\r\nP.tangent = P.tan = function () {\r\n  var pr, rm,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (!x.isFinite()) return new Ctor(NaN);\r\n  if (x.isZero()) return new Ctor(x);\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n  Ctor.precision = pr + 10;\r\n  Ctor.rounding = 1;\r\n\r\n  x = x.sin();\r\n  x.s = 1;\r\n  x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);\r\n\r\n  Ctor.precision = pr;\r\n  Ctor.rounding = rm;\r\n\r\n  return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);\r\n};\r\n\r\n\r\n/*\r\n *  n * 0 = 0\r\n *  n * N = N\r\n *  n * I = I\r\n *  0 * n = 0\r\n *  0 * 0 = 0\r\n *  0 * N = N\r\n *  0 * I = N\r\n *  N * n = N\r\n *  N * 0 = N\r\n *  N * N = N\r\n *  N * I = N\r\n *  I * n = I\r\n *  I * 0 = N\r\n *  I * N = N\r\n *  I * I = I\r\n *\r\n * Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n */\r\nP.times = P.mul = function (y) {\r\n  var carry, e, i, k, r, rL, t, xdL, ydL,\r\n    x = this,\r\n    Ctor = x.constructor,\r\n    xd = x.d,\r\n    yd = (y = new Ctor(y)).d;\r\n\r\n  y.s *= x.s;\r\n\r\n   // If either is NaN, ±Infinity or ±0...\r\n  if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n    return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd\r\n\r\n      // Return NaN if either is NaN.\r\n      // Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.\r\n      ? NaN\r\n\r\n      // Return ±Infinity if either is ±Infinity.\r\n      // Return ±0 if either is ±0.\r\n      : !xd || !yd ? y.s / 0 : y.s * 0);\r\n  }\r\n\r\n  e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);\r\n  xdL = xd.length;\r\n  ydL = yd.length;\r\n\r\n  // Ensure xd points to the longer array.\r\n  if (xdL < ydL) {\r\n    r = xd;\r\n    xd = yd;\r\n    yd = r;\r\n    rL = xdL;\r\n    xdL = ydL;\r\n    ydL = rL;\r\n  }\r\n\r\n  // Initialise the result array with zeros.\r\n  r = [];\r\n  rL = xdL + ydL;\r\n  for (i = rL; i--;) r.push(0);\r\n\r\n  // Multiply!\r\n  for (i = ydL; --i >= 0;) {\r\n    carry = 0;\r\n    for (k = xdL + i; k > i;) {\r\n      t = r[k] + yd[i] * xd[k - i - 1] + carry;\r\n      r[k--] = t % BASE | 0;\r\n      carry = t / BASE | 0;\r\n    }\r\n\r\n    r[k] = (r[k] + carry) % BASE | 0;\r\n  }\r\n\r\n  // Remove trailing zeros.\r\n  for (; !r[--rL];) r.pop();\r\n\r\n  if (carry) ++e;\r\n  else r.shift();\r\n\r\n  y.d = r;\r\n  y.e = getBase10Exponent(r, e);\r\n\r\n  return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 2, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toBinary = function (sd, rm) {\r\n  return toStringBinary(this, 2, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`\r\n * decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.\r\n *\r\n * If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toDecimalPlaces = P.toDP = function (dp, rm) {\r\n  var x = this,\r\n    Ctor = x.constructor;\r\n\r\n  x = new Ctor(x);\r\n  if (dp === void 0) return x;\r\n\r\n  checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n  if (rm === void 0) rm = Ctor.rounding;\r\n  else checkInt32(rm, 0, 8);\r\n\r\n  return finalise(x, dp + x.e + 1, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in exponential notation rounded to\r\n * `dp` fixed decimal places using rounding mode `rounding`.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toExponential = function (dp, rm) {\r\n  var str,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (dp === void 0) {\r\n    str = finiteToString(x, true);\r\n  } else {\r\n    checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n    if (rm === void 0) rm = Ctor.rounding;\r\n    else checkInt32(rm, 0, 8);\r\n\r\n    x = finalise(new Ctor(x), dp + 1, rm);\r\n    str = finiteToString(x, true, dp + 1);\r\n  }\r\n\r\n  return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in normal (fixed-point) notation to\r\n * `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is\r\n * omitted.\r\n *\r\n * As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.\r\n * (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.\r\n * (-0).toFixed(3) is '0.000'.\r\n * (-0.5).toFixed(0) is '-0'.\r\n *\r\n */\r\nP.toFixed = function (dp, rm) {\r\n  var str, y,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (dp === void 0) {\r\n    str = finiteToString(x);\r\n  } else {\r\n    checkInt32(dp, 0, MAX_DIGITS);\r\n\r\n    if (rm === void 0) rm = Ctor.rounding;\r\n    else checkInt32(rm, 0, 8);\r\n\r\n    y = finalise(new Ctor(x), dp + x.e + 1, rm);\r\n    str = finiteToString(y, false, dp + y.e + 1);\r\n  }\r\n\r\n  // To determine whether to add the minus sign look at the value before it was rounded,\r\n  // i.e. look at `x` rather than `y`.\r\n  return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return an array representing the value of this Decimal as a simple fraction with an integer\r\n * numerator and an integer denominator.\r\n *\r\n * The denominator will be a positive non-zero value less than or equal to the specified maximum\r\n * denominator. If a maximum denominator is not specified, the denominator will be the lowest\r\n * value necessary to represent the number exactly.\r\n *\r\n * [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.\r\n *\r\n */\r\nP.toFraction = function (maxD) {\r\n  var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,\r\n    x = this,\r\n    xd = x.d,\r\n    Ctor = x.constructor;\r\n\r\n  if (!xd) return new Ctor(x);\r\n\r\n  n1 = d0 = new Ctor(1);\r\n  d1 = n0 = new Ctor(0);\r\n\r\n  d = new Ctor(d1);\r\n  e = d.e = getPrecision(xd) - x.e - 1;\r\n  k = e % LOG_BASE;\r\n  d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);\r\n\r\n  if (maxD == null) {\r\n\r\n    // d is 10**e, the minimum max-denominator needed.\r\n    maxD = e > 0 ? d : n1;\r\n  } else {\r\n    n = new Ctor(maxD);\r\n    if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);\r\n    maxD = n.gt(d) ? (e > 0 ? d : n1) : n;\r\n  }\r\n\r\n  external = false;\r\n  n = new Ctor(digitsToString(xd));\r\n  pr = Ctor.precision;\r\n  Ctor.precision = e = xd.length * LOG_BASE * 2;\r\n\r\n  for (;;)  {\r\n    q = divide(n, d, 0, 1, 1);\r\n    d2 = d0.plus(q.times(d1));\r\n    if (d2.cmp(maxD) == 1) break;\r\n    d0 = d1;\r\n    d1 = d2;\r\n    d2 = n1;\r\n    n1 = n0.plus(q.times(d2));\r\n    n0 = d2;\r\n    d2 = d;\r\n    d = n.minus(q.times(d2));\r\n    n = d2;\r\n  }\r\n\r\n  d2 = divide(maxD.minus(d0), d1, 0, 1, 1);\r\n  n0 = n0.plus(d2.times(n1));\r\n  d0 = d0.plus(d2.times(d1));\r\n  n0.s = n1.s = x.s;\r\n\r\n  // Determine which fraction is closer to x, n0/d0 or n1/d1?\r\n  r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1\r\n      ? [n1, d1] : [n0, d0];\r\n\r\n  Ctor.precision = pr;\r\n  external = true;\r\n\r\n  return r;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 16, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toHexadecimal = P.toHex = function (sd, rm) {\r\n  return toStringBinary(this, 16, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Returns a new Decimal whose value is the nearest multiple of `y` in the direction of rounding\r\n * mode `rm`, or `Decimal.rounding` if `rm` is omitted, to the value of this Decimal.\r\n *\r\n * The return value will always have the same sign as this Decimal, unless either this Decimal\r\n * or `y` is NaN, in which case the return value will be also be NaN.\r\n *\r\n * The return value is not affected by the value of `precision`.\r\n *\r\n * y {number|string|Decimal} The magnitude to round to a multiple of.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toNearest() rounding mode not an integer: {rm}'\r\n * 'toNearest() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toNearest = function (y, rm) {\r\n  var x = this,\r\n    Ctor = x.constructor;\r\n\r\n  x = new Ctor(x);\r\n\r\n  if (y == null) {\r\n\r\n    // If x is not finite, return x.\r\n    if (!x.d) return x;\r\n\r\n    y = new Ctor(1);\r\n    rm = Ctor.rounding;\r\n  } else {\r\n    y = new Ctor(y);\r\n    if (rm === void 0) {\r\n      rm = Ctor.rounding;\r\n    } else {\r\n      checkInt32(rm, 0, 8);\r\n    }\r\n\r\n    // If x is not finite, return x if y is not NaN, else NaN.\r\n    if (!x.d) return y.s ? x : y;\r\n\r\n    // If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.\r\n    if (!y.d) {\r\n      if (y.s) y.s = x.s;\r\n      return y;\r\n    }\r\n  }\r\n\r\n  // If y is not zero, calculate the nearest multiple of y to x.\r\n  if (y.d[0]) {\r\n    external = false;\r\n    x = divide(x, y, 0, rm, 1).times(y);\r\n    external = true;\r\n    finalise(x);\r\n\r\n  // If y is zero, return zero with the sign of x.\r\n  } else {\r\n    y.s = x.s;\r\n    x = y;\r\n  }\r\n\r\n  return x;\r\n};\r\n\r\n\r\n/*\r\n * Return the value of this Decimal converted to a number primitive.\r\n * Zero keeps its sign.\r\n *\r\n */\r\nP.toNumber = function () {\r\n  return +this;\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal in base 8, round to `sd` significant\r\n * digits using rounding mode `rm`.\r\n *\r\n * If the optional `sd` argument is present then return binary exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toOctal = function (sd, rm) {\r\n  return toStringBinary(this, 8, sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded\r\n * to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * ECMAScript compliant.\r\n *\r\n *   pow(x, NaN)                           = NaN\r\n *   pow(x, ±0)                            = 1\r\n\r\n *   pow(NaN, non-zero)                    = NaN\r\n *   pow(abs(x) > 1, +Infinity)            = +Infinity\r\n *   pow(abs(x) > 1, -Infinity)            = +0\r\n *   pow(abs(x) == 1, ±Infinity)           = NaN\r\n *   pow(abs(x) < 1, +Infinity)            = +0\r\n *   pow(abs(x) < 1, -Infinity)            = +Infinity\r\n *   pow(+Infinity, y > 0)                 = +Infinity\r\n *   pow(+Infinity, y < 0)                 = +0\r\n *   pow(-Infinity, odd integer > 0)       = -Infinity\r\n *   pow(-Infinity, even integer > 0)      = +Infinity\r\n *   pow(-Infinity, odd integer < 0)       = -0\r\n *   pow(-Infinity, even integer < 0)      = +0\r\n *   pow(+0, y > 0)                        = +0\r\n *   pow(+0, y < 0)                        = +Infinity\r\n *   pow(-0, odd integer > 0)              = -0\r\n *   pow(-0, even integer > 0)             = +0\r\n *   pow(-0, odd integer < 0)              = -Infinity\r\n *   pow(-0, even integer < 0)             = +Infinity\r\n *   pow(finite x < 0, finite non-integer) = NaN\r\n *\r\n * For non-integer or very large exponents pow(x, y) is calculated using\r\n *\r\n *   x^y = exp(y*ln(x))\r\n *\r\n * Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the\r\n * probability of an incorrectly rounded result\r\n * P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14\r\n * i.e. 1 in 250,000,000,000,000\r\n *\r\n * If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).\r\n *\r\n * y {number|string|Decimal} The power to which to raise this Decimal.\r\n *\r\n */\r\nP.toPower = P.pow = function (y) {\r\n  var e, k, pr, r, rm, s,\r\n    x = this,\r\n    Ctor = x.constructor,\r\n    yn = +(y = new Ctor(y));\r\n\r\n  // Either ±Infinity, NaN or ±0?\r\n  if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));\r\n\r\n  x = new Ctor(x);\r\n\r\n  if (x.eq(1)) return x;\r\n\r\n  pr = Ctor.precision;\r\n  rm = Ctor.rounding;\r\n\r\n  if (y.eq(1)) return finalise(x, pr, rm);\r\n\r\n  // y exponent\r\n  e = mathfloor(y.e / LOG_BASE);\r\n\r\n  // If y is a small integer use the 'exponentiation by squaring' algorithm.\r\n  if (e >= y.d.length - 1 && (k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {\r\n    r = intPow(Ctor, x, k, pr);\r\n    return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);\r\n  }\r\n\r\n  s = x.s;\r\n\r\n  // if x is negative\r\n  if (s < 0) {\r\n\r\n    // if y is not an integer\r\n    if (e < y.d.length - 1) return new Ctor(NaN);\r\n\r\n    // Result is positive if x is negative and the last digit of integer y is even.\r\n    if ((y.d[e] & 1) == 0) s = 1;\r\n\r\n    // if x.eq(-1)\r\n    if (x.e == 0 && x.d[0] == 1 && x.d.length == 1) {\r\n      x.s = s;\r\n      return x;\r\n    }\r\n  }\r\n\r\n  // Estimate result exponent.\r\n  // x^y = 10^e,  where e = y * log10(x)\r\n  // log10(x) = log10(x_significand) + x_exponent\r\n  // log10(x_significand) = ln(x_significand) / ln(10)\r\n  k = mathpow(+x, yn);\r\n  e = k == 0 || !isFinite(k)\r\n    ? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))\r\n    : new Ctor(k + '').e;\r\n\r\n  // Exponent estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.\r\n\r\n  // Overflow/underflow?\r\n  if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? s / 0 : 0);\r\n\r\n  external = false;\r\n  Ctor.rounding = x.s = 1;\r\n\r\n  // Estimate the extra guard digits needed to ensure five correct rounding digits from\r\n  // naturalLogarithm(x). Example of failure without these extra digits (precision: 10):\r\n  // new Decimal(2.32456).pow('2087987436534566.46411')\r\n  // should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815\r\n  k = Math.min(12, (e + '').length);\r\n\r\n  // r = x^y = exp(y*ln(x))\r\n  r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);\r\n\r\n  // r may be Infinity, e.g. (0.9999999999999999).pow(-1e+40)\r\n  if (r.d) {\r\n\r\n    // Truncate to the required precision plus five rounding digits.\r\n    r = finalise(r, pr + 5, 1);\r\n\r\n    // If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate\r\n    // the result.\r\n    if (checkRoundingDigits(r.d, pr, rm)) {\r\n      e = pr + 10;\r\n\r\n      // Truncate to the increased precision plus five rounding digits.\r\n      r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);\r\n\r\n      // Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).\r\n      if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {\r\n        r = finalise(r, pr + 1, 0);\r\n      }\r\n    }\r\n  }\r\n\r\n  r.s = s;\r\n  external = true;\r\n  Ctor.rounding = rm;\r\n\r\n  return finalise(r, pr, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal rounded to `sd` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * Return exponential notation if `sd` is less than the number of digits necessary to represent\r\n * the integer part of the value in normal notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n */\r\nP.toPrecision = function (sd, rm) {\r\n  var str,\r\n    x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (sd === void 0) {\r\n    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n  } else {\r\n    checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n    if (rm === void 0) rm = Ctor.rounding;\r\n    else checkInt32(rm, 0, 8);\r\n\r\n    x = finalise(new Ctor(x), sd, rm);\r\n    str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);\r\n  }\r\n\r\n  return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`\r\n * significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if\r\n * omitted.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * 'toSD() digits out of range: {sd}'\r\n * 'toSD() digits not an integer: {sd}'\r\n * 'toSD() rounding mode not an integer: {rm}'\r\n * 'toSD() rounding mode out of range: {rm}'\r\n *\r\n */\r\nP.toSignificantDigits = P.toSD = function (sd, rm) {\r\n  var x = this,\r\n    Ctor = x.constructor;\r\n\r\n  if (sd === void 0) {\r\n    sd = Ctor.precision;\r\n    rm = Ctor.rounding;\r\n  } else {\r\n    checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n    if (rm === void 0) rm = Ctor.rounding;\r\n    else checkInt32(rm, 0, 8);\r\n  }\r\n\r\n  return finalise(new Ctor(x), sd, rm);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n *\r\n * Return exponential notation if this Decimal has a positive exponent equal to or greater than\r\n * `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.\r\n *\r\n */\r\nP.toString = function () {\r\n  var x = this,\r\n    Ctor = x.constructor,\r\n    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n  return x.isNeg() && !x.isZero() ? '-' + str : str;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal truncated to a whole number.\r\n *\r\n */\r\nP.truncated = P.trunc = function () {\r\n  return finalise(new this.constructor(this), this.e + 1, 1);\r\n};\r\n\r\n\r\n/*\r\n * Return a string representing the value of this Decimal.\r\n * Unlike `toString`, negative zero will include the minus sign.\r\n *\r\n */\r\nP.valueOf = P.toJSON = function () {\r\n  var x = this,\r\n    Ctor = x.constructor,\r\n    str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);\r\n\r\n  return x.isNeg() ? '-' + str : str;\r\n};\r\n\r\n\r\n// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.\r\n\r\n\r\n/*\r\n *  digitsToString           P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toPower,\r\n *                           finiteToString, naturalExponential, naturalLogarithm\r\n *  checkInt32               P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,\r\n *                           P.toPrecision, P.toSignificantDigits, toStringBinary, random\r\n *  checkRoundingDigits      P.logarithm, P.toPower, naturalExponential, naturalLogarithm\r\n *  convertBase              toStringBinary, parseOther\r\n *  cos                      P.cos\r\n *  divide                   P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,\r\n *                           P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,\r\n *                           P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,\r\n *                           taylorSeries, atan2, parseOther\r\n *  finalise                 P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,\r\n *                           P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,\r\n *                           P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,\r\n *                           P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,\r\n *                           P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,\r\n *                           P.truncated, divide, getLn10, getPi, naturalExponential,\r\n *                           naturalLogarithm, ceil, floor, round, trunc\r\n *  finiteToString           P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,\r\n *                           toStringBinary\r\n *  getBase10Exponent        P.minus, P.plus, P.times, parseOther\r\n *  getLn10                  P.logarithm, naturalLogarithm\r\n *  getPi                    P.acos, P.asin, P.atan, toLessThanHalfPi, atan2\r\n *  getPrecision             P.precision, P.toFraction\r\n *  getZeroString            digitsToString, finiteToString\r\n *  intPow                   P.toPower, parseOther\r\n *  isOdd                    toLessThanHalfPi\r\n *  maxOrMin                 max, min\r\n *  naturalExponential       P.naturalExponential, P.toPower\r\n *  naturalLogarithm         P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,\r\n *                           P.toPower, naturalExponential\r\n *  nonFiniteToString        finiteToString, toStringBinary\r\n *  parseDecimal             Decimal\r\n *  parseOther               Decimal\r\n *  sin                      P.sin\r\n *  taylorSeries             P.cosh, P.sinh, cos, sin\r\n *  toLessThanHalfPi         P.cos, P.sin\r\n *  toStringBinary           P.toBinary, P.toHexadecimal, P.toOctal\r\n *  truncate                 intPow\r\n *\r\n *  Throws:                  P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,\r\n *                           naturalLogarithm, config, parseOther, random, Decimal\r\n */\r\n\r\n\r\nfunction digitsToString(d) {\r\n  var i, k, ws,\r\n    indexOfLastWord = d.length - 1,\r\n    str = '',\r\n    w = d[0];\r\n\r\n  if (indexOfLastWord > 0) {\r\n    str += w;\r\n    for (i = 1; i < indexOfLastWord; i++) {\r\n      ws = d[i] + '';\r\n      k = LOG_BASE - ws.length;\r\n      if (k) str += getZeroString(k);\r\n      str += ws;\r\n    }\r\n\r\n    w = d[i];\r\n    ws = w + '';\r\n    k = LOG_BASE - ws.length;\r\n    if (k) str += getZeroString(k);\r\n  } else if (w === 0) {\r\n    return '0';\r\n  }\r\n\r\n  // Remove trailing zeros of last w.\r\n  for (; w % 10 === 0;) w /= 10;\r\n\r\n  return str + w;\r\n}\r\n\r\n\r\nfunction checkInt32(i, min, max) {\r\n  if (i !== ~~i || i < min || i > max) {\r\n    throw Error(invalidArgument + i);\r\n  }\r\n}\r\n\r\n\r\n/*\r\n * Check 5 rounding digits if `repeating` is null, 4 otherwise.\r\n * `repeating == null` if caller is `log` or `pow`,\r\n * `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.\r\n */\r\nfunction checkRoundingDigits(d, i, rm, repeating) {\r\n  var di, k, r, rd;\r\n\r\n  // Get the length of the first word of the array d.\r\n  for (k = d[0]; k >= 10; k /= 10) --i;\r\n\r\n  // Is the rounding digit in the first word of d?\r\n  if (--i < 0) {\r\n    i += LOG_BASE;\r\n    di = 0;\r\n  } else {\r\n    di = Math.ceil((i + 1) / LOG_BASE);\r\n    i %= LOG_BASE;\r\n  }\r\n\r\n  // i is the index (0 - 6) of the rounding digit.\r\n  // E.g. if within the word 3487563 the first rounding digit is 5,\r\n  // then i = 4, k = 1000, rd = 3487563 % 1000 = 563\r\n  k = mathpow(10, LOG_BASE - i);\r\n  rd = d[di] % k | 0;\r\n\r\n  if (repeating == null) {\r\n    if (i < 3) {\r\n      if (i == 0) rd = rd / 100 | 0;\r\n      else if (i == 1) rd = rd / 10 | 0;\r\n      r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;\r\n    } else {\r\n      r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&\r\n        (d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||\r\n          (rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;\r\n    }\r\n  } else {\r\n    if (i < 4) {\r\n      if (i == 0) rd = rd / 1000 | 0;\r\n      else if (i == 1) rd = rd / 100 | 0;\r\n      else if (i == 2) rd = rd / 10 | 0;\r\n      r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;\r\n    } else {\r\n      r = ((repeating || rm < 4) && rd + 1 == k ||\r\n      (!repeating && rm > 3) && rd + 1 == k / 2) &&\r\n        (d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;\r\n    }\r\n  }\r\n\r\n  return r;\r\n}\r\n\r\n\r\n// Convert string of `baseIn` to an array of numbers of `baseOut`.\r\n// Eg. convertBase('255', 10, 16) returns [15, 15].\r\n// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].\r\nfunction convertBase(str, baseIn, baseOut) {\r\n  var j,\r\n    arr = [0],\r\n    arrL,\r\n    i = 0,\r\n    strL = str.length;\r\n\r\n  for (; i < strL;) {\r\n    for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;\r\n    arr[0] += NUMERALS.indexOf(str.charAt(i++));\r\n    for (j = 0; j < arr.length; j++) {\r\n      if (arr[j] > baseOut - 1) {\r\n        if (arr[j + 1] === void 0) arr[j + 1] = 0;\r\n        arr[j + 1] += arr[j] / baseOut | 0;\r\n        arr[j] %= baseOut;\r\n      }\r\n    }\r\n  }\r\n\r\n  return arr.reverse();\r\n}\r\n\r\n\r\n/*\r\n * cos(x) = 1 - x^2/2! + x^4/4! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction cosine(Ctor, x) {\r\n  var k, len, y;\r\n\r\n  if (x.isZero()) return x;\r\n\r\n  // Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1\r\n  // i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1\r\n\r\n  // Estimate the optimum number of times to use the argument reduction.\r\n  len = x.d.length;\r\n  if (len < 32) {\r\n    k = Math.ceil(len / 3);\r\n    y = (1 / tinyPow(4, k)).toString();\r\n  } else {\r\n    k = 16;\r\n    y = '2.3283064365386962890625e-10';\r\n  }\r\n\r\n  Ctor.precision += k;\r\n\r\n  x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));\r\n\r\n  // Reverse argument reduction\r\n  for (var i = k; i--;) {\r\n    var cos2x = x.times(x);\r\n    x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);\r\n  }\r\n\r\n  Ctor.precision -= k;\r\n\r\n  return x;\r\n}\r\n\r\n\r\n/*\r\n * Perform division in the specified base.\r\n */\r\nvar divide = (function () {\r\n\r\n  // Assumes non-zero x and k, and hence non-zero result.\r\n  function multiplyInteger(x, k, base) {\r\n    var temp,\r\n      carry = 0,\r\n      i = x.length;\r\n\r\n    for (x = x.slice(); i--;) {\r\n      temp = x[i] * k + carry;\r\n      x[i] = temp % base | 0;\r\n      carry = temp / base | 0;\r\n    }\r\n\r\n    if (carry) x.unshift(carry);\r\n\r\n    return x;\r\n  }\r\n\r\n  function compare(a, b, aL, bL) {\r\n    var i, r;\r\n\r\n    if (aL != bL) {\r\n      r = aL > bL ? 1 : -1;\r\n    } else {\r\n      for (i = r = 0; i < aL; i++) {\r\n        if (a[i] != b[i]) {\r\n          r = a[i] > b[i] ? 1 : -1;\r\n          break;\r\n        }\r\n      }\r\n    }\r\n\r\n    return r;\r\n  }\r\n\r\n  function subtract(a, b, aL, base) {\r\n    var i = 0;\r\n\r\n    // Subtract b from a.\r\n    for (; aL--;) {\r\n      a[aL] -= i;\r\n      i = a[aL] < b[aL] ? 1 : 0;\r\n      a[aL] = i * base + a[aL] - b[aL];\r\n    }\r\n\r\n    // Remove leading zeros.\r\n    for (; !a[0] && a.length > 1;) a.shift();\r\n  }\r\n\r\n  return function (x, y, pr, rm, dp, base) {\r\n    var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,\r\n      yL, yz,\r\n      Ctor = x.constructor,\r\n      sign = x.s == y.s ? 1 : -1,\r\n      xd = x.d,\r\n      yd = y.d;\r\n\r\n    // Either NaN, Infinity or 0?\r\n    if (!xd || !xd[0] || !yd || !yd[0]) {\r\n\r\n      return new Ctor(// Return NaN if either NaN, or both Infinity or 0.\r\n        !x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :\r\n\r\n        // Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.\r\n        xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);\r\n    }\r\n\r\n    if (base) {\r\n      logBase = 1;\r\n      e = x.e - y.e;\r\n    } else {\r\n      base = BASE;\r\n      logBase = LOG_BASE;\r\n      e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);\r\n    }\r\n\r\n    yL = yd.length;\r\n    xL = xd.length;\r\n    q = new Ctor(sign);\r\n    qd = q.d = [];\r\n\r\n    // Result exponent may be one less than e.\r\n    // The digit array of a Decimal from toStringBinary may have trailing zeros.\r\n    for (i = 0; yd[i] == (xd[i] || 0); i++);\r\n\r\n    if (yd[i] > (xd[i] || 0)) e--;\r\n\r\n    if (pr == null) {\r\n      sd = pr = Ctor.precision;\r\n      rm = Ctor.rounding;\r\n    } else if (dp) {\r\n      sd = pr + (x.e - y.e) + 1;\r\n    } else {\r\n      sd = pr;\r\n    }\r\n\r\n    if (sd < 0) {\r\n      qd.push(1);\r\n      more = true;\r\n    } else {\r\n\r\n      // Convert precision in number of base 10 digits to base 1e7 digits.\r\n      sd = sd / logBase + 2 | 0;\r\n      i = 0;\r\n\r\n      // divisor < 1e7\r\n      if (yL == 1) {\r\n        k = 0;\r\n        yd = yd[0];\r\n        sd++;\r\n\r\n        // k is the carry.\r\n        for (; (i < xL || k) && sd--; i++) {\r\n          t = k * base + (xd[i] || 0);\r\n          qd[i] = t / yd | 0;\r\n          k = t % yd | 0;\r\n        }\r\n\r\n        more = k || i < xL;\r\n\r\n      // divisor >= 1e7\r\n      } else {\r\n\r\n        // Normalise xd and yd so highest order digit of yd is >= base/2\r\n        k = base / (yd[0] + 1) | 0;\r\n\r\n        if (k > 1) {\r\n          yd = multiplyInteger(yd, k, base);\r\n          xd = multiplyInteger(xd, k, base);\r\n          yL = yd.length;\r\n          xL = xd.length;\r\n        }\r\n\r\n        xi = yL;\r\n        rem = xd.slice(0, yL);\r\n        remL = rem.length;\r\n\r\n        // Add zeros to make remainder as long as divisor.\r\n        for (; remL < yL;) rem[remL++] = 0;\r\n\r\n        yz = yd.slice();\r\n        yz.unshift(0);\r\n        yd0 = yd[0];\r\n\r\n        if (yd[1] >= base / 2) ++yd0;\r\n\r\n        do {\r\n          k = 0;\r\n\r\n          // Compare divisor and remainder.\r\n          cmp = compare(yd, rem, yL, remL);\r\n\r\n          // If divisor < remainder.\r\n          if (cmp < 0) {\r\n\r\n            // Calculate trial digit, k.\r\n            rem0 = rem[0];\r\n            if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n            // k will be how many times the divisor goes into the current remainder.\r\n            k = rem0 / yd0 | 0;\r\n\r\n            //  Algorithm:\r\n            //  1. product = divisor * trial digit (k)\r\n            //  2. if product > remainder: product -= divisor, k--\r\n            //  3. remainder -= product\r\n            //  4. if product was < remainder at 2:\r\n            //    5. compare new remainder and divisor\r\n            //    6. If remainder > divisor: remainder -= divisor, k++\r\n\r\n            if (k > 1) {\r\n              if (k >= base) k = base - 1;\r\n\r\n              // product = divisor * trial digit.\r\n              prod = multiplyInteger(yd, k, base);\r\n              prodL = prod.length;\r\n              remL = rem.length;\r\n\r\n              // Compare product and remainder.\r\n              cmp = compare(prod, rem, prodL, remL);\r\n\r\n              // product > remainder.\r\n              if (cmp == 1) {\r\n                k--;\r\n\r\n                // Subtract divisor from product.\r\n                subtract(prod, yL < prodL ? yz : yd, prodL, base);\r\n              }\r\n            } else {\r\n\r\n              // cmp is -1.\r\n              // If k is 0, there is no need to compare yd and rem again below, so change cmp to 1\r\n              // to avoid it. If k is 1 there is a need to compare yd and rem again below.\r\n              if (k == 0) cmp = k = 1;\r\n              prod = yd.slice();\r\n            }\r\n\r\n            prodL = prod.length;\r\n            if (prodL < remL) prod.unshift(0);\r\n\r\n            // Subtract product from remainder.\r\n            subtract(rem, prod, remL, base);\r\n\r\n            // If product was < previous remainder.\r\n            if (cmp == -1) {\r\n              remL = rem.length;\r\n\r\n              // Compare divisor and new remainder.\r\n              cmp = compare(yd, rem, yL, remL);\r\n\r\n              // If divisor < new remainder, subtract divisor from remainder.\r\n              if (cmp < 1) {\r\n                k++;\r\n\r\n                // Subtract divisor from remainder.\r\n                subtract(rem, yL < remL ? yz : yd, remL, base);\r\n              }\r\n            }\r\n\r\n            remL = rem.length;\r\n          } else if (cmp === 0) {\r\n            k++;\r\n            rem = [0];\r\n          }    // if cmp === 1, k will be 0\r\n\r\n          // Add the next digit, k, to the result array.\r\n          qd[i++] = k;\r\n\r\n          // Update the remainder.\r\n          if (cmp && rem[0]) {\r\n            rem[remL++] = xd[xi] || 0;\r\n          } else {\r\n            rem = [xd[xi]];\r\n            remL = 1;\r\n          }\r\n\r\n        } while ((xi++ < xL || rem[0] !== void 0) && sd--);\r\n\r\n        more = rem[0] !== void 0;\r\n      }\r\n\r\n      // Leading zero?\r\n      if (!qd[0]) qd.shift();\r\n    }\r\n\r\n    // logBase is 1 when divide is being used for base conversion.\r\n    if (logBase == 1) {\r\n      q.e = e;\r\n      inexact = more;\r\n    } else {\r\n\r\n      // To calculate q.e, first get the number of digits of qd[0].\r\n      for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;\r\n      q.e = i + e * logBase - 1;\r\n\r\n      finalise(q, dp ? pr + q.e + 1 : pr, rm, more);\r\n    }\r\n\r\n    return q;\r\n  };\r\n})();\r\n\r\n\r\n/*\r\n * Round `x` to `sd` significant digits using rounding mode `rm`.\r\n * Check for over/under-flow.\r\n */\r\n function finalise(x, sd, rm, isTruncated) {\r\n  var digits, i, j, k, rd, roundUp, w, xd, xdi,\r\n    Ctor = x.constructor;\r\n\r\n  // Don't round if sd is null or undefined.\r\n  out: if (sd != null) {\r\n    xd = x.d;\r\n\r\n    // Infinity/NaN.\r\n    if (!xd) return x;\r\n\r\n    // rd: the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n    // w: the word of xd containing rd, a base 1e7 number.\r\n    // xdi: the index of w within xd.\r\n    // digits: the number of digits of w.\r\n    // i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if\r\n    // they had leading zeros)\r\n    // j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).\r\n\r\n    // Get the length of the first word of the digits array xd.\r\n    for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;\r\n    i = sd - digits;\r\n\r\n    // Is the rounding digit in the first word of xd?\r\n    if (i < 0) {\r\n      i += LOG_BASE;\r\n      j = sd;\r\n      w = xd[xdi = 0];\r\n\r\n      // Get the rounding digit at index j of w.\r\n      rd = w / mathpow(10, digits - j - 1) % 10 | 0;\r\n    } else {\r\n      xdi = Math.ceil((i + 1) / LOG_BASE);\r\n      k = xd.length;\r\n      if (xdi >= k) {\r\n        if (isTruncated) {\r\n\r\n          // Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.\r\n          for (; k++ <= xdi;) xd.push(0);\r\n          w = rd = 0;\r\n          digits = 1;\r\n          i %= LOG_BASE;\r\n          j = i - LOG_BASE + 1;\r\n        } else {\r\n          break out;\r\n        }\r\n      } else {\r\n        w = k = xd[xdi];\r\n\r\n        // Get the number of digits of w.\r\n        for (digits = 1; k >= 10; k /= 10) digits++;\r\n\r\n        // Get the index of rd within w.\r\n        i %= LOG_BASE;\r\n\r\n        // Get the index of rd within w, adjusted for leading zeros.\r\n        // The number of leading zeros of w is given by LOG_BASE - digits.\r\n        j = i - LOG_BASE + digits;\r\n\r\n        // Get the rounding digit at index j of w.\r\n        rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;\r\n      }\r\n    }\r\n\r\n    // Are there any non-zero digits after the rounding digit?\r\n    isTruncated = isTruncated || sd < 0 ||\r\n      xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));\r\n\r\n    // The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right\r\n    // of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression\r\n    // will give 714.\r\n\r\n    roundUp = rm < 4\r\n      ? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n      : rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&\r\n\r\n        // Check whether the digit to the left of the rounding digit is odd.\r\n        ((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||\r\n          rm == (x.s < 0 ? 8 : 7));\r\n\r\n    if (sd < 1 || !xd[0]) {\r\n      xd.length = 0;\r\n      if (roundUp) {\r\n\r\n        // Convert sd to decimal places.\r\n        sd -= x.e + 1;\r\n\r\n        // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n        xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);\r\n        x.e = -sd || 0;\r\n      } else {\r\n\r\n        // Zero.\r\n        xd[0] = x.e = 0;\r\n      }\r\n\r\n      return x;\r\n    }\r\n\r\n    // Remove excess digits.\r\n    if (i == 0) {\r\n      xd.length = xdi;\r\n      k = 1;\r\n      xdi--;\r\n    } else {\r\n      xd.length = xdi + 1;\r\n      k = mathpow(10, LOG_BASE - i);\r\n\r\n      // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n      // j > 0 means i > number of leading zeros of w.\r\n      xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;\r\n    }\r\n\r\n    if (roundUp) {\r\n      for (;;) {\r\n\r\n        // Is the digit to be rounded up in the first word of xd?\r\n        if (xdi == 0) {\r\n\r\n          // i will be the length of xd[0] before k is added.\r\n          for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;\r\n          j = xd[0] += k;\r\n          for (k = 1; j >= 10; j /= 10) k++;\r\n\r\n          // if i != k the length has increased.\r\n          if (i != k) {\r\n            x.e++;\r\n            if (xd[0] == BASE) xd[0] = 1;\r\n          }\r\n\r\n          break;\r\n        } else {\r\n          xd[xdi] += k;\r\n          if (xd[xdi] != BASE) break;\r\n          xd[xdi--] = 0;\r\n          k = 1;\r\n        }\r\n      }\r\n    }\r\n\r\n    // Remove trailing zeros.\r\n    for (i = xd.length; xd[--i] === 0;) xd.pop();\r\n  }\r\n\r\n  if (external) {\r\n\r\n    // Overflow?\r\n    if (x.e > Ctor.maxE) {\r\n\r\n      // Infinity.\r\n      x.d = null;\r\n      x.e = NaN;\r\n\r\n    // Underflow?\r\n    } else if (x.e < Ctor.minE) {\r\n\r\n      // Zero.\r\n      x.e = 0;\r\n      x.d = [0];\r\n      // Ctor.underflow = true;\r\n    } // else Ctor.underflow = false;\r\n  }\r\n\r\n  return x;\r\n}\r\n\r\n\r\nfunction finiteToString(x, isExp, sd) {\r\n  if (!x.isFinite()) return nonFiniteToString(x);\r\n  var k,\r\n    e = x.e,\r\n    str = digitsToString(x.d),\r\n    len = str.length;\r\n\r\n  if (isExp) {\r\n    if (sd && (k = sd - len) > 0) {\r\n      str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);\r\n    } else if (len > 1) {\r\n      str = str.charAt(0) + '.' + str.slice(1);\r\n    }\r\n\r\n    str = str + (x.e < 0 ? 'e' : 'e+') + x.e;\r\n  } else if (e < 0) {\r\n    str = '0.' + getZeroString(-e - 1) + str;\r\n    if (sd && (k = sd - len) > 0) str += getZeroString(k);\r\n  } else if (e >= len) {\r\n    str += getZeroString(e + 1 - len);\r\n    if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);\r\n  } else {\r\n    if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);\r\n    if (sd && (k = sd - len) > 0) {\r\n      if (e + 1 === len) str += '.';\r\n      str += getZeroString(k);\r\n    }\r\n  }\r\n\r\n  return str;\r\n}\r\n\r\n\r\n// Calculate the base 10 exponent from the base 1e7 exponent.\r\nfunction getBase10Exponent(digits, e) {\r\n  var w = digits[0];\r\n\r\n  // Add the number of digits of the first word of the digits array.\r\n  for ( e *= LOG_BASE; w >= 10; w /= 10) e++;\r\n  return e;\r\n}\r\n\r\n\r\nfunction getLn10(Ctor, sd, pr) {\r\n  if (sd > LN10_PRECISION) {\r\n\r\n    // Reset global state in case the exception is caught.\r\n    external = true;\r\n    if (pr) Ctor.precision = pr;\r\n    throw Error(precisionLimitExceeded);\r\n  }\r\n  return finalise(new Ctor(LN10), sd, 1, true);\r\n}\r\n\r\n\r\nfunction getPi(Ctor, sd, rm) {\r\n  if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);\r\n  return finalise(new Ctor(PI), sd, rm, true);\r\n}\r\n\r\n\r\nfunction getPrecision(digits) {\r\n  var w = digits.length - 1,\r\n    len = w * LOG_BASE + 1;\r\n\r\n  w = digits[w];\r\n\r\n  // If non-zero...\r\n  if (w) {\r\n\r\n    // Subtract the number of trailing zeros of the last word.\r\n    for (; w % 10 == 0; w /= 10) len--;\r\n\r\n    // Add the number of digits of the first word.\r\n    for (w = digits[0]; w >= 10; w /= 10) len++;\r\n  }\r\n\r\n  return len;\r\n}\r\n\r\n\r\nfunction getZeroString(k) {\r\n  var zs = '';\r\n  for (; k--;) zs += '0';\r\n  return zs;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an\r\n * integer of type number.\r\n *\r\n * Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.\r\n *\r\n */\r\nfunction intPow(Ctor, x, n, pr) {\r\n  var isTruncated,\r\n    r = new Ctor(1),\r\n\r\n    // Max n of 9007199254740991 takes 53 loop iterations.\r\n    // Maximum digits array length; leaves [28, 34] guard digits.\r\n    k = Math.ceil(pr / LOG_BASE + 4);\r\n\r\n  external = false;\r\n\r\n  for (;;) {\r\n    if (n % 2) {\r\n      r = r.times(x);\r\n      if (truncate(r.d, k)) isTruncated = true;\r\n    }\r\n\r\n    n = mathfloor(n / 2);\r\n    if (n === 0) {\r\n\r\n      // To ensure correct rounding when r.d is truncated, increment the last word if it is zero.\r\n      n = r.d.length - 1;\r\n      if (isTruncated && r.d[n] === 0) ++r.d[n];\r\n      break;\r\n    }\r\n\r\n    x = x.times(x);\r\n    truncate(x.d, k);\r\n  }\r\n\r\n  external = true;\r\n\r\n  return r;\r\n}\r\n\r\n\r\nfunction isOdd(n) {\r\n  return n.d[n.d.length - 1] & 1;\r\n}\r\n\r\n\r\n/*\r\n * Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.\r\n */\r\nfunction maxOrMin(Ctor, args, ltgt) {\r\n  var y,\r\n    x = new Ctor(args[0]),\r\n    i = 0;\r\n\r\n  for (; ++i < args.length;) {\r\n    y = new Ctor(args[i]);\r\n    if (!y.s) {\r\n      x = y;\r\n      break;\r\n    } else if (x[ltgt](y)) {\r\n      x = y;\r\n    }\r\n  }\r\n\r\n  return x;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n * Taylor/Maclaurin series.\r\n *\r\n * exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...\r\n *\r\n * Argument reduction:\r\n *   Repeat x = x / 32, k += 5, until |x| < 0.1\r\n *   exp(x) = exp(x / 2^k)^(2^k)\r\n *\r\n * Previously, the argument was initially reduced by\r\n * exp(x) = exp(r) * 10^k  where r = x - k * ln10, k = floor(x / ln10)\r\n * to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was\r\n * found to be slower than just dividing repeatedly by 32 as above.\r\n *\r\n * Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000\r\n * Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000\r\n * (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)\r\n *\r\n *  exp(Infinity)  = Infinity\r\n *  exp(-Infinity) = 0\r\n *  exp(NaN)       = NaN\r\n *  exp(±0)        = 1\r\n *\r\n *  exp(x) is non-terminating for any finite, non-zero x.\r\n *\r\n *  The result will always be correctly rounded.\r\n *\r\n */\r\nfunction naturalExponential(x, sd) {\r\n  var denominator, guard, j, pow, sum, t, wpr,\r\n    rep = 0,\r\n    i = 0,\r\n    k = 0,\r\n    Ctor = x.constructor,\r\n    rm = Ctor.rounding,\r\n    pr = Ctor.precision;\r\n\r\n  // 0/NaN/Infinity?\r\n  if (!x.d || !x.d[0] || x.e > 17) {\r\n\r\n    return new Ctor(x.d\r\n      ? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0\r\n      : x.s ? x.s < 0 ? 0 : x : 0 / 0);\r\n  }\r\n\r\n  if (sd == null) {\r\n    external = false;\r\n    wpr = pr;\r\n  } else {\r\n    wpr = sd;\r\n  }\r\n\r\n  t = new Ctor(0.03125);\r\n\r\n  // while abs(x) >= 0.1\r\n  while (x.e > -2) {\r\n\r\n    // x = x / 2^5\r\n    x = x.times(t);\r\n    k += 5;\r\n  }\r\n\r\n  // Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision\r\n  // necessary to ensure the first 4 rounding digits are correct.\r\n  guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;\r\n  wpr += guard;\r\n  denominator = pow = sum = new Ctor(1);\r\n  Ctor.precision = wpr;\r\n\r\n  for (;;) {\r\n    pow = finalise(pow.times(x), wpr, 1);\r\n    denominator = denominator.times(++i);\r\n    t = sum.plus(divide(pow, denominator, wpr, 1));\r\n\r\n    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n      j = k;\r\n      while (j--) sum = finalise(sum.times(sum), wpr, 1);\r\n\r\n      // Check to see if the first 4 rounding digits are [49]999.\r\n      // If so, repeat the summation with a higher precision, otherwise\r\n      // e.g. with precision: 18, rounding: 1\r\n      // exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)\r\n      // `wpr - guard` is the index of first rounding digit.\r\n      if (sd == null) {\r\n\r\n        if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n          Ctor.precision = wpr += 10;\r\n          denominator = pow = t = new Ctor(1);\r\n          i = 0;\r\n          rep++;\r\n        } else {\r\n          return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n        }\r\n      } else {\r\n        Ctor.precision = pr;\r\n        return sum;\r\n      }\r\n    }\r\n\r\n    sum = t;\r\n  }\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant\r\n * digits.\r\n *\r\n *  ln(-n)        = NaN\r\n *  ln(0)         = -Infinity\r\n *  ln(-0)        = -Infinity\r\n *  ln(1)         = 0\r\n *  ln(Infinity)  = Infinity\r\n *  ln(-Infinity) = NaN\r\n *  ln(NaN)       = NaN\r\n *\r\n *  ln(n) (n != 1) is non-terminating.\r\n *\r\n */\r\nfunction naturalLogarithm(y, sd) {\r\n  var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,\r\n    n = 1,\r\n    guard = 10,\r\n    x = y,\r\n    xd = x.d,\r\n    Ctor = x.constructor,\r\n    rm = Ctor.rounding,\r\n    pr = Ctor.precision;\r\n\r\n  // Is x negative or Infinity, NaN, 0 or 1?\r\n  if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {\r\n    return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);\r\n  }\r\n\r\n  if (sd == null) {\r\n    external = false;\r\n    wpr = pr;\r\n  } else {\r\n    wpr = sd;\r\n  }\r\n\r\n  Ctor.precision = wpr += guard;\r\n  c = digitsToString(xd);\r\n  c0 = c.charAt(0);\r\n\r\n  if (Math.abs(e = x.e) < 1.5e15) {\r\n\r\n    // Argument reduction.\r\n    // The series converges faster the closer the argument is to 1, so using\r\n    // ln(a^b) = b * ln(a),   ln(a) = ln(a^b) / b\r\n    // multiply the argument by itself until the leading digits of the significand are 7, 8, 9,\r\n    // 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can\r\n    // later be divided by this number, then separate out the power of 10 using\r\n    // ln(a*10^b) = ln(a) + b*ln(10).\r\n\r\n    // max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).\r\n    //while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {\r\n    // max n is 6 (gives 0.7 - 1.3)\r\n    while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {\r\n      x = x.times(y);\r\n      c = digitsToString(x.d);\r\n      c0 = c.charAt(0);\r\n      n++;\r\n    }\r\n\r\n    e = x.e;\r\n\r\n    if (c0 > 1) {\r\n      x = new Ctor('0.' + c);\r\n      e++;\r\n    } else {\r\n      x = new Ctor(c0 + '.' + c.slice(1));\r\n    }\r\n  } else {\r\n\r\n    // The argument reduction method above may result in overflow if the argument y is a massive\r\n    // number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this\r\n    // function using ln(x*10^e) = ln(x) + e*ln(10).\r\n    t = getLn10(Ctor, wpr + 2, pr).times(e + '');\r\n    x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);\r\n    Ctor.precision = pr;\r\n\r\n    return sd == null ? finalise(x, pr, rm, external = true) : x;\r\n  }\r\n\r\n  // x1 is x reduced to a value near 1.\r\n  x1 = x;\r\n\r\n  // Taylor series.\r\n  // ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)\r\n  // where x = (y - 1)/(y + 1)    (|x| < 1)\r\n  sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);\r\n  x2 = finalise(x.times(x), wpr, 1);\r\n  denominator = 3;\r\n\r\n  for (;;) {\r\n    numerator = finalise(numerator.times(x2), wpr, 1);\r\n    t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));\r\n\r\n    if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {\r\n      sum = sum.times(2);\r\n\r\n      // Reverse the argument reduction. Check that e is not 0 because, besides preventing an\r\n      // unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.\r\n      if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));\r\n      sum = divide(sum, new Ctor(n), wpr, 1);\r\n\r\n      // Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has\r\n      // been repeated previously) and the first 4 rounding digits 9999?\r\n      // If so, restart the summation with a higher precision, otherwise\r\n      // e.g. with precision: 12, rounding: 1\r\n      // ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.\r\n      // `wpr - guard` is the index of first rounding digit.\r\n      if (sd == null) {\r\n        if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {\r\n          Ctor.precision = wpr += guard;\r\n          t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);\r\n          x2 = finalise(x.times(x), wpr, 1);\r\n          denominator = rep = 1;\r\n        } else {\r\n          return finalise(sum, Ctor.precision = pr, rm, external = true);\r\n        }\r\n      } else {\r\n        Ctor.precision = pr;\r\n        return sum;\r\n      }\r\n    }\r\n\r\n    sum = t;\r\n    denominator += 2;\r\n  }\r\n}\r\n\r\n\r\n// ±Infinity, NaN.\r\nfunction nonFiniteToString(x) {\r\n  // Unsigned.\r\n  return String(x.s * x.s / 0);\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from string `str`.\r\n */\r\nfunction parseDecimal(x, str) {\r\n  var e, i, len;\r\n\r\n  // Decimal point?\r\n  if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n  // Exponential form?\r\n  if ((i = str.search(/e/i)) > 0) {\r\n\r\n    // Determine exponent.\r\n    if (e < 0) e = i;\r\n    e += +str.slice(i + 1);\r\n    str = str.substring(0, i);\r\n  } else if (e < 0) {\r\n\r\n    // Integer.\r\n    e = str.length;\r\n  }\r\n\r\n  // Determine leading zeros.\r\n  for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n  // Determine trailing zeros.\r\n  for (len = str.length; str.charCodeAt(len - 1) === 48; --len);\r\n  str = str.slice(i, len);\r\n\r\n  if (str) {\r\n    len -= i;\r\n    x.e = e = e - i - 1;\r\n    x.d = [];\r\n\r\n    // Transform base\r\n\r\n    // e is the base 10 exponent.\r\n    // i is where to slice str to get the first word of the digits array.\r\n    i = (e + 1) % LOG_BASE;\r\n    if (e < 0) i += LOG_BASE;\r\n\r\n    if (i < len) {\r\n      if (i) x.d.push(+str.slice(0, i));\r\n      for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));\r\n      str = str.slice(i);\r\n      i = LOG_BASE - str.length;\r\n    } else {\r\n      i -= len;\r\n    }\r\n\r\n    for (; i--;) str += '0';\r\n    x.d.push(+str);\r\n\r\n    if (external) {\r\n\r\n      // Overflow?\r\n      if (x.e > x.constructor.maxE) {\r\n\r\n        // Infinity.\r\n        x.d = null;\r\n        x.e = NaN;\r\n\r\n      // Underflow?\r\n      } else if (x.e < x.constructor.minE) {\r\n\r\n        // Zero.\r\n        x.e = 0;\r\n        x.d = [0];\r\n        // x.constructor.underflow = true;\r\n      } // else x.constructor.underflow = false;\r\n    }\r\n  } else {\r\n\r\n    // Zero.\r\n    x.e = 0;\r\n    x.d = [0];\r\n  }\r\n\r\n  return x;\r\n}\r\n\r\n\r\n/*\r\n * Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.\r\n */\r\nfunction parseOther(x, str) {\r\n  var base, Ctor, divisor, i, isFloat, len, p, xd, xe;\r\n\r\n  if (str.indexOf('_') > -1) {\r\n    str = str.replace(/(\\d)_(?=\\d)/g, '$1');\r\n    if (isDecimal.test(str)) return parseDecimal(x, str);\r\n  } else if (str === 'Infinity' || str === 'NaN') {\r\n    if (!+str) x.s = NaN;\r\n    x.e = NaN;\r\n    x.d = null;\r\n    return x;\r\n  }\r\n\r\n  if (isHex.test(str))  {\r\n    base = 16;\r\n    str = str.toLowerCase();\r\n  } else if (isBinary.test(str))  {\r\n    base = 2;\r\n  } else if (isOctal.test(str))  {\r\n    base = 8;\r\n  } else {\r\n    throw Error(invalidArgument + str);\r\n  }\r\n\r\n  // Is there a binary exponent part?\r\n  i = str.search(/p/i);\r\n\r\n  if (i > 0) {\r\n    p = +str.slice(i + 1);\r\n    str = str.substring(2, i);\r\n  } else {\r\n    str = str.slice(2);\r\n  }\r\n\r\n  // Convert `str` as an integer then divide the result by `base` raised to a power such that the\r\n  // fraction part will be restored.\r\n  i = str.indexOf('.');\r\n  isFloat = i >= 0;\r\n  Ctor = x.constructor;\r\n\r\n  if (isFloat) {\r\n    str = str.replace('.', '');\r\n    len = str.length;\r\n    i = len - i;\r\n\r\n    // log[10](16) = 1.2041... , log[10](88) = 1.9444....\r\n    divisor = intPow(Ctor, new Ctor(base), i, i * 2);\r\n  }\r\n\r\n  xd = convertBase(str, base, BASE);\r\n  xe = xd.length - 1;\r\n\r\n  // Remove trailing zeros.\r\n  for (i = xe; xd[i] === 0; --i) xd.pop();\r\n  if (i < 0) return new Ctor(x.s * 0);\r\n  x.e = getBase10Exponent(xd, xe);\r\n  x.d = xd;\r\n  external = false;\r\n\r\n  // At what precision to perform the division to ensure exact conversion?\r\n  // maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)\r\n  // log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412\r\n  // E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.\r\n  // maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount\r\n  // Therefore using 4 * the number of digits of str will always be enough.\r\n  if (isFloat) x = divide(x, divisor, len * 4);\r\n\r\n  // Multiply by the binary exponent part if present.\r\n  if (p) x = x.times(Math.abs(p) < 54 ? mathpow(2, p) : Decimal.pow(2, p));\r\n  external = true;\r\n\r\n  return x;\r\n}\r\n\r\n\r\n/*\r\n * sin(x) = x - x^3/3! + x^5/5! - ...\r\n * |x| < pi/2\r\n *\r\n */\r\nfunction sine(Ctor, x) {\r\n  var k,\r\n    len = x.d.length;\r\n\r\n  if (len < 3) {\r\n    return x.isZero() ? x : taylorSeries(Ctor, 2, x, x);\r\n  }\r\n\r\n  // Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)\r\n  // i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)\r\n  // and  sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))\r\n\r\n  // Estimate the optimum number of times to use the argument reduction.\r\n  k = 1.4 * Math.sqrt(len);\r\n  k = k > 16 ? 16 : k | 0;\r\n\r\n  x = x.times(1 / tinyPow(5, k));\r\n  x = taylorSeries(Ctor, 2, x, x);\r\n\r\n  // Reverse argument reduction\r\n  var sin2_x,\r\n    d5 = new Ctor(5),\r\n    d16 = new Ctor(16),\r\n    d20 = new Ctor(20);\r\n  for (; k--;) {\r\n    sin2_x = x.times(x);\r\n    x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));\r\n  }\r\n\r\n  return x;\r\n}\r\n\r\n\r\n// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.\r\nfunction taylorSeries(Ctor, n, x, y, isHyperbolic) {\r\n  var j, t, u, x2,\r\n    i = 1,\r\n    pr = Ctor.precision,\r\n    k = Math.ceil(pr / LOG_BASE);\r\n\r\n  external = false;\r\n  x2 = x.times(x);\r\n  u = new Ctor(y);\r\n\r\n  for (;;) {\r\n    t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);\r\n    u = isHyperbolic ? y.plus(t) : y.minus(t);\r\n    y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);\r\n    t = u.plus(y);\r\n\r\n    if (t.d[k] !== void 0) {\r\n      for (j = k; t.d[j] === u.d[j] && j--;);\r\n      if (j == -1) break;\r\n    }\r\n\r\n    j = u;\r\n    u = y;\r\n    y = t;\r\n    t = j;\r\n    i++;\r\n  }\r\n\r\n  external = true;\r\n  t.d.length = k + 1;\r\n\r\n  return t;\r\n}\r\n\r\n\r\n// Exponent e must be positive and non-zero.\r\nfunction tinyPow(b, e) {\r\n  var n = b;\r\n  while (--e) n *= b;\r\n  return n;\r\n}\r\n\r\n\r\n// Return the absolute value of `x` reduced to less than or equal to half pi.\r\nfunction toLessThanHalfPi(Ctor, x) {\r\n  var t,\r\n    isNeg = x.s < 0,\r\n    pi = getPi(Ctor, Ctor.precision, 1),\r\n    halfPi = pi.times(0.5);\r\n\r\n  x = x.abs();\r\n\r\n  if (x.lte(halfPi)) {\r\n    quadrant = isNeg ? 4 : 1;\r\n    return x;\r\n  }\r\n\r\n  t = x.divToInt(pi);\r\n\r\n  if (t.isZero()) {\r\n    quadrant = isNeg ? 3 : 2;\r\n  } else {\r\n    x = x.minus(t.times(pi));\r\n\r\n    // 0 <= x < pi\r\n    if (x.lte(halfPi)) {\r\n      quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);\r\n      return x;\r\n    }\r\n\r\n    quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);\r\n  }\r\n\r\n  return x.minus(pi).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return the value of Decimal `x` as a string in base `baseOut`.\r\n *\r\n * If the optional `sd` argument is present include a binary exponent suffix.\r\n */\r\nfunction toStringBinary(x, baseOut, sd, rm) {\r\n  var base, e, i, k, len, roundUp, str, xd, y,\r\n    Ctor = x.constructor,\r\n    isExp = sd !== void 0;\r\n\r\n  if (isExp) {\r\n    checkInt32(sd, 1, MAX_DIGITS);\r\n    if (rm === void 0) rm = Ctor.rounding;\r\n    else checkInt32(rm, 0, 8);\r\n  } else {\r\n    sd = Ctor.precision;\r\n    rm = Ctor.rounding;\r\n  }\r\n\r\n  if (!x.isFinite()) {\r\n    str = nonFiniteToString(x);\r\n  } else {\r\n    str = finiteToString(x);\r\n    i = str.indexOf('.');\r\n\r\n    // Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:\r\n    // maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))\r\n    // minBinaryExponent = floor(decimalExponent * log[2](10))\r\n    // log[2](10) = 3.321928094887362347870319429489390175864\r\n\r\n    if (isExp) {\r\n      base = 2;\r\n      if (baseOut == 16) {\r\n        sd = sd * 4 - 3;\r\n      } else if (baseOut == 8) {\r\n        sd = sd * 3 - 2;\r\n      }\r\n    } else {\r\n      base = baseOut;\r\n    }\r\n\r\n    // Convert the number as an integer then divide the result by its base raised to a power such\r\n    // that the fraction part will be restored.\r\n\r\n    // Non-integer.\r\n    if (i >= 0) {\r\n      str = str.replace('.', '');\r\n      y = new Ctor(1);\r\n      y.e = str.length - i;\r\n      y.d = convertBase(finiteToString(y), 10, base);\r\n      y.e = y.d.length;\r\n    }\r\n\r\n    xd = convertBase(str, 10, base);\r\n    e = len = xd.length;\r\n\r\n    // Remove trailing zeros.\r\n    for (; xd[--len] == 0;) xd.pop();\r\n\r\n    if (!xd[0]) {\r\n      str = isExp ? '0p+0' : '0';\r\n    } else {\r\n      if (i < 0) {\r\n        e--;\r\n      } else {\r\n        x = new Ctor(x);\r\n        x.d = xd;\r\n        x.e = e;\r\n        x = divide(x, y, sd, rm, 0, base);\r\n        xd = x.d;\r\n        e = x.e;\r\n        roundUp = inexact;\r\n      }\r\n\r\n      // The rounding digit, i.e. the digit after the digit that may be rounded up.\r\n      i = xd[sd];\r\n      k = base / 2;\r\n      roundUp = roundUp || xd[sd + 1] !== void 0;\r\n\r\n      roundUp = rm < 4\r\n        ? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))\r\n        : i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||\r\n          rm === (x.s < 0 ? 8 : 7));\r\n\r\n      xd.length = sd;\r\n\r\n      if (roundUp) {\r\n\r\n        // Rounding up may mean the previous digit has to be rounded up and so on.\r\n        for (; ++xd[--sd] > base - 1;) {\r\n          xd[sd] = 0;\r\n          if (!sd) {\r\n            ++e;\r\n            xd.unshift(1);\r\n          }\r\n        }\r\n      }\r\n\r\n      // Determine trailing zeros.\r\n      for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n      // E.g. [4, 11, 15] becomes 4bf.\r\n      for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n\r\n      // Add binary exponent suffix?\r\n      if (isExp) {\r\n        if (len > 1) {\r\n          if (baseOut == 16 || baseOut == 8) {\r\n            i = baseOut == 16 ? 4 : 3;\r\n            for (--len; len % i; len++) str += '0';\r\n            xd = convertBase(str, base, baseOut);\r\n            for (len = xd.length; !xd[len - 1]; --len);\r\n\r\n            // xd[0] will always be be 1\r\n            for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);\r\n          } else {\r\n            str = str.charAt(0) + '.' + str.slice(1);\r\n          }\r\n        }\r\n\r\n        str =  str + (e < 0 ? 'p' : 'p+') + e;\r\n      } else if (e < 0) {\r\n        for (; ++e;) str = '0' + str;\r\n        str = '0.' + str;\r\n      } else {\r\n        if (++e > len) for (e -= len; e-- ;) str += '0';\r\n        else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);\r\n      }\r\n    }\r\n\r\n    str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;\r\n  }\r\n\r\n  return x.s < 0 ? '-' + str : str;\r\n}\r\n\r\n\r\n// Does not strip trailing zeros.\r\nfunction truncate(arr, len) {\r\n  if (arr.length > len) {\r\n    arr.length = len;\r\n    return true;\r\n  }\r\n}\r\n\r\n\r\n// Decimal methods\r\n\r\n\r\n/*\r\n *  abs\r\n *  acos\r\n *  acosh\r\n *  add\r\n *  asin\r\n *  asinh\r\n *  atan\r\n *  atanh\r\n *  atan2\r\n *  cbrt\r\n *  ceil\r\n *  clamp\r\n *  clone\r\n *  config\r\n *  cos\r\n *  cosh\r\n *  div\r\n *  exp\r\n *  floor\r\n *  hypot\r\n *  ln\r\n *  log\r\n *  log2\r\n *  log10\r\n *  max\r\n *  min\r\n *  mod\r\n *  mul\r\n *  pow\r\n *  random\r\n *  round\r\n *  set\r\n *  sign\r\n *  sin\r\n *  sinh\r\n *  sqrt\r\n *  sub\r\n *  sum\r\n *  tan\r\n *  tanh\r\n *  trunc\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction abs(x) {\r\n  return new this(x).abs();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arccosine in radians of `x`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction acos(x) {\r\n  return new this(x).acos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction acosh(x) {\r\n  return new this(x).acosh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction add(x, y) {\r\n  return new this(x).plus(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction asin(x) {\r\n  return new this(x).asin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction asinh(x) {\r\n  return new this(x).asinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction atan(x) {\r\n  return new this(x).atan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to\r\n * `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction atanh(x) {\r\n  return new this(x).atanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi\r\n * (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-pi, pi]\r\n *\r\n * y {number|string|Decimal} The y-coordinate.\r\n * x {number|string|Decimal} The x-coordinate.\r\n *\r\n * atan2(±0, -0)               = ±pi\r\n * atan2(±0, +0)               = ±0\r\n * atan2(±0, -x)               = ±pi for x > 0\r\n * atan2(±0, x)                = ±0 for x > 0\r\n * atan2(-y, ±0)               = -pi/2 for y > 0\r\n * atan2(y, ±0)                = pi/2 for y > 0\r\n * atan2(±y, -Infinity)        = ±pi for finite y > 0\r\n * atan2(±y, +Infinity)        = ±0 for finite y > 0\r\n * atan2(±Infinity, x)         = ±pi/2 for finite x\r\n * atan2(±Infinity, -Infinity) = ±3*pi/4\r\n * atan2(±Infinity, +Infinity) = ±pi/4\r\n * atan2(NaN, x) = NaN\r\n * atan2(y, NaN) = NaN\r\n *\r\n */\r\nfunction atan2(y, x) {\r\n  y = new this(y);\r\n  x = new this(x);\r\n  var r,\r\n    pr = this.precision,\r\n    rm = this.rounding,\r\n    wpr = pr + 4;\r\n\r\n  // Either NaN\r\n  if (!y.s || !x.s) {\r\n    r = new this(NaN);\r\n\r\n  // Both ±Infinity\r\n  } else if (!y.d && !x.d) {\r\n    r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);\r\n    r.s = y.s;\r\n\r\n  // x is ±Infinity or y is ±0\r\n  } else if (!x.d || y.isZero()) {\r\n    r = x.s < 0 ? getPi(this, pr, rm) : new this(0);\r\n    r.s = y.s;\r\n\r\n  // y is ±Infinity or x is ±0\r\n  } else if (!y.d || x.isZero()) {\r\n    r = getPi(this, wpr, 1).times(0.5);\r\n    r.s = y.s;\r\n\r\n  // Both non-zero and finite\r\n  } else if (x.s < 0) {\r\n    this.precision = wpr;\r\n    this.rounding = 1;\r\n    r = this.atan(divide(y, x, wpr, 1));\r\n    x = getPi(this, wpr, 1);\r\n    this.precision = pr;\r\n    this.rounding = rm;\r\n    r = y.s < 0 ? r.minus(x) : r.plus(x);\r\n  } else {\r\n    r = this.atan(divide(y, x, wpr, 1));\r\n  }\r\n\r\n  return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction cbrt(x) {\r\n  return new this(x).cbrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ceil(x) {\r\n  return finalise(x = new this(x), x.e + 1, 2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` clamped to the range delineated by `min` and `max`.\r\n *\r\n * x {number|string|Decimal}\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nfunction clamp(x, min, max) {\r\n  return new this(x).clamp(min, max);\r\n}\r\n\r\n\r\n/*\r\n * Configure global settings for a Decimal constructor.\r\n *\r\n * `obj` is an object with one or more of the following properties,\r\n *\r\n *   precision  {number}\r\n *   rounding   {number}\r\n *   toExpNeg   {number}\r\n *   toExpPos   {number}\r\n *   maxE       {number}\r\n *   minE       {number}\r\n *   modulo     {number}\r\n *   crypto     {boolean|number}\r\n *   defaults   {true}\r\n *\r\n * E.g. Decimal.config({ precision: 20, rounding: 4 })\r\n *\r\n */\r\nfunction config(obj) {\r\n  if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');\r\n  var i, p, v,\r\n    useDefaults = obj.defaults === true,\r\n    ps = [\r\n      'precision', 1, MAX_DIGITS,\r\n      'rounding', 0, 8,\r\n      'toExpNeg', -EXP_LIMIT, 0,\r\n      'toExpPos', 0, EXP_LIMIT,\r\n      'maxE', 0, EXP_LIMIT,\r\n      'minE', -EXP_LIMIT, 0,\r\n      'modulo', 0, 9\r\n    ];\r\n\r\n  for (i = 0; i < ps.length; i += 3) {\r\n    if (p = ps[i], useDefaults) this[p] = DEFAULTS[p];\r\n    if ((v = obj[p]) !== void 0) {\r\n      if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;\r\n      else throw Error(invalidArgument + p + ': ' + v);\r\n    }\r\n  }\r\n\r\n  if (p = 'crypto', useDefaults) this[p] = DEFAULTS[p];\r\n  if ((v = obj[p]) !== void 0) {\r\n    if (v === true || v === false || v === 0 || v === 1) {\r\n      if (v) {\r\n        if (typeof crypto != 'undefined' && crypto &&\r\n          (crypto.getRandomValues || crypto.randomBytes)) {\r\n          this[p] = true;\r\n        } else {\r\n          throw Error(cryptoUnavailable);\r\n        }\r\n      } else {\r\n        this[p] = false;\r\n      }\r\n    } else {\r\n      throw Error(invalidArgument + p + ': ' + v);\r\n    }\r\n  }\r\n\r\n  return this;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cos(x) {\r\n  return new this(x).cos();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction cosh(x) {\r\n  return new this(x).cosh();\r\n}\r\n\r\n\r\n/*\r\n * Create and return a Decimal constructor with the same configuration properties as this Decimal\r\n * constructor.\r\n *\r\n */\r\nfunction clone(obj) {\r\n  var i, p, ps;\r\n\r\n  /*\r\n   * The Decimal constructor and exported function.\r\n   * Return a new Decimal instance.\r\n   *\r\n   * v {number|string|Decimal} A numeric value.\r\n   *\r\n   */\r\n  function Decimal(v) {\r\n    var e, i, t,\r\n      x = this;\r\n\r\n    // Decimal called without new.\r\n    if (!(x instanceof Decimal)) return new Decimal(v);\r\n\r\n    // Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor\r\n    // which points to Object.\r\n    x.constructor = Decimal;\r\n\r\n    // Duplicate.\r\n    if (isDecimalInstance(v)) {\r\n      x.s = v.s;\r\n\r\n      if (external) {\r\n        if (!v.d || v.e > Decimal.maxE) {\r\n\r\n          // Infinity.\r\n          x.e = NaN;\r\n          x.d = null;\r\n        } else if (v.e < Decimal.minE) {\r\n\r\n          // Zero.\r\n          x.e = 0;\r\n          x.d = [0];\r\n        } else {\r\n          x.e = v.e;\r\n          x.d = v.d.slice();\r\n        }\r\n      } else {\r\n        x.e = v.e;\r\n        x.d = v.d ? v.d.slice() : v.d;\r\n      }\r\n\r\n      return;\r\n    }\r\n\r\n    t = typeof v;\r\n\r\n    if (t === 'number') {\r\n      if (v === 0) {\r\n        x.s = 1 / v < 0 ? -1 : 1;\r\n        x.e = 0;\r\n        x.d = [0];\r\n        return;\r\n      }\r\n\r\n      if (v < 0) {\r\n        v = -v;\r\n        x.s = -1;\r\n      } else {\r\n        x.s = 1;\r\n      }\r\n\r\n      // Fast path for small integers.\r\n      if (v === ~~v && v < 1e7) {\r\n        for (e = 0, i = v; i >= 10; i /= 10) e++;\r\n\r\n        if (external) {\r\n          if (e > Decimal.maxE) {\r\n            x.e = NaN;\r\n            x.d = null;\r\n          } else if (e < Decimal.minE) {\r\n            x.e = 0;\r\n            x.d = [0];\r\n          } else {\r\n            x.e = e;\r\n            x.d = [v];\r\n          }\r\n        } else {\r\n          x.e = e;\r\n          x.d = [v];\r\n        }\r\n\r\n        return;\r\n\r\n      // Infinity, NaN.\r\n      } else if (v * 0 !== 0) {\r\n        if (!v) x.s = NaN;\r\n        x.e = NaN;\r\n        x.d = null;\r\n        return;\r\n      }\r\n\r\n      return parseDecimal(x, v.toString());\r\n\r\n    } else if (t !== 'string') {\r\n      throw Error(invalidArgument + v);\r\n    }\r\n\r\n    // Minus sign?\r\n    if ((i = v.charCodeAt(0)) === 45) {\r\n      v = v.slice(1);\r\n      x.s = -1;\r\n    } else {\r\n      // Plus sign?\r\n      if (i === 43) v = v.slice(1);\r\n      x.s = 1;\r\n    }\r\n\r\n    return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);\r\n  }\r\n\r\n  Decimal.prototype = P;\r\n\r\n  Decimal.ROUND_UP = 0;\r\n  Decimal.ROUND_DOWN = 1;\r\n  Decimal.ROUND_CEIL = 2;\r\n  Decimal.ROUND_FLOOR = 3;\r\n  Decimal.ROUND_HALF_UP = 4;\r\n  Decimal.ROUND_HALF_DOWN = 5;\r\n  Decimal.ROUND_HALF_EVEN = 6;\r\n  Decimal.ROUND_HALF_CEIL = 7;\r\n  Decimal.ROUND_HALF_FLOOR = 8;\r\n  Decimal.EUCLID = 9;\r\n\r\n  Decimal.config = Decimal.set = config;\r\n  Decimal.clone = clone;\r\n  Decimal.isDecimal = isDecimalInstance;\r\n\r\n  Decimal.abs = abs;\r\n  Decimal.acos = acos;\r\n  Decimal.acosh = acosh;        // ES6\r\n  Decimal.add = add;\r\n  Decimal.asin = asin;\r\n  Decimal.asinh = asinh;        // ES6\r\n  Decimal.atan = atan;\r\n  Decimal.atanh = atanh;        // ES6\r\n  Decimal.atan2 = atan2;\r\n  Decimal.cbrt = cbrt;          // ES6\r\n  Decimal.ceil = ceil;\r\n  Decimal.clamp = clamp;\r\n  Decimal.cos = cos;\r\n  Decimal.cosh = cosh;          // ES6\r\n  Decimal.div = div;\r\n  Decimal.exp = exp;\r\n  Decimal.floor = floor;\r\n  Decimal.hypot = hypot;        // ES6\r\n  Decimal.ln = ln;\r\n  Decimal.log = log;\r\n  Decimal.log10 = log10;        // ES6\r\n  Decimal.log2 = log2;          // ES6\r\n  Decimal.max = max;\r\n  Decimal.min = min;\r\n  Decimal.mod = mod;\r\n  Decimal.mul = mul;\r\n  Decimal.pow = pow;\r\n  Decimal.random = random;\r\n  Decimal.round = round;\r\n  Decimal.sign = sign;          // ES6\r\n  Decimal.sin = sin;\r\n  Decimal.sinh = sinh;          // ES6\r\n  Decimal.sqrt = sqrt;\r\n  Decimal.sub = sub;\r\n  Decimal.sum = sum;\r\n  Decimal.tan = tan;\r\n  Decimal.tanh = tanh;          // ES6\r\n  Decimal.trunc = trunc;        // ES6\r\n\r\n  if (obj === void 0) obj = {};\r\n  if (obj) {\r\n    if (obj.defaults !== true) {\r\n      ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];\r\n      for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];\r\n    }\r\n  }\r\n\r\n  Decimal.config(obj);\r\n\r\n  return Decimal;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction div(x, y) {\r\n  return new this(x).div(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The power to which to raise the base of the natural log.\r\n *\r\n */\r\nfunction exp(x) {\r\n  return new this(x).exp();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction floor(x) {\r\n  return finalise(x = new this(x), x.e + 1, 3);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of the sum of the squares of the arguments,\r\n * rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction hypot() {\r\n  var i, n,\r\n    t = new this(0);\r\n\r\n  external = false;\r\n\r\n  for (i = 0; i < arguments.length;) {\r\n    n = new this(arguments[i++]);\r\n    if (!n.d) {\r\n      if (n.s) {\r\n        external = true;\r\n        return new this(1 / 0);\r\n      }\r\n      t = n;\r\n    } else if (t.d) {\r\n      t = t.plus(n.times(n));\r\n    }\r\n  }\r\n\r\n  external = true;\r\n\r\n  return t.sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return true if object is a Decimal instance (where Decimal is any Decimal constructor),\r\n * otherwise return false.\r\n *\r\n */\r\nfunction isDecimalInstance(obj) {\r\n  return obj instanceof Decimal || obj && obj.toStringTag === tag || false;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction ln(x) {\r\n  return new this(x).ln();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base\r\n * is specified, rounded to `precision` significant digits using rounding mode `rounding`.\r\n *\r\n * log[y](x)\r\n *\r\n * x {number|string|Decimal} The argument of the logarithm.\r\n * y {number|string|Decimal} The base of the logarithm.\r\n *\r\n */\r\nfunction log(x, y) {\r\n  return new this(x).log(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log2(x) {\r\n  return new this(x).log(2);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction log10(x) {\r\n  return new this(x).log(10);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction max() {\r\n  return maxOrMin(this, arguments, 'lt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction min() {\r\n  return maxOrMin(this, arguments, 'gt');\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mod(x, y) {\r\n  return new this(x).mod(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction mul(x, y) {\r\n  return new this(x).mul(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} The base.\r\n * y {number|string|Decimal} The exponent.\r\n *\r\n */\r\nfunction pow(x, y) {\r\n  return new this(x).pow(y);\r\n}\r\n\r\n\r\n/*\r\n * Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with\r\n * `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros\r\n * are produced).\r\n *\r\n * [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.\r\n *\r\n */\r\nfunction random(sd) {\r\n  var d, e, k, n,\r\n    i = 0,\r\n    r = new this(1),\r\n    rd = [];\r\n\r\n  if (sd === void 0) sd = this.precision;\r\n  else checkInt32(sd, 1, MAX_DIGITS);\r\n\r\n  k = Math.ceil(sd / LOG_BASE);\r\n\r\n  if (!this.crypto) {\r\n    for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;\r\n\r\n  // Browsers supporting crypto.getRandomValues.\r\n  } else if (crypto.getRandomValues) {\r\n    d = crypto.getRandomValues(new Uint32Array(k));\r\n\r\n    for (; i < k;) {\r\n      n = d[i];\r\n\r\n      // 0 <= n < 4294967296\r\n      // Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).\r\n      if (n >= 4.29e9) {\r\n        d[i] = crypto.getRandomValues(new Uint32Array(1))[0];\r\n      } else {\r\n\r\n        // 0 <= n <= 4289999999\r\n        // 0 <= (n % 1e7) <= 9999999\r\n        rd[i++] = n % 1e7;\r\n      }\r\n    }\r\n\r\n  // Node.js supporting crypto.randomBytes.\r\n  } else if (crypto.randomBytes) {\r\n\r\n    // buffer\r\n    d = crypto.randomBytes(k *= 4);\r\n\r\n    for (; i < k;) {\r\n\r\n      // 0 <= n < 2147483648\r\n      n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);\r\n\r\n      // Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).\r\n      if (n >= 2.14e9) {\r\n        crypto.randomBytes(4).copy(d, i);\r\n      } else {\r\n\r\n        // 0 <= n <= 2139999999\r\n        // 0 <= (n % 1e7) <= 9999999\r\n        rd.push(n % 1e7);\r\n        i += 4;\r\n      }\r\n    }\r\n\r\n    i = k / 4;\r\n  } else {\r\n    throw Error(cryptoUnavailable);\r\n  }\r\n\r\n  k = rd[--i];\r\n  sd %= LOG_BASE;\r\n\r\n  // Convert trailing digits to zeros according to sd.\r\n  if (k && sd) {\r\n    n = mathpow(10, LOG_BASE - sd);\r\n    rd[i] = (k / n | 0) * n;\r\n  }\r\n\r\n  // Remove trailing words which are zero.\r\n  for (; rd[i] === 0; i--) rd.pop();\r\n\r\n  // Zero?\r\n  if (i < 0) {\r\n    e = 0;\r\n    rd = [0];\r\n  } else {\r\n    e = -1;\r\n\r\n    // Remove leading words which are zero and adjust exponent accordingly.\r\n    for (; rd[0] === 0; e -= LOG_BASE) rd.shift();\r\n\r\n    // Count the digits of the first word of rd to determine leading zeros.\r\n    for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;\r\n\r\n    // Adjust the exponent for leading zeros of the first word of rd.\r\n    if (k < LOG_BASE) e -= LOG_BASE - k;\r\n  }\r\n\r\n  r.e = e;\r\n  r.d = rd;\r\n\r\n  return r;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.\r\n *\r\n * To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction round(x) {\r\n  return finalise(x = new this(x), x.e + 1, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return\r\n *   1    if x > 0,\r\n *  -1    if x < 0,\r\n *   0    if x is 0,\r\n *  -0    if x is -0,\r\n *   NaN  otherwise\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sign(x) {\r\n  x = new this(x);\r\n  return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sin(x) {\r\n  return new this(x).sin();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction sinh(x) {\r\n  return new this(x).sinh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction sqrt(x) {\r\n  return new this(x).sqrt();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits\r\n * using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal}\r\n * y {number|string|Decimal}\r\n *\r\n */\r\nfunction sub(x, y) {\r\n  return new this(x).sub(y);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the sum of the arguments, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * Only the result is rounded, not the intermediate calculations.\r\n *\r\n * arguments {number|string|Decimal}\r\n *\r\n */\r\nfunction sum() {\r\n  var i = 0,\r\n    args = arguments,\r\n    x = new this(args[i]);\r\n\r\n  external = false;\r\n  for (; x.s && ++i < args.length;) x = x.plus(args[i]);\r\n  external = true;\r\n\r\n  return finalise(x, this.precision, this.rounding);\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant\r\n * digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tan(x) {\r\n  return new this(x).tan();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`\r\n * significant digits using rounding mode `rounding`.\r\n *\r\n * x {number|string|Decimal} A value in radians.\r\n *\r\n */\r\nfunction tanh(x) {\r\n  return new this(x).tanh();\r\n}\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is `x` truncated to an integer.\r\n *\r\n * x {number|string|Decimal}\r\n *\r\n */\r\nfunction trunc(x) {\r\n  return finalise(x = new this(x), x.e + 1, 1);\r\n}\r\n\r\n\r\nP[Symbol.for('nodejs.util.inspect.custom')] = P.toString;\r\nP[Symbol.toStringTag] = 'Decimal';\r\n\r\n// Create and configure initial Decimal constructor.\r\nexport var Decimal = P.constructor = clone(DEFAULTS);\r\n\r\n// Create the internal constants from their string values.\r\nLN10 = new Decimal(LN10);\r\nPI = new Decimal(PI);\r\n\r\nexport default Decimal;\r\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 { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { AccountMeta, PublicKey, SystemProgram, SYSVAR_RENT_PUBKEY } from \"@solana/web3.js\";\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 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\");\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 { 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.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.raydium.io/icon/So11111111111111111111111111111111111111112.png`,\n  tags: [],\n  priority: 2,\n  type: \"raydium\",\n  extensions: {\n    coingeckoId: \"solana\",\n  },\n};\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish, parseBigNumberish, Rounding } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\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 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 { BigNumberish, Rounding, 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","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 { Rounding } from \"../common/bignumber\";\nimport BN from \"bn.js\";\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 {\n  Connection,\n  PublicKey,\n  sendAndConfirmTransaction,\n  Signer,\n  Transaction,\n  TransactionInstruction,\n  TransactionMessage,\n  VersionedTransaction,\n} from \"@solana/web3.js\";\nimport axios from \"axios\";\n\nimport { SignAllTransactions, ComputeBudgetConfig } from \"@/raydium/type\";\nimport { TxVersion } from \"./txType\";\nimport { Owner } from \"../owner\";\nimport { getRecentBlockHash, addComputeBudget, checkLegacyTxSize, checkV0TxSize, printSimulate } from \"./txUtils\";\nimport { CacheLTA, getMultipleLookupTableInfo, LOOKUP_TABLE_CACHE } from \"./lookupTable\";\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 TxBuilderInit {\n  connection: Connection;\n  feePayer: PublicKey;\n  owner?: Owner;\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: () => 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: () => Promise<{ txId: string; signedTx: VersionedTransaction }>;\n}\n\nexport interface ExecuteParam {\n  sequentially: boolean;\n  onTxUpdate?: (completeTxs: { txId: string; status: \"success\" | \"error\" | \"sent\" }[]) => void;\n}\nexport interface MultiTxBuildData<T = Record<string, any>> {\n  builder: TxBuilder;\n  transactions: Transaction[];\n  instructionTypes: string[];\n  signers: Signer[][];\n  execute: (executeParams?: ExecuteParam) => 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?: ExecuteParam) => 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\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 signAllTransactions?: SignAllTransactions;\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  }\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) {\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 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\n    return {\n      builder: this,\n      transaction,\n      signers: this.signers,\n      instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n      execute: async () => {\n        const recentBlockHash = await getRecentBlockHash(this.connection);\n        transaction.recentBlockhash = recentBlockHash;\n        if (this.signers.length) transaction.sign(...this.signers);\n        printSimulate([transaction]);\n        if (this.owner?.isKeyPair) {\n          return {\n            txId: await sendAndConfirmTransaction(this.connection, transaction, this.signers),\n            signedTx: transaction,\n          };\n        }\n        if (this.signAllTransactions) {\n          const txs = await this.signAllTransactions([transaction]);\n          return {\n            txId: await this.connection.sendRawTransaction(txs[0].serialize(), { skipPreflight: true }),\n            signedTx: txs[0],\n          };\n        }\n        throw new Error(\"please connect wallet first\");\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    return {\n      builder: this,\n      transactions: allTransactions,\n      signers: allSigners,\n      instructionTypes: allInstructionTypes,\n      execute: async (executeParams?: ExecuteParam) => {\n        const { sequentially, onTxUpdate } = executeParams || {};\n        const recentBlockHash = await getRecentBlockHash(this.connection);\n        if (this.owner?.isKeyPair) {\n          return {\n            txIds: await await Promise.all(\n              allTransactions.map(async (tx, idx) => {\n                tx.recentBlockhash = recentBlockHash;\n                return await sendAndConfirmTransaction(this.connection, tx, allSigners[idx]);\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: { txId: string; status: \"success\" | \"error\" | \"sent\" }[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight: true });\n              processedTxs.push({ txId, status: \"sent\" });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n              this.connection.onSignature(\n                txId,\n                (signatureResult) => {\n                  const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                  if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                  onTxUpdate?.([...processedTxs]);\n                  checkSendTx();\n                },\n                \"processed\",\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: true });\n              txIds.push(txId);\n            }\n            return {\n              txIds,\n              signedTxs,\n            };\n          }\n        }\n        throw new Error(\"please connect wallet first\");\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    },\n  ): Promise<MakeTxData<TxVersion.V0, O>> {\n    const { lookupTableCache = {}, lookupTableAddress = [], forerunCreate, ...extInfo } = props || {};\n    const lookupTableAddressAccount = {\n      ...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 messageV0 = new TransactionMessage({\n      payerKey: this.feePayer,\n      recentBlockhash: forerunCreate ? PublicKey.default.toBase58() : await getRecentBlockHash(this.connection),\n      instructions: [...this.allInstructions],\n    }).compileToV0Message(Object.values(lookupTableAddressAccount));\n    const transaction = new VersionedTransaction(messageV0);\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 () => {\n        printSimulate([transaction]);\n        if (this.owner?.isKeyPair) {\n          transaction.sign([this.owner.signer as Signer]);\n          return {\n            txId: await this.connection.sendTransaction(transaction, { skipPreflight: true }),\n            signedTx: transaction,\n          };\n        }\n        if (this.signAllTransactions) {\n          const txs = await this.signAllTransactions<VersionedTransaction>([transaction]);\n          return {\n            txId: await this.connection.sendTransaction(txs[0], { skipPreflight: true }),\n            signedTx: txs[0],\n          };\n        }\n        throw new Error(\"please connect wallet first\");\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    };\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    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?: ExecuteParam) => {\n        printSimulate(allTransactions);\n        const { sequentially, onTxUpdate } = executeParams || {};\n        if (this.owner?.isKeyPair) {\n          allTransactions.forEach((tx) => tx.sign([this.owner!.signer as Signer]));\n          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx) => {\n                return await this.connection.sendTransaction(tx);\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: { txId: string; status: \"success\" | \"error\" | \"sent\" }[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight: true });\n              processedTxs.push({ txId, status: \"sent\" });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n              this.connection.onSignature(\n                txId,\n                (signatureResult) => {\n                  const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                  if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                  onTxUpdate?.([...processedTxs]);\n                  checkSendTx();\n                },\n                \"processed\",\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: true });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please connect wallet first\");\n      },\n      extInfo: buildProps || {},\n    };\n  }\n\n  public async sizeCheckBuild(\n    props?: Record<string, any> & { autoComputeBudget?: boolean },\n  ): Promise<MultiTxBuildData> {\n    const { autoComputeBudget = false, ...extInfo } = props || {};\n\n    let computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } = {\n      instructions: [],\n      instructionTypes: [],\n    };\n\n    if (autoComputeBudget) {\n      const computeConfig = autoComputeBudget ? await this.getComputeBudgetConfig() : undefined;\n      computeBudgetData =\n        autoComputeBudget && computeConfig\n          ? addComputeBudget(computeConfig)\n          : { instructions: [], 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    this.allInstructions.forEach((item) => {\n      const _itemIns = [...instructionQueue, item];\n      const _itemInsWithCompute = autoComputeBudget ? [...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        (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\n        // if add computeBudget still not exceed tx size limit\n        if (\n          checkLegacyTxSize({\n            instructions: autoComputeBudget\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: autoComputeBudget\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    return {\n      builder: this,\n      transactions: allTransactions,\n      signers: allSigners,\n      instructionTypes: this.instructionTypes,\n      execute: async (executeParams?: ExecuteParam) => {\n        const { sequentially, onTxUpdate } = executeParams || {};\n        const recentBlockHash = await getRecentBlockHash(this.connection);\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          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx, idx) => {\n                return await sendAndConfirmTransaction(this.connection, tx, allSigners[idx]);\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n        if (this.signAllTransactions) {\n          const signedTxs = await this.signAllTransactions(allTransactions);\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: { txId: string; status: \"success\" | \"error\" | \"sent\" }[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight: true });\n              processedTxs.push({ txId, status: \"sent\" });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n              this.connection.onSignature(\n                txId,\n                (signatureResult) => {\n                  const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                  if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                  onTxUpdate?.([...processedTxs]);\n                  checkSendTx();\n                },\n                \"processed\",\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: true });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please connect wallet first\");\n      },\n      extInfo: extInfo || {},\n    };\n  }\n\n  public async sizeCheckBuildV0(\n    props?: Record<string, any> & {\n      autoComputeBudget?: boolean;\n      lookupTableCache?: CacheLTA;\n      lookupTableAddress?: string[];\n    },\n  ): Promise<MultiTxV0BuildData> {\n    const { autoComputeBudget = false, lookupTableCache = {}, lookupTableAddress = [], ...extInfo } = props || {};\n    const lookupTableAddressAccount = {\n      ...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    let computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } = {\n      instructions: [],\n      instructionTypes: [],\n    };\n\n    if (autoComputeBudget) {\n      const computeConfig = autoComputeBudget ? await this.getComputeBudgetConfig() : undefined;\n      computeBudgetData =\n        autoComputeBudget && computeConfig\n          ? addComputeBudget(computeConfig)\n          : { instructions: [], instructionTypes: [] };\n    }\n\n    const blockHash = await getRecentBlockHash(this.connection);\n\n    const signerKey: { [key: string]: Signer } = this.signers.reduce(\n      (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n      {},\n    );\n\n    const allTransactions: VersionedTransaction[] = [];\n    const allSigners: Signer[][] = [];\n\n    let instructionQueue: TransactionInstruction[] = [];\n    this.allInstructions.forEach((item) => {\n      const _itemIns = [...instructionQueue, item];\n      const _itemInsWithCompute = autoComputeBudget ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n      if (\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\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          autoComputeBudget &&\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        autoComputeBudget &&\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      allSigners.push(_signers);\n    }\n\n    return {\n      builder: this,\n      transactions: allTransactions,\n      buildProps: props,\n      signers: allSigners,\n      instructionTypes: this.instructionTypes,\n      execute: async (executeParams?: ExecuteParam) => {\n        const { sequentially, onTxUpdate } = executeParams || {};\n        allTransactions.map(async (tx, idx) => {\n          if (allSigners[idx].length) tx.sign(allSigners[idx]);\n        });\n        printSimulate(allTransactions);\n        if (this.owner?.isKeyPair) {\n          return {\n            txIds: await Promise.all(\n              allTransactions.map(async (tx) => {\n                return await this.connection.sendTransaction(tx, { skipPreflight: true });\n              }),\n            ),\n            signedTxs: allTransactions,\n          };\n        }\n        if (this.signAllTransactions) {\n          const signedTxs = await this.signAllTransactions(allTransactions);\n          if (sequentially) {\n            let i = 0;\n            const processedTxs: { txId: string; status: \"success\" | \"error\" | \"sent\" }[] = [];\n            const checkSendTx = async (): Promise<void> => {\n              if (!signedTxs[i]) return;\n              const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight: true });\n              processedTxs.push({ txId, status: \"sent\" });\n              onTxUpdate?.([...processedTxs]);\n              i++;\n              this.connection.onSignature(\n                txId,\n                (signatureResult) => {\n                  const targetTxIdx = processedTxs.findIndex((tx) => tx.txId === txId);\n                  if (targetTxIdx > -1) processedTxs[targetTxIdx].status = signatureResult.err ? \"error\" : \"success\";\n                  onTxUpdate?.([...processedTxs]);\n                  checkSendTx();\n                },\n                \"processed\",\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: true });\n              txIds.push(txId);\n            }\n            return { txIds, signedTxs };\n          }\n        }\n        throw new Error(\"please connect wallet first\");\n      },\n      extInfo: extInfo || {},\n    };\n  }\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\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  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","import {\n  Connection,\n  PublicKey,\n  ComputeBudgetProgram,\n  SimulatedTransactionResponse,\n  Transaction,\n  TransactionInstruction,\n  TransactionMessage,\n  Keypair,\n  EpochInfo,\n  VersionedTransaction,\n} from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nimport { createLogger } from \"../logger\";\nimport { InstructionType } from \"./txType\";\nimport { CacheLTA } from \"./lookupTable\";\n\nimport { ComputeBudgetConfig } from \"@/raydium/type\";\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): Promise<string> {\n  try {\n    return (await connection.getLatestBlockhash?.())?.blockhash || (await connection.getRecentBlockhash()).blockhash;\n  } catch {\n    return (await connection.getRecentBlockhash()).blockhash;\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 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    let serialized = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });\n    if (transaction instanceof VersionedTransaction) serialized = toBuffer(serialized);\n    const base64 = serialized.toString(\"base64\");\n    allBase64.push(base64);\n  });\n  console.log(\"simulate tx string:\", allBase64);\n\n  return allBase64;\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  \"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\": new AddressLookupTableAccount({\n    key: new PublicKey(\"2immgwYNHBbyVQKVGCEkgWpi53bLwWNRMB5G2nbgYV17\"),\n    state: AddressLookupTableAccount.deserialize(\n      Buffer.from(\n        \"AQAAAP//////////d49+DAAAAAAAAQZMWvw7GUNJdaccNBVnb57OKakxL2BHLYvhRwVILRsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMGRm/lIRcy/+ytunLDm+e8jOW7xfcSayxDmzpAAAAABt324ddloZPZy+FGzut5rBy0he1fWzeROoz1hX7/AKkG3fbh7nWP3hhCXbzkbM3athr8TYO5DSf+vfko2KGL/AVKU1D4XciC1hSlVnJ4iilt3x6rq9CmBniISTL07vagBqfVFxksXFEhjMlMPUrxf1ja7gibof1E49vZigAAAAAGp9UXGMd0yShWY5hpHV62i164o5tLbVxzVVshAAAAAIyXJY9OJInxuz0QKRSODYMLWhOZ2v8QhASOe9jb6fhZC3BlsePRfEU4nVJ/awTDzVi4bHMaoP21SbbRvAP4KUbIScv+6Yw2LHF/6K0ZjUPibbSWXCirYPGuuVl7zT789IUPLW4CpHr4JNCatp3ELXDLKMv6JJ+37le50lbBJ2LvDQdRqCgtphMF/imcN7mY5YRx2xE1A3MQ+L4QRaYK9u4GRfZP3LsAd00a+IkCpA22UNQMKdq5BFbJuwuOLqc8zxCTDlqxBG8J0HcxtfogQHDK06ukzfaXiNDKAob1MqBHS9lJxDYCwz8gd5DtFqNSTKG5l1zxIaKpDP/sffi2is1H9aKveyXSu5StXElYRl9SD5As0DHE4N0GLnf84/siiKXVyp4Ez121kLcUui/jLLFZEz/BwZK3Ilf9B9OcsEAeDMKAy2vjGSxQODgBz0QwGA+eP4ZjIjrIAQaXENv31QfLlOdXSRCkaybRniDHF4C8YcwhcvsqrOVuTP4B2Na+9wLdtrB31uz2rtlFI5kahdsnp/d1SrASDInYCtTYtdoke4kX+hoKWcEWM4Tle8pTUkUVv4BxS6fje/EzKBE4Qu9N9LMnrw/JNO0hqMVB4rk/2ou4AB1loQ7FZoPwut2o4KZB+0p9xnbrQKw038qjpHar+PyDwvxBRcu5hpHw3dguezeWv+IwvgW5icu8EGkhGa9AkFPPJT7VMSFb8xowveU=\",\n        \"base64\",\n      ),\n    ),\n  }),\n};\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\nimport { chunkArray } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../raydium/type\";\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}\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 { batchRequest, commitment = \"confirmed\" } = {\n    batchRequest: false,\n    ...config,\n  };\n\n  const chunkedKeys = chunkArray(publicKeys, 100);\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}: {\n  connection: Connection;\n  mints: PublicKey[];\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n  if (mints.length === 0) return {};\n  const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n    connection,\n    mints.map((i) => ({ pubkey: i })),\n  );\n\n  const mintK: ReturnTypeFetchMultipleMintInfos = {};\n  for (const i of mintInfos) {\n    const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n    mintK[i.pubkey.toString()] = {\n      ...t,\n      feeConfig: getTransferFeeConfig(t) ?? undefined,\n    };\n  }\n\n  return mintK;\n}\n","import { Keypair, PublicKey, Signer } from \"@solana/web3.js\";\n\ntype _Owner = Keypair | PublicKey;\n\nexport class Owner {\n  private readonly _owner: _Owner;\n\n  constructor(owner: _Owner) {\n    this._owner = owner;\n  }\n\n  get publicKey(): PublicKey {\n    if (Owner.isKeyPair(this._owner)) {\n      return this._owner.publicKey;\n    }\n\n    return this._owner;\n  }\n\n  get signer(): Signer | undefined {\n    return Owner.isKeyPair(this._owner) ? this._owner : undefined;\n  }\n\n  get isKeyPair(): boolean {\n    return Owner.isKeyPair(this._owner);\n  }\n\n  get isPublicKey(): boolean {\n    return Owner.isPublicKey(this._owner);\n  }\n\n  static isKeyPair(owner: _Owner): owner is Keypair {\n    return (owner as Keypair).secretKey !== undefined;\n  }\n\n  static isPublicKey(owner: _Owner): owner is PublicKey {\n    return !Owner.isKeyPair(owner);\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\n// raydium\nexport const FARM_PROGRAM_ID_V3 = new PublicKey(\"EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q\");\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 CLMM_PROGRAM_ID = new PublicKey(\"CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK\");\nexport const Router = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\");\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 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\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\nexport type ProgramIdConfig = Partial<typeof ALL_PROGRAM_ID>;\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { findProgramAddress } from \"./txTool/txUtils\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\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 { EpochInfo } from \"@solana/web3.js\";\nimport { TransferFeeConfig, TransferFee } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport { GetTransferAmountFee } from \"../raydium/type\";\nimport { TransferFeeDataBaseType } from \"../api/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","export const API_URLS = {\n  BASE_HOST: \"https://uapi.raydium.io\",\n\n  COINGECKO: \"https://api.coingecko.com/api/v3/simple/price\",\n\n  FARM_ARP: \"/main/farm/info\",\n  FARM_ARP_LINE: \"/main/farm-apr-tv\",\n\n  AMM_V3_CONFIG: \"/v3/pools/clmm-config\",\n\n  VERSION: \"/v3/main/version\",\n\n  PRICE: \"/v2/main/price\",\n\n  // api v3\n  CHECK_AVAILABILITY: \"/v3/main/AvailabilityCheckAPI\",\n  RPCS: \"/v3/main/rpcs\",\n  INFO: \"/v3/main/info\",\n  STAKE_POOLS: \"/v3/main/stake-pools\",\n  CHAIN_TIME: \"/v3/main/chain-time\",\n  TOKEN_LIST: \"/v3/mint/list\",\n  TOKEN_INFO: \"/v3/mint/item/{mint}\",\n  JUP_TOKEN_LIST: \"https://token.jup.ag/{type}\",\n  /**\n   * type: {all | concentrated | standard}\n   * sort: {liquidity | volume_24h / 7d / 30d | fee_24h / 7d / 30d | apr_24h / 7d / 30d}\n   * order: {desc/asc}\n   * page: number\n   */\n  POOL_LIST: \"/v3/pools/info/{type}/{sort}/{order}/{page_size}/{page}\",\n  POOL_SEARCH_BY_ID: \"/v3/pools/info/ids/{ids}\",\n  /**\n   * search_text: search text\n   * type: {all | concentrated | standard}\n   * sort: {liquidity | volume_24h / 7d / 30d | fee_24h / 7d / 30d | apr_24h / 7d / 30d}\n   * order: {desc/asc}\n   * page: number\n   */\n  POOL_SEARCH: \"/v3/pools/info/search/{search_text}/{type}/{sort}/{order}/{page_size}/{page}\",\n  /**\n   * mint1/mint2: search pool by mint\n   * sort: {liquidity | volume_24h / 7d / 30d | fee_24h / 7d / 30d | apr_24h / 7d / 30d}\n   * type: {all | concentrated | standard}\n   * order: {desc/asc}\n   * page: number\n   */\n  POOL_SEARCH_MINT: \"/v3/pools/info/mint/{mint1}/{type}/{sort}/{order}/{page_size}/{page}\",\n  POOL_SEARCH_MINT_2: \"/v3/pools/info/mint/{mint1}/{mint2}/{type}/{sort}/{order}/{page_size}/{page}\",\n  POOL_SEARCH_LP: \"/v3/pools/info/lps/{lp_mints}\",\n  POOL_KEY_BY_ID: \"/v3/pools/key/id/{id}\",\n  POOLS_KEY: \"/v3/pools/key/{type}/{page_size}/{page}\",\n  POOLS_KEY_BY_MINT: \"/v3/pools/key/mint/{mint1}/{type}/{page_size}/{page}\",\n  POOLS_KEY_BY_MINT_2: \"/v3/pools/key/mint/{mint1}/{mint2}/{type}/{page_size}/{page}\",\n  POOL_LIQUIDITY_LINE: \"/v3/pools/line/liquidity/{id}\",\n  POOL_POSITION_LINE: \"/v3/pools/line/position/{id}\",\n  FARM_INFO: \"/v3/farms/info/ids/{ids}\",\n  FARM_LP_INFO: \"/v3/farms/info/lp/{pool_lp}/{page_size}/{page}\",\n  FARM_LIST: \"/v3/farms/info/list/all/{page_size}/{page}\",\n  FARM_KEYS: \"/v3/farms/key/ids/{ids}\",\n  OWNER_CREATED_FARM: \"/v3/owner/create-pool/{owner}\",\n  OWNER_IDO: \"/v3/owner/main/ido/{owner}\",\n  OWNER_STAKE_FARMS: \"/v3/owner/position/stake/{owner}\",\n  IDO_KEYS: \"/v3/ido/key/ids/{ids}\",\n  SWAP_HOST: \"https://transaction.raydium.io\",\n  SWAP_COMPUTE: \"/v1/compute/\",\n  SWAP_TX: \"/v1/transaction/\",\n  MINT_PRICE: \"/v3/mint/price\",\n  MIGRATE_CONFIG: \"/v3/main/migrate-lp\",\n};\n\nexport const DEV_API_URLS = {\n  ...API_URLS,\n};\n\nexport type API_URL_CONFIG = Partial<typeof API_URLS>;\n","export const SESSION_KEY = \"ray_tab_hash\";\nexport const STORAGE_KEY = \"ray_req_hash\";\n\nexport const getSessionKey = (): string => {\n  if (typeof window === undefined) return \"\";\n  let key = sessionStorage.getItem(SESSION_KEY);\n\n  // new a session key\n  if (!key) {\n    key = `ray-${Date.now()}`;\n    sessionStorage.setItem(SESSION_KEY, key);\n  }\n  return key;\n};\n\nexport interface ResHistory {\n  status: number;\n  url: string;\n  params?: any;\n  data: any;\n  logCount?: number;\n  time: number;\n  session: string;\n  removeLastLog?: boolean;\n}\n\nexport const updateReqHistory = async ({\n  logCount = 1000,\n  removeLastLog,\n  ...resData\n}: Omit<ResHistory, \"time\" | \"session\">): Promise<void> => {\n  if (typeof window === undefined) return new Promise((resolve) => resolve());\n  const data: ResHistory[] = JSON.parse(localStorage.getItem(STORAGE_KEY) || \"[]\").slice(0, logCount - 1);\n\n  // means retry last save error\n  if (removeLastLog) data.pop();\n\n  // if data > 1kb\n  if (new Blob([JSON.stringify(resData.data)]).size > 1024)\n    resData.data = JSON.stringify(resData.data).substring(0, 200) + \"...\";\n  data.unshift({ ...resData, time: Date.now(), session: getSessionKey() });\n\n  try {\n    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n  } catch {\n    // if retry failed, empty request data\n    if (removeLastLog) {\n      let success = false;\n      const resStr = JSON.stringify(resData.data).substring(0, 100);\n      data[0].data = resStr + (resStr.length > 100 ? \"...\" : \"\");\n      while (!success) {\n        data.pop();\n        const resStr = JSON.stringify(resData.data).substring(0, 100);\n        data[0].data = resStr + (resStr.length > 100 ? \"...\" : \"\");\n        try {\n          localStorage.setItem(STORAGE_KEY, JSON.stringify(data));\n          success = true;\n        } catch {\n          success = false;\n        }\n      }\n      return new Promise((resolve) => resolve());\n    }\n    return updateReqHistory({\n      ...resData,\n      logCount,\n      removeLastLog: true,\n    });\n  }\n};\n","export const EMPTY_OWNER =\n  \"please provide owner in load() initialization or you can set by calling raydium.setOwner(owner)\";\n\nexport const EMPTY_CONNECTION =\n  \"please provide connection in load() initialization or set it by raydium.setConnection(connection)\";\n","import { createAssociatedTokenAccountInstruction, TOKEN_PROGRAM_ID, AccountLayout } from \"@solana/spl-token\";\nimport { Commitment, PublicKey, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport { getATAAddress, BigNumberish, InstructionType, WSOLMint } from \"@/common\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\n\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport {\n  closeAccountInstruction,\n  createWSolAccountInstructions,\n  makeTransferInstruction,\n  initTokenAccountInstruction,\n} from \"./instruction\";\nimport { HandleTokenAccountParams, TokenAccount, TokenAccountRaw, GetOrCreateTokenAccountParams } from \"./types\";\nimport { parseTokenAccountResp, generatePubKey } from \"./util\";\n\nexport interface TokenAccountDataProp {\n  tokenAccounts?: TokenAccount[];\n  tokenAccountRawInfos?: TokenAccountRaw[];\n}\nexport default class Account extends ModuleBase {\n  private _tokenAccounts: TokenAccount[] = [];\n  private _tokenAccountRawInfos: TokenAccountRaw[] = [];\n  private _accountChangeListenerId?: number;\n  private _accountListener: ((data: TokenAccountDataProp) => void)[] = [];\n  private _clientOwnedToken = false;\n\n  constructor(params: TokenAccountDataProp & ModuleBaseProps) {\n    super(params);\n    const { tokenAccounts, tokenAccountRawInfos } = params;\n    this._tokenAccounts = tokenAccounts || [];\n    this._tokenAccountRawInfos = tokenAccountRawInfos || [];\n    this._clientOwnedToken = !!(tokenAccounts || tokenAccountRawInfos);\n  }\n\n  get tokenAccounts(): TokenAccount[] {\n    return this._tokenAccounts;\n  }\n  get tokenAccountRawInfos(): TokenAccountRaw[] {\n    return this._tokenAccountRawInfos;\n  }\n\n  public updateTokenAccount({ tokenAccounts, tokenAccountRawInfos }: TokenAccountDataProp): Account {\n    if (tokenAccounts) this._tokenAccounts = tokenAccounts;\n    if (tokenAccountRawInfos) this._tokenAccountRawInfos = tokenAccountRawInfos;\n    this._accountChangeListenerId && this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n    this._accountChangeListenerId = undefined;\n    this._clientOwnedToken = true;\n    return this;\n  }\n\n  public addAccountChangeListener(cbk: (data: TokenAccountDataProp) => void): Account {\n    this._accountListener.push(cbk);\n    return this;\n  }\n\n  public removeAccountChangeListener(cbk: (data: TokenAccountDataProp) => void): Account {\n    this._accountListener = this._accountListener.filter((listener) => listener !== cbk);\n    return this;\n  }\n\n  public getAssociatedTokenAccount(mint: PublicKey, programId?: PublicKey): PublicKey {\n    return getATAAddress(this.scope.ownerPubKey, mint, programId).publicKey;\n  }\n\n  public async fetchWalletTokenAccounts(config?: { forceUpdate?: boolean; commitment?: Commitment }): Promise<{\n    tokenAccounts: TokenAccount[];\n    tokenAccountRawInfos: TokenAccountRaw[];\n  }> {\n    if (this._clientOwnedToken || (!config?.forceUpdate && this._tokenAccounts.length)) {\n      return {\n        tokenAccounts: this._tokenAccounts,\n        tokenAccountRawInfos: this._tokenAccountRawInfos,\n      };\n    }\n    this.scope.checkOwner();\n\n    const defaultConfig = {};\n    const customConfig = { ...defaultConfig, ...config };\n\n    const [solAccountResp, ownerTokenAccountResp] = await Promise.all([\n      this.scope.connection.getAccountInfo(this.scope.ownerPubKey, customConfig.commitment),\n      this.scope.connection.getTokenAccountsByOwner(\n        this.scope.ownerPubKey,\n        { programId: TOKEN_PROGRAM_ID },\n        customConfig.commitment,\n      ),\n    ]);\n\n    const { tokenAccounts, tokenAccountRawInfos } = parseTokenAccountResp({\n      owner: this.scope.ownerPubKey,\n      solAccountResp,\n      tokenAccountResp: ownerTokenAccountResp,\n    });\n\n    this._tokenAccounts = tokenAccounts;\n    this._tokenAccountRawInfos = tokenAccountRawInfos;\n\n    this._accountChangeListenerId && this.scope.connection.removeAccountChangeListener(this._accountChangeListenerId);\n    this._accountChangeListenerId = this.scope.connection.onAccountChange(\n      this.scope.ownerPubKey,\n      () => this.fetchWalletTokenAccounts({ forceUpdate: true }),\n      \"confirmed\",\n    );\n\n    return { tokenAccounts, tokenAccountRawInfos };\n  }\n\n  // user token account needed, old _selectTokenAccount\n  public async getCreatedTokenAccount({\n    mint,\n    programId = TOKEN_PROGRAM_ID,\n    associatedOnly = true,\n  }: {\n    mint: PublicKey;\n    programId?: PublicKey;\n    associatedOnly?: boolean;\n  }): Promise<PublicKey | undefined> {\n    await this.fetchWalletTokenAccounts();\n    const tokenAccounts = this._tokenAccounts\n      .filter(({ mint: accountMint }) => accountMint?.equals(mint))\n      // sort by balance\n      .sort((a, b) => (a.amount.lt(b.amount) ? 1 : -1));\n\n    const ata = this.getAssociatedTokenAccount(mint, programId);\n    for (const tokenAccount of tokenAccounts) {\n      const { publicKey } = tokenAccount;\n      if (publicKey) {\n        if (associatedOnly && ata.equals(publicKey)) return publicKey;\n        return publicKey;\n      }\n    }\n  }\n\n  // old _selectOrCreateTokenAccount\n  public async getOrCreateTokenAccount(params: GetOrCreateTokenAccountParams): Promise<{\n    account?: PublicKey;\n    instructionParams?: AddInstructionParam;\n  }> {\n    await this.fetchWalletTokenAccounts();\n    const {\n      mint,\n      createInfo,\n      associatedOnly,\n      owner,\n      notUseTokenAccount = false,\n      skipCloseAccount = false,\n      checkCreateATAOwner = false,\n    } = params;\n    const tokenProgram = new PublicKey(params.tokenProgram || TOKEN_PROGRAM_ID);\n    const ata = this.getAssociatedTokenAccount(mint, new PublicKey(tokenProgram));\n    const accounts = (notUseTokenAccount ? [] : this.tokenAccountRawInfos)\n      .filter((i) => i.accountInfo.mint.equals(mint) && (!associatedOnly || i.pubkey.equals(ata)))\n      .sort((a, b) => (a.accountInfo.amount.lt(b.accountInfo.amount) ? 1 : -1));\n    // find token or don't need create\n    if (createInfo === undefined || accounts.length > 0) {\n      return accounts.length > 0 ? { account: accounts[0].pubkey } : {};\n    }\n\n    const newTxInstructions: AddInstructionParam = {\n      instructions: [],\n      endInstructions: [],\n      signers: [],\n      instructionTypes: [],\n      endInstructionTypes: [],\n    };\n\n    if (associatedOnly) {\n      const _createATAIns = createAssociatedTokenAccountInstruction(owner, ata, owner, mint, tokenProgram);\n      if (checkCreateATAOwner) {\n        const ataInfo = await this.scope.connection.getAccountInfo(ata);\n        if (ataInfo === null) {\n          newTxInstructions.instructions?.push(_createATAIns);\n          newTxInstructions.instructionTypes!.push(InstructionType.CreateATA);\n        } else if (\n          ataInfo.owner.equals(tokenProgram) &&\n          AccountLayout.decode(ataInfo.data).mint.equals(mint) &&\n          AccountLayout.decode(ataInfo.data).owner.equals(owner)\n        ) {\n          /* empty */\n        } else {\n          throw Error(`create ata check error -> mint: ${mint.toString()}, ata: ${ata.toString()}`);\n        }\n      } else {\n        newTxInstructions.instructions!.push(_createATAIns);\n        newTxInstructions.instructionTypes!.push(InstructionType.CreateATA);\n      }\n      if (mint.equals(WSOLMint) && createInfo.amount) {\n        const txInstruction = await createWSolAccountInstructions({\n          connection: this.scope.connection,\n          owner: this.scope.ownerPubKey,\n          payer: createInfo.payer || this.scope.ownerPubKey,\n          amount: createInfo.amount ?? 0,\n          skipCloseAccount,\n        });\n        newTxInstructions.instructions!.push(...(txInstruction.instructions || []));\n        newTxInstructions.endInstructions!.push(...(txInstruction.endInstructions || []));\n        newTxInstructions.instructionTypes!.push(...(txInstruction.instructionTypes || []));\n        newTxInstructions.endInstructionTypes!.push(...(txInstruction.endInstructionTypes || []));\n\n        if (createInfo.amount) {\n          newTxInstructions.instructions!.push(\n            makeTransferInstruction({\n              source: txInstruction.addresses.newAccount,\n              destination: ata,\n              owner: this.scope.ownerPubKey,\n              amount: createInfo.amount,\n              tokenProgram: TOKEN_PROGRAM_ID,\n            }),\n          );\n          newTxInstructions.instructionTypes!.push(InstructionType.TransferAmount);\n        }\n      }\n\n      if (!skipCloseAccount) {\n        newTxInstructions.endInstructions!.push(\n          closeAccountInstruction({\n            owner,\n            payer: createInfo.payer || owner,\n            tokenAccount: ata,\n            programId: tokenProgram,\n          }),\n        );\n        newTxInstructions.endInstructionTypes!.push(InstructionType.CloseAccount);\n      }\n\n      return { account: ata, instructionParams: newTxInstructions };\n    } else {\n      if (mint.equals(WSOLMint)) {\n        const txInstruction = await createWSolAccountInstructions({\n          connection: this.scope.connection,\n          owner: this.scope.ownerPubKey,\n          payer: createInfo.payer || this.scope.ownerPubKey,\n          amount: createInfo.amount ?? 0,\n          skipCloseAccount,\n        });\n        newTxInstructions.instructions!.push(...(txInstruction.instructions || []));\n        newTxInstructions.endInstructions!.push(...(txInstruction.endInstructions || []));\n        newTxInstructions.signers!.push(...(txInstruction.signers || []));\n        newTxInstructions.instructionTypes!.push(...(txInstruction.instructionTypes || []));\n        newTxInstructions.endInstructionTypes!.push(...(txInstruction.endInstructionTypes || []));\n\n        return { account: txInstruction.addresses.newAccount, instructionParams: newTxInstructions };\n      } else {\n        const newTokenAccount = generatePubKey({ fromPublicKey: owner, programId: tokenProgram });\n        const balanceNeeded = await this.scope.connection.getMinimumBalanceForRentExemption(AccountLayout.span);\n\n        const createAccountIns = SystemProgram.createAccountWithSeed({\n          fromPubkey: owner,\n          basePubkey: owner,\n          seed: newTokenAccount.seed,\n          newAccountPubkey: newTokenAccount.publicKey,\n          lamports: balanceNeeded,\n          space: AccountLayout.span,\n          programId: tokenProgram,\n        });\n\n        newTxInstructions.instructions!.push(\n          createAccountIns,\n          initTokenAccountInstruction({\n            mint,\n            tokenAccount: newTokenAccount.publicKey,\n            owner: this.scope.ownerPubKey,\n            programId: tokenProgram,\n          }),\n        );\n        newTxInstructions.instructionTypes!.push(InstructionType.CreateAccount);\n        newTxInstructions.instructionTypes!.push(InstructionType.InitAccount);\n        if (!skipCloseAccount) {\n          newTxInstructions.endInstructions!.push(\n            closeAccountInstruction({\n              owner,\n              payer: createInfo.payer || owner,\n              tokenAccount: newTokenAccount.publicKey,\n              programId: tokenProgram,\n            }),\n          );\n          newTxInstructions.endInstructionTypes!.push(InstructionType.CloseAccount);\n        }\n        return { account: newTokenAccount.publicKey, instructionParams: newTxInstructions };\n      }\n    }\n  }\n\n  public async checkOrCreateAta({\n    mint,\n    programId = TOKEN_PROGRAM_ID,\n    autoUnwrapWSOLToSOL,\n  }: {\n    mint: PublicKey;\n    programId?: PublicKey;\n    autoUnwrapWSOLToSOL?: boolean;\n  }): Promise<{ pubKey: PublicKey; newInstructions: AddInstructionParam }> {\n    await this.fetchWalletTokenAccounts();\n    let tokenAccountAddress = this.scope.account.tokenAccounts.find(\n      ({ mint: accountTokenMint }) => accountTokenMint?.toBase58() === mint.toBase58(),\n    )?.publicKey;\n\n    const owner = this.scope.ownerPubKey;\n    const newTxInstructions: AddInstructionParam = {};\n\n    if (!tokenAccountAddress) {\n      const ataAddress = this.getAssociatedTokenAccount(mint, programId);\n      const instruction = await createAssociatedTokenAccountInstruction(owner, ataAddress, owner, mint, programId);\n      newTxInstructions.instructions = [instruction];\n      newTxInstructions.instructionTypes = [InstructionType.CreateATA];\n      tokenAccountAddress = ataAddress;\n    }\n    if (autoUnwrapWSOLToSOL && WSOLMint.toBase58() === mint.toBase58()) {\n      newTxInstructions.endInstructions = [\n        closeAccountInstruction({ owner, payer: owner, tokenAccount: tokenAccountAddress, programId }),\n      ];\n      newTxInstructions.endInstructionTypes = [InstructionType.CloseAccount];\n    }\n\n    return {\n      pubKey: tokenAccountAddress,\n      newInstructions: newTxInstructions,\n    };\n  }\n\n  // old _handleTokenAccount\n  public async handleTokenAccount(\n    params: HandleTokenAccountParams,\n  ): Promise<AddInstructionParam & { tokenAccount?: PublicKey }> {\n    const {\n      side,\n      amount,\n      mint,\n      programId = TOKEN_PROGRAM_ID,\n      tokenAccount,\n      payer = this.scope.ownerPubKey,\n      bypassAssociatedCheck,\n      skipCloseAccount,\n      checkCreateATAOwner,\n    } = params;\n\n    const ata = this.getAssociatedTokenAccount(mint, programId);\n\n    if (new PublicKey(WSOLMint).equals(mint)) {\n      const txInstruction = await createWSolAccountInstructions({\n        connection: this.scope.connection,\n        owner: this.scope.ownerPubKey,\n        payer,\n        amount,\n        skipCloseAccount,\n      });\n      return { tokenAccount: txInstruction.addresses.newAccount, ...txInstruction };\n    } else if (!tokenAccount || (side === \"out\" && !ata.equals(tokenAccount) && !bypassAssociatedCheck)) {\n      const instructions: TransactionInstruction[] = [];\n      const _createATAIns = createAssociatedTokenAccountInstruction(\n        this.scope.ownerPubKey,\n        ata,\n        this.scope.ownerPubKey,\n        mint,\n        programId,\n      );\n\n      if (checkCreateATAOwner) {\n        const ataInfo = await this.scope.connection.getAccountInfo(ata);\n        if (ataInfo === null) {\n          instructions.push(_createATAIns);\n        } else if (\n          ataInfo.owner.equals(TOKEN_PROGRAM_ID) &&\n          AccountLayout.decode(ataInfo.data).mint.equals(mint) &&\n          AccountLayout.decode(ataInfo.data).owner.equals(this.scope.ownerPubKey)\n        ) {\n          /* empty */\n        } else {\n          throw Error(`create ata check error -> mint: ${mint.toString()}, ata: ${ata.toString()}`);\n        }\n      } else {\n        instructions.push(_createATAIns);\n      }\n\n      return {\n        tokenAccount: ata,\n        instructions,\n        instructionTypes: [InstructionType.CreateATA],\n      };\n    }\n\n    return { tokenAccount };\n  }\n\n  public async processTokenAccount(props: {\n    mint: PublicKey;\n    programId?: PublicKey;\n    amount?: BigNumberish;\n    useSOLBalance?: boolean;\n    handleTokenAccount?: boolean;\n  }): Promise<Promise<AddInstructionParam & { tokenAccount?: PublicKey }>> {\n    const { mint, programId = TOKEN_PROGRAM_ID, amount, useSOLBalance, handleTokenAccount } = props;\n    let tokenAccount: PublicKey | undefined;\n    const txBuilder = this.createTxBuilder();\n\n    if (mint.equals(new PublicKey(WSOLMint)) && useSOLBalance) {\n      // mintA\n      const { tokenAccount: _tokenAccount, ...instructions } = await this.handleTokenAccount({\n        side: \"in\",\n        amount: amount || 0,\n        mint,\n        bypassAssociatedCheck: true,\n        programId,\n      });\n      tokenAccount = _tokenAccount;\n      txBuilder.addInstruction(instructions);\n    } else {\n      tokenAccount = await this.getCreatedTokenAccount({\n        mint,\n        associatedOnly: false,\n        programId,\n      });\n      if (!tokenAccount && handleTokenAccount) {\n        const { tokenAccount: _tokenAccount, ...instructions } = await this.scope.account.handleTokenAccount({\n          side: \"in\",\n          amount: 0,\n          mint,\n          bypassAssociatedCheck: true,\n          programId,\n        });\n        tokenAccount = _tokenAccount;\n        txBuilder.addInstruction(instructions);\n      }\n    }\n\n    return { tokenAccount, ...txBuilder.AllTxData };\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      owner: this.scope.owner,\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    // this.logger.error(message);\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 {\n  createInitializeAccountInstruction,\n  createCloseAccountInstruction,\n  createTransferInstruction,\n  TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport { Commitment, Connection, PublicKey, Signer, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { generatePubKey } from \"./util\";\nimport { BigNumberish, parseBigNumberish } from \"@/common\";\nimport { AddInstructionParam } from \"@/common/txTool/txTool\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { TOKEN_WSOL } from \"../token/constant\";\n\nimport { splAccountLayout } from \"./layout\";\n\nexport function initTokenAccountInstruction(params: {\n  mint: PublicKey;\n  tokenAccount: PublicKey;\n  owner: PublicKey;\n  programId?: PublicKey;\n}): TransactionInstruction {\n  const { mint, tokenAccount, owner, programId = TOKEN_PROGRAM_ID } = params;\n  return createInitializeAccountInstruction(tokenAccount, mint, owner, programId);\n}\n\nexport function closeAccountInstruction(params: {\n  tokenAccount: PublicKey;\n  payer: PublicKey;\n  multiSigners?: Signer[];\n  owner: PublicKey;\n  programId?: PublicKey;\n}): TransactionInstruction {\n  const { tokenAccount, payer, multiSigners = [], owner, programId = TOKEN_PROGRAM_ID } = params;\n  return createCloseAccountInstruction(tokenAccount, payer, owner, multiSigners, programId);\n}\n\ninterface CreateWSolTokenAccount {\n  connection: Connection;\n  payer: PublicKey;\n  owner: PublicKey;\n  amount: BigNumberish;\n  commitment?: Commitment;\n  skipCloseAccount?: boolean;\n}\n/**\n * WrappedNative account = wsol account\n */\nexport async function createWSolAccountInstructions(params: CreateWSolTokenAccount): Promise<\n  AddInstructionParam & {\n    addresses: { newAccount: PublicKey };\n  }\n> {\n  const { connection, amount, commitment, payer, owner, skipCloseAccount } = params;\n\n  const balanceNeeded = await connection.getMinimumBalanceForRentExemption(splAccountLayout.span, commitment);\n  const lamports = parseBigNumberish(amount).add(new BN(balanceNeeded));\n  const newAccount = generatePubKey({ fromPublicKey: payer, programId: TOKEN_PROGRAM_ID });\n\n  return {\n    addresses: { newAccount: newAccount.publicKey },\n    signers: [],\n    instructions: [\n      SystemProgram.createAccountWithSeed({\n        fromPubkey: payer,\n        basePubkey: payer,\n        seed: newAccount.seed,\n        newAccountPubkey: newAccount.publicKey,\n        lamports: lamports.toNumber(),\n        space: splAccountLayout.span,\n        programId: TOKEN_PROGRAM_ID,\n      }),\n      initTokenAccountInstruction({\n        mint: new PublicKey(TOKEN_WSOL.address),\n        tokenAccount: newAccount.publicKey,\n        owner,\n        programId: TOKEN_PROGRAM_ID,\n      }),\n    ],\n    instructionTypes: [InstructionType.CreateAccount, InstructionType.InitAccount],\n    endInstructionTypes: skipCloseAccount ? [] : [InstructionType.CloseAccount],\n    endInstructions: skipCloseAccount\n      ? []\n      : [\n          closeAccountInstruction({\n            tokenAccount: newAccount.publicKey,\n            payer,\n            owner,\n          }),\n        ],\n  };\n}\n\nexport function makeTransferInstruction({\n  source,\n  destination,\n  owner,\n  amount,\n  multiSigners = [],\n  tokenProgram = TOKEN_PROGRAM_ID,\n}: {\n  source: PublicKey;\n  destination: PublicKey;\n  owner: PublicKey;\n  amount: BigNumberish;\n  multiSigners?: Signer[];\n  tokenProgram?: PublicKey;\n}): TransactionInstruction {\n  return createTransferInstruction(source, destination, owner, BigInt(String(amount)), multiSigners, tokenProgram);\n}\n","import { AccountInfo, PublicKey, RpcResponseAndContext, Keypair, GetProgramAccountsResponse } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\nimport { createLogger, getATAAddress } from \"@/common\";\n\nimport { splAccountLayout } from \"./layout\";\nimport { TokenAccount, TokenAccountRaw } from \"./types\";\nimport { sha256 } from \"@noble/hashes/sha256\";\n\nconst logger = createLogger(\"Raydium_Util\");\n\nexport interface ParseTokenAccount {\n  owner: PublicKey;\n  solAccountResp?: AccountInfo<Buffer> | null;\n  tokenAccountResp: RpcResponseAndContext<GetProgramAccountsResponse>;\n}\n\nexport function parseTokenAccountResp({ owner, solAccountResp, tokenAccountResp }: ParseTokenAccount): {\n  tokenAccounts: TokenAccount[];\n  tokenAccountRawInfos: TokenAccountRaw[];\n} {\n  const tokenAccounts: TokenAccount[] = [];\n  const tokenAccountRawInfos: TokenAccountRaw[] = [];\n\n  for (const { pubkey, account } of tokenAccountResp.value) {\n    const accountInfo = splAccountLayout.decode(account.data);\n    const { mint, amount } = accountInfo;\n    tokenAccounts.push({\n      publicKey: pubkey,\n      mint,\n      amount,\n      isAssociated: getATAAddress(owner, mint, account.owner).publicKey.equals(pubkey),\n      isNative: false,\n      programId: account.owner,\n    });\n    // todo programId should get from api\n    tokenAccountRawInfos.push({ pubkey, accountInfo, programId: account.owner });\n  }\n\n  if (solAccountResp) {\n    tokenAccounts.push({\n      mint: PublicKey.default,\n      amount: new BN(solAccountResp.lamports),\n      isNative: true,\n      programId: solAccountResp.owner,\n    });\n  }\n\n  return {\n    tokenAccounts,\n    tokenAccountRawInfos,\n  };\n}\n\nexport function generatePubKey({\n  fromPublicKey,\n  programId = TOKEN_PROGRAM_ID,\n}: {\n  fromPublicKey: PublicKey;\n  programId: PublicKey;\n}): { publicKey: PublicKey; seed: string } {\n  const seed = Keypair.generate().publicKey.toBase58().slice(0, 32);\n  const publicKey = createWithSeed(fromPublicKey, seed, programId);\n  return { publicKey, seed };\n}\n\nfunction createWithSeed(fromPublicKey: PublicKey, seed: string, programId: PublicKey): PublicKey {\n  const buffer = Buffer.concat([fromPublicKey.toBuffer(), Buffer.from(seed), programId.toBuffer()]);\n  const publicKeyBytes = sha256(buffer);\n  return new PublicKey(publicKeyBytes);\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 _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> = Structure<any, any, S>;\n\nexport class Union<Schema> 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 splAccountLayout = struct([\n  publicKey(\"mint\"),\n  publicKey(\"owner\"),\n  u64(\"amount\"),\n  u32(\"delegateOption\"),\n  publicKey(\"delegate\"),\n  u8(\"state\"),\n  u32(\"isNativeOption\"),\n  u64(\"isNative\"),\n  u64(\"delegatedAmount\"),\n  u32(\"closeAuthorityOption\"),\n  publicKey(\"closeAuthority\"),\n]);\n",null,null,null,null,"import { createAssociatedTokenAccountInstruction } from \"@solana/spl-token\";\nimport { PublicKey, SystemProgram } from \"@solana/web3.js\";\n\nimport { FormatFarmKeyOut } from \"@/api/type\";\nimport { AddInstructionParam, jsonInfo2PoolKeys } from \"@/common\";\nimport { parseBigNumberish, BN_ZERO } from \"@/common/bignumber\";\nimport { SOLMint, WSOLMint } from \"@/common/pubKey\";\nimport { MakeTxData, MakeMultiTxData } from \"@/common/txTool/txTool\";\nimport { InstructionType, TxVersion } from \"@/common/txTool/txType\";\nimport { getATAAddress } from \"@/common/pda\";\nimport { FARM_PROGRAM_ID_V6 } from \"@/common/programId\";\nimport { generatePubKey } from \"../account/util\";\n\nimport { createWSolAccountInstructions } from \"../account/instruction\";\nimport ModuleBase from \"../moduleBase\";\nimport { TOKEN_WSOL } from \"../token/constant\";\nimport { ComputeBudgetConfig } from \"@/raydium/type\";\nimport {\n  FARM_LOCK_MINT,\n  FARM_LOCK_VAULT,\n  isValidFarmVersion,\n  poolTypeV6,\n  validateFarmRewards,\n  FARM_PROGRAM_TO_VERSION,\n} from \"./config\";\nimport {\n  createAssociatedLedgerAccountInstruction,\n  makeCreateFarmInstruction,\n  makeCreatorWithdrawFarmRewardInstruction,\n  makeRestartRewardInstruction,\n  makeAddNewRewardInstruction,\n  makeWithdrawInstructionV3,\n  makeWithdrawInstructionV5,\n  makeWithdrawInstructionV6,\n  makeDepositInstructionV3,\n  makeDepositInstructionV5,\n  makeDepositInstructionV6,\n} from \"./instruction\";\nimport { farmStateV6Layout, FarmLedger } from \"./layout\";\nimport {\n  CreateFarm,\n  FarmDWParam,\n  FarmRewardInfo,\n  FarmRewardInfoConfig,\n  RewardInfoKey,\n  UpdateFarmReward,\n  UpdateFarmRewards,\n  CreateFarmExtInfo,\n} from \"./type\";\nimport {\n  calFarmRewardAmount,\n  farmRewardInfoToConfig,\n  getAssociatedAuthority,\n  getAssociatedLedgerAccount,\n  getAssociatedLedgerPoolAccount,\n  getFarmLedgerLayout,\n} from \"./util\";\nimport { FormatFarmInfoOut, FormatFarmKeyOutV6 } from \"@/api/type\";\nimport Decimal from \"decimal.js\";\n\nexport default class Farm extends ModuleBase {\n  // token account needed\n  private async _getUserRewardInfo({ payer, rewardInfo }: { payer: PublicKey; rewardInfo: FarmRewardInfo }): Promise<{\n    rewardPubKey?: PublicKey;\n    newInstruction?: AddInstructionParam;\n  }> {\n    if (rewardInfo.mint.equals(SOLMint)) {\n      const txInstructions = await createWSolAccountInstructions({\n        connection: this.scope.connection,\n        owner: this.scope.ownerPubKey,\n        payer,\n        amount: calFarmRewardAmount(rewardInfo),\n      });\n      return {\n        rewardPubKey: txInstructions.addresses.newAccount,\n        newInstruction: txInstructions,\n      };\n    }\n\n    return {\n      rewardPubKey: await this.scope.account.getCreatedTokenAccount({\n        mint: rewardInfo.mint,\n        associatedOnly: false,\n      })!,\n    };\n  }\n\n  // token account needed\n  public async create<T extends TxVersion>({\n    poolInfo: propPoolInfo,\n    rewardInfos,\n    payer,\n    programId = FARM_PROGRAM_ID_V6,\n    txVersion,\n  }: CreateFarm<T>): Promise<MakeTxData<T, CreateFarmExtInfo>> {\n    this.checkDisabled();\n    this.scope.checkOwner();\n\n    const lpMint = new PublicKey(propPoolInfo.lpMint.address);\n    const poolInfo = {\n      lpMint,\n      lockInfo: { lockMint: FARM_LOCK_MINT, lockVault: FARM_LOCK_VAULT },\n      version: 6,\n      rewardInfos,\n      programId,\n    };\n\n    const txBuilder = this.createTxBuilder();\n    const payerPubKey = payer ?? this.scope.ownerPubKey;\n    const farmKeyPair = generatePubKey({ fromPublicKey: payerPubKey, programId: poolInfo.programId });\n    const lamports = await this.scope.connection.getMinimumBalanceForRentExemption(farmStateV6Layout.span);\n\n    txBuilder.addInstruction({\n      instructions: [\n        SystemProgram.createAccountWithSeed({\n          fromPubkey: payerPubKey,\n          basePubkey: payerPubKey,\n          seed: farmKeyPair.seed,\n          newAccountPubkey: farmKeyPair.publicKey,\n          lamports,\n          space: farmStateV6Layout.span,\n          programId: poolInfo.programId,\n        }),\n      ],\n    });\n\n    const { publicKey: authority, nonce } = getAssociatedAuthority({\n      programId: new PublicKey(poolInfo.programId),\n      poolId: farmKeyPair.publicKey,\n    });\n\n    const lpVault = getAssociatedLedgerPoolAccount({\n      programId: poolInfo.programId,\n      poolId: farmKeyPair.publicKey,\n      mint: poolInfo.lpMint,\n      type: \"lpVault\",\n    });\n\n    const rewardInfoConfig: FarmRewardInfoConfig[] = [];\n    const rewardInfoKey: RewardInfoKey[] = [];\n\n    for (const rewardInfo of poolInfo.rewardInfos) {\n      if (rewardInfo.openTime >= rewardInfo.endTime)\n        this.logAndCreateError(\"start time error\", \"rewardInfo.rewardOpenTime\", rewardInfo.openTime.toString());\n      if (isNaN(poolTypeV6[rewardInfo.rewardType])) this.logAndCreateError(\"rewardType error\", rewardInfo.rewardType);\n      if (Number(rewardInfo.perSecond) <= 0) this.logAndCreateError(\"rewardPerSecond error\", rewardInfo.perSecond);\n\n      rewardInfoConfig.push(farmRewardInfoToConfig(rewardInfo));\n\n      const { rewardPubKey, newInstruction } = await this._getUserRewardInfo({\n        rewardInfo,\n        payer: payerPubKey,\n      });\n      if (newInstruction) txBuilder.addInstruction(newInstruction);\n\n      if (!rewardPubKey) this.logAndCreateError(\"cannot found target token accounts\", this.scope.account.tokenAccounts);\n\n      const rewardMint = rewardInfo.mint.equals(SOLMint) ? new PublicKey(TOKEN_WSOL.address) : rewardInfo.mint;\n      rewardInfoKey.push({\n        rewardMint,\n        rewardVault: getAssociatedLedgerPoolAccount({\n          programId: poolInfo.programId,\n          poolId: farmKeyPair.publicKey,\n          mint: rewardMint,\n          type: \"rewardVault\",\n        }),\n        userRewardToken: rewardPubKey!,\n      });\n    }\n\n    const lockUserAccount = await this.scope.account.getCreatedTokenAccount({\n      mint: poolInfo.lockInfo.lockMint,\n    });\n\n    if (!lockUserAccount)\n      this.logAndCreateError(\"cannot found lock vault\", \"tokenAccounts\", this.scope.account.tokenAccounts);\n\n    const { instruction, instructionType } = makeCreateFarmInstruction({\n      farmId: farmKeyPair.publicKey,\n      owner: this.scope.ownerPubKey,\n      farmAuthority: authority,\n      lpVault,\n      lpMint: poolInfo.lpMint,\n      lockVault: poolInfo.lockInfo.lockVault,\n      lockMint: poolInfo.lockInfo.lockMint,\n      lockUserAccount,\n      programId: poolInfo.programId,\n      rewardInfo: rewardInfoKey,\n      rewardInfoConfig,\n      nonce,\n    });\n\n    return txBuilder\n      .addInstruction({\n        instructions: [instruction],\n        instructionTypes: [instructionType],\n      })\n      .versionBuild<CreateFarmExtInfo>({\n        txVersion,\n        extInfo: {\n          farmId: farmKeyPair.publicKey,\n          farmAuthority: authority,\n          lpVault,\n          lockUserAccount: lockUserAccount!,\n          nonce,\n        },\n      }) as Promise<MakeTxData<T, CreateFarmExtInfo>>;\n  }\n\n  public async restartReward<T extends TxVersion>({\n    farmInfo,\n    payer,\n    newRewardInfo,\n    txVersion,\n  }: UpdateFarmReward): Promise<MakeTxData<T>> {\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n    if (version !== 6) this.logAndCreateError(\"invalid farm version \", version);\n\n    const farmInfoKeys = jsonInfo2PoolKeys((await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0]);\n\n    const farmKeys = {\n      id: farmInfoKeys.id,\n      rewardInfos: farmInfo.rewardInfos,\n      lpVault: farmInfoKeys.lpVault,\n      programId: farmInfoKeys.programId,\n    };\n\n    if (newRewardInfo.openTime >= newRewardInfo.endTime)\n      this.logAndCreateError(\"start time error\", \"newRewardInfo\", newRewardInfo);\n\n    const payerPubKey = payer || this.scope.ownerPubKey;\n\n    const rewardMint = newRewardInfo.mint.equals(SOLMint) ? new PublicKey(TOKEN_WSOL.address) : newRewardInfo.mint;\n    const rewardInfoIndex = farmKeys.rewardInfos.findIndex((item) =>\n      new PublicKey(item.mint.address).equals(rewardMint),\n    );\n    const rewardInfo = farmInfoKeys.rewardInfos[rewardInfoIndex];\n\n    if (!rewardInfo) this.logAndCreateError(\"configuration does not exist\", \"rewardMint\", rewardMint);\n\n    const rewardVault = rewardInfo!.vault ?? SOLMint;\n    const txBuilder = this.createTxBuilder();\n\n    const { rewardPubKey: userRewardTokenPub, newInstruction } = await this._getUserRewardInfo({\n      rewardInfo: newRewardInfo,\n      payer: payerPubKey,\n    });\n    if (newInstruction) txBuilder.addInstruction(newInstruction);\n\n    if (!userRewardTokenPub)\n      this.logAndCreateError(\"cannot found target token accounts\", this.scope.account.tokenAccounts);\n\n    return txBuilder\n      .addInstruction({\n        instructions: [\n          makeRestartRewardInstruction({\n            payer: this.scope.ownerPubKey,\n            rewardVault,\n            userRewardTokenPub: userRewardTokenPub!,\n            farmKeys,\n            rewardInfo: newRewardInfo,\n          }),\n        ],\n        instructionTypes: [InstructionType.FarmV6Restart],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async restartRewards<T extends TxVersion>({\n    farmInfo,\n    payer,\n    newRewardInfos,\n    txVersion,\n  }: UpdateFarmRewards<T>): Promise<MakeTxData<T>> {\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n    if (version !== 6) this.logAndCreateError(\"invalid farm version \", version);\n\n    const farmInfoKeys = jsonInfo2PoolKeys((await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0]);\n\n    const farmKeys = {\n      id: farmInfoKeys.id,\n      rewardInfos: farmInfo.rewardInfos,\n      lpVault: farmInfoKeys.lpVault,\n      programId: farmInfoKeys.programId,\n    };\n\n    newRewardInfos.forEach((reward) => {\n      if (reward.openTime >= reward.endTime) this.logAndCreateError(\"start time error\", \"newRewardInfo\", reward);\n    });\n\n    const payerPubKey = payer || this.scope.ownerPubKey;\n    const txBuilder = this.createTxBuilder();\n\n    for (const itemReward of newRewardInfos) {\n      const rewardMint = itemReward.mint.equals(SOLMint) ? new PublicKey(TOKEN_WSOL.address) : itemReward.mint;\n      const rewardInfoIndex = farmKeys.rewardInfos.findIndex((item) =>\n        new PublicKey(item.mint.address).equals(rewardMint),\n      );\n      const rewardInfo = farmInfoKeys.rewardInfos[rewardInfoIndex];\n      if (!rewardInfo) this.logAndCreateError(\"configuration does not exist\", \"rewardMint\", rewardMint);\n      const rewardVault = rewardInfo!.vault ?? SOLMint;\n      const { rewardPubKey: userRewardTokenPub, newInstruction } = await this._getUserRewardInfo({\n        rewardInfo: itemReward,\n        payer: payerPubKey,\n      });\n      if (newInstruction) txBuilder.addInstruction(newInstruction);\n      if (!userRewardTokenPub)\n        this.logAndCreateError(\"cannot found target token accounts\", this.scope.account.tokenAccounts);\n      const ins = makeRestartRewardInstruction({\n        payer: this.scope.ownerPubKey,\n        rewardVault,\n        userRewardTokenPub: userRewardTokenPub!,\n        farmKeys,\n        rewardInfo: itemReward,\n      });\n      txBuilder.addInstruction({\n        instructions: [ins],\n        instructionTypes: [InstructionType.FarmV6Restart],\n      });\n    }\n\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async addNewRewardToken<T extends TxVersion>(params: UpdateFarmReward): Promise<MakeTxData<T>> {\n    const { txVersion, farmInfo, newRewardInfo, payer } = params;\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n    if (version !== 6) this.logAndCreateError(\"invalid farm version \", version);\n\n    const farmKeys = jsonInfo2PoolKeys((await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0]);\n    const payerPubKey = payer ?? this.scope.ownerPubKey;\n    const txBuilder = this.createTxBuilder();\n\n    const rewardMint = newRewardInfo.mint.equals(SOLMint) ? new PublicKey(TOKEN_WSOL.address) : newRewardInfo.mint;\n\n    const rewardVault = getAssociatedLedgerPoolAccount({\n      programId: new PublicKey(farmInfo.programId),\n      poolId: new PublicKey(farmInfo.id),\n      mint: rewardMint,\n      type: \"rewardVault\",\n    });\n\n    const { rewardPubKey: userRewardTokenPub, newInstruction } = await this._getUserRewardInfo({\n      rewardInfo: newRewardInfo,\n      payer: payerPubKey,\n    });\n    if (newInstruction) txBuilder.addInstruction(newInstruction);\n\n    if (!userRewardTokenPub)\n      this.logAndCreateError(\"annot found target token accounts\", this.scope.account.tokenAccounts);\n\n    newRewardInfo.mint = rewardMint;\n\n    return txBuilder\n      .addInstruction({\n        instructions: [\n          makeAddNewRewardInstruction({\n            payer: this.scope.ownerPubKey,\n            userRewardTokenPub: userRewardTokenPub!,\n            farmKeys,\n            rewardVault,\n            rewardInfo: newRewardInfo,\n          }),\n        ],\n        instructionTypes: [InstructionType.FarmV6CreatorAddReward],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async addNewRewardsToken<T extends TxVersion>(params: UpdateFarmRewards<T>): Promise<MakeTxData<T>> {\n    const { txVersion, farmInfo, newRewardInfos, payer } = params;\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n    if (version !== 6) this.logAndCreateError(\"invalid farm version \", version);\n\n    const farmKeys = jsonInfo2PoolKeys((await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0]);\n    const payerPubKey = payer ?? this.scope.ownerPubKey;\n    const txBuilder = this.createTxBuilder();\n\n    for (const itemReward of newRewardInfos) {\n      const rewardMint = itemReward.mint.equals(SOLMint) ? new PublicKey(TOKEN_WSOL.address) : itemReward.mint;\n      const rewardVault = getAssociatedLedgerPoolAccount({\n        programId: new PublicKey(farmInfo.programId),\n        poolId: new PublicKey(farmInfo.id),\n        mint: rewardMint,\n        type: \"rewardVault\",\n      });\n      const { rewardPubKey: userRewardTokenPub, newInstruction } = await this._getUserRewardInfo({\n        rewardInfo: itemReward,\n        payer: payerPubKey,\n      });\n      if (newInstruction) txBuilder.addInstruction(newInstruction);\n      if (!userRewardTokenPub)\n        this.logAndCreateError(\"cannot found target token accounts\", this.scope.account.tokenAccounts);\n      const ins = makeAddNewRewardInstruction({\n        payer: this.scope.ownerPubKey,\n        userRewardTokenPub: userRewardTokenPub!,\n        farmKeys,\n        rewardVault,\n        rewardInfo: { ...itemReward, mint: rewardMint },\n      });\n      txBuilder.addInstruction({\n        instructions: [ins],\n        instructionTypes: [InstructionType.FarmV6CreatorAddReward],\n      });\n    }\n\n    return txBuilder.versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async deposit<T extends TxVersion>(params: FarmDWParam<T>): Promise<MakeTxData<T>> {\n    const {\n      txVersion,\n      farmInfo,\n      amount,\n      feePayer,\n      useSOLBalance,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      userAuxiliaryLedgers,\n      computeBudgetConfig,\n    } = params;\n\n    if (this.scope.availability.addFarm === false)\n      this.logAndCreateError(\"farm deposit feature disabled in your region\");\n\n    const { rewardInfos, programId } = farmInfo;\n    const version = FARM_PROGRAM_TO_VERSION[programId];\n    if (!isValidFarmVersion(version)) this.logAndCreateError(\"invalid farm program:\", farmInfo.programId);\n    const [farmProgramId, farmId] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n    const farmKeys = (await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0];\n\n    const ledger = getAssociatedLedgerAccount({\n      programId: farmProgramId,\n      poolId: farmId,\n      owner: this.scope.ownerPubKey,\n      version,\n    });\n\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    const ownerMintToAccount: { [mint: string]: PublicKey } = {};\n    for (const item of this.scope.account.tokenAccounts) {\n      if (associatedOnly) {\n        const ata = getATAAddress(this.scope.ownerPubKey, item.mint, item.programId).publicKey;\n        if (item.publicKey && ata.equals(item.publicKey)) ownerMintToAccount[item.mint.toString()] = item.publicKey;\n      } else {\n        ownerMintToAccount[item.mint.toString()] = item.publicKey!;\n      }\n    }\n\n    const lpMint = farmKeys.lpMint;\n    const ownerLpTokenAccount = ownerMintToAccount[lpMint.address];\n    if (!ownerLpTokenAccount) this.logAndCreateError(\"you don't have any lp\", \"lp zero\", ownerMintToAccount);\n\n    const rewardAccounts: PublicKey[] = [];\n    for (const itemReward of rewardInfos) {\n      const rewardUseSOLBalance = useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n\n      let ownerRewardAccount = ownerMintToAccount[itemReward.mint.address];\n\n      if (!ownerRewardAccount) {\n        const { account: _ownerRewardAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          mint: new PublicKey(itemReward.mint.address),\n          notUseTokenAccount: rewardUseSOLBalance,\n          createInfo: {\n            payer: feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !rewardUseSOLBalance,\n          associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n        ownerRewardAccount = _ownerRewardAccount!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n\n      ownerMintToAccount[itemReward.mint.address] = ownerRewardAccount;\n      rewardAccounts.push(ownerRewardAccount);\n    }\n\n    let ledgerInfo: FarmLedger | undefined = undefined;\n    const ledgerData = await this.scope.connection.getAccountInfo(ledger);\n    if (ledgerData) {\n      const ledgerLayout = getFarmLedgerLayout(version)!;\n      ledgerInfo = ledgerLayout.decode(ledgerData.data);\n    }\n\n    if (farmInfo.programId !== FARM_PROGRAM_ID_V6.toString() && !ledgerInfo) {\n      const { instruction, instructionType } = createAssociatedLedgerAccountInstruction({\n        id: farmId,\n        programId: farmProgramId,\n        version,\n        ledger,\n        owner: this.scope.ownerPubKey,\n      });\n      txBuilder.addInstruction({ instructions: [instruction], instructionTypes: [instructionType] });\n    }\n\n    const errorMsg = validateFarmRewards({\n      version,\n      rewardInfos,\n      rewardTokenAccountsPublicKeys: rewardAccounts,\n    });\n    if (errorMsg) this.logAndCreateError(errorMsg);\n\n    const insParams = {\n      amount: parseBigNumberish(amount),\n      owner: this.scope.ownerPubKey,\n      farmInfo,\n      farmKeys,\n      lpAccount: ownerLpTokenAccount,\n      rewardAccounts,\n      userAuxiliaryLedgers: userAuxiliaryLedgers?.map((key) => new PublicKey(key)),\n    };\n\n    const newInstruction =\n      version === 6\n        ? makeDepositInstructionV6(insParams)\n        : version === 5\n        ? makeDepositInstructionV5(insParams)\n        : makeDepositInstructionV3(insParams);\n\n    const insType = {\n      3: InstructionType.FarmV3Deposit,\n      5: InstructionType.FarmV5Deposit,\n      6: InstructionType.FarmV6Deposit,\n    };\n\n    return txBuilder\n      .addInstruction({\n        instructions: [newInstruction],\n        instructionTypes: [insType[version]],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async withdraw<T extends TxVersion>(params: FarmDWParam<T>): Promise<MakeTxData<T>> {\n    const {\n      txVersion,\n      farmInfo,\n      amount,\n      deposited,\n      useSOLBalance,\n      feePayer,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      userAuxiliaryLedgers,\n      computeBudgetConfig,\n    } = params;\n    const { rewardInfos } = farmInfo;\n\n    if (this.scope.availability.removeFarm === false)\n      this.logAndCreateError(\"farm withdraw feature disabled in your region\");\n\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n\n    if (!isValidFarmVersion(version)) this.logAndCreateError(\"invalid farm program:\", farmInfo.programId);\n\n    const farmKeys = (await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0];\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    const ownerMintToAccount: { [mint: string]: PublicKey } = {};\n    for (const item of this.scope.account.tokenAccounts) {\n      if (associatedOnly) {\n        const ata = getATAAddress(this.scope.ownerPubKey, item.mint).publicKey;\n        if (item.publicKey && ata.equals(item.publicKey)) ownerMintToAccount[item.mint.toString()] = item.publicKey;\n      } else {\n        ownerMintToAccount[item.mint.toString()] = item.publicKey!;\n      }\n    }\n\n    if (!deposited) {\n      const ledger = getAssociatedLedgerAccount({\n        programId: new PublicKey(farmInfo.programId),\n        poolId: new PublicKey(farmInfo.id),\n        owner: this.scope.ownerPubKey,\n        version,\n      });\n      const ledgerData = await this.scope.connection.getAccountInfo(ledger);\n      if (!ledgerData) this.logAndCreateError(\"no lp data\", { farmId: farmInfo.id, version, ledgerData });\n      const ledgerLayout = getFarmLedgerLayout(version)!;\n      const ledgerInfo = ledgerLayout.decode(ledgerData!.data);\n      if (ledgerInfo.deposited.isZero()) this.logAndCreateError(\"no deposited lp\", { farmId: farmInfo.id });\n    } else {\n      if (deposited.isZero()) this.logAndCreateError(\"no deposited lp\", { farmId: farmInfo.id });\n    }\n\n    const lpMint = farmKeys.lpMint.address;\n    const lpMintUseSOLBalance = useSOLBalance && lpMint === WSOLMint.toString();\n\n    let ownerLpTokenAccount = ownerMintToAccount[lpMint.toString()];\n    if (!ownerLpTokenAccount) {\n      const { account: _ownerRewardAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        mint: new PublicKey(lpMint),\n        notUseTokenAccount: lpMintUseSOLBalance,\n        createInfo: {\n          payer: feePayer || this.scope.ownerPubKey,\n          amount: 0,\n        },\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: true,\n        associatedOnly: lpMintUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n      ownerLpTokenAccount = _ownerRewardAccount!;\n      instructionParams && txBuilder.addInstruction(instructionParams);\n    }\n    ownerMintToAccount[lpMint.toString()] = ownerLpTokenAccount;\n\n    const rewardAccounts: PublicKey[] = [];\n    for (const itemReward of rewardInfos) {\n      const rewardUseSOLBalance = useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n\n      let ownerRewardAccount = ownerMintToAccount[itemReward.mint.address];\n      if (!ownerRewardAccount) {\n        const { account: _ownerRewardAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          mint: new PublicKey(itemReward.mint.address),\n          notUseTokenAccount: rewardUseSOLBalance,\n          createInfo: {\n            payer: feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: !rewardUseSOLBalance,\n          associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n        ownerRewardAccount = _ownerRewardAccount!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n\n      ownerMintToAccount[itemReward.mint.address] = ownerRewardAccount;\n      rewardAccounts.push(ownerRewardAccount);\n    }\n\n    const errorMsg = validateFarmRewards({\n      version,\n      rewardInfos,\n      rewardTokenAccountsPublicKeys: rewardAccounts,\n    });\n    if (errorMsg) this.logAndCreateError(errorMsg);\n\n    const insParams = {\n      amount: parseBigNumberish(amount),\n      owner: this.scope.ownerPubKey,\n      farmInfo,\n      farmKeys,\n      lpAccount: ownerLpTokenAccount,\n      rewardAccounts,\n      userAuxiliaryLedgers: userAuxiliaryLedgers?.map((key) => new PublicKey(key)),\n    };\n\n    const newInstruction =\n      version === 6\n        ? makeWithdrawInstructionV6(insParams)\n        : version === 5\n        ? makeWithdrawInstructionV5(insParams)\n        : makeWithdrawInstructionV3(insParams);\n\n    const insType = {\n      3: InstructionType.FarmV3Withdraw,\n      5: InstructionType.FarmV5Withdraw,\n      6: InstructionType.FarmV6Withdraw,\n    };\n\n    return txBuilder\n      .addInstruction({\n        instructions: [newInstruction],\n        instructionTypes: [insType[version]],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  // token account needed\n  public async withdrawFarmReward<T extends TxVersion>({\n    farmInfo,\n    withdrawMint,\n    txVersion,\n  }: {\n    farmInfo: FormatFarmInfoOut;\n    withdrawMint: PublicKey;\n    payer?: PublicKey;\n    txVersion?: T;\n  }): Promise<MakeTxData<T>> {\n    this.scope.checkOwner();\n    const farmKeys = jsonInfo2PoolKeys(\n      (await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0] as FormatFarmKeyOutV6,\n    );\n    const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n    if (version !== 6) this.logAndCreateError(\"invalid farm version\", version);\n\n    const rewardInfoIdx = farmInfo.rewardInfos.findIndex((item) =>\n      item.mint.address === SOLMint.toString() ? new PublicKey(TOKEN_WSOL.address) : withdrawMint,\n    );\n    const rewardInfo = farmKeys.rewardInfos[rewardInfoIdx];\n    if (!rewardInfo) this.logAndCreateError(\"withdraw mint error\", \"rewardInfos\", farmInfo);\n\n    const rewardVault = rewardInfo?.vault ?? SOLMint;\n    const txBuilder = this.createTxBuilder();\n\n    let userRewardToken: PublicKey;\n\n    if (withdrawMint.equals(SOLMint)) {\n      const txInstruction = await createWSolAccountInstructions({\n        connection: this.scope.connection,\n        owner: this.scope.ownerPubKey,\n        payer: this.scope.ownerPubKey,\n        amount: calFarmRewardAmount({\n          ...rewardInfo,\n          perSecond: new Decimal(rewardInfo.perSecond).mul(10 ** rewardInfo.mint.decimals).toString(),\n        }),\n      });\n      userRewardToken = txInstruction.addresses.newAccount;\n      txBuilder.addInstruction(txInstruction);\n    } else {\n      const selectUserRewardToken = await this.scope.account.getCreatedTokenAccount({\n        mint: withdrawMint,\n      });\n\n      if (selectUserRewardToken === null) {\n        userRewardToken = await this.scope.account.getAssociatedTokenAccount(withdrawMint);\n        txBuilder.addInstruction({\n          instructions: [\n            createAssociatedTokenAccountInstruction(\n              this.scope.ownerPubKey,\n              userRewardToken,\n              this.scope.ownerPubKey,\n              withdrawMint,\n            ),\n          ],\n          instructionTypes: [InstructionType.CreateATA],\n        });\n      } else {\n        userRewardToken = selectUserRewardToken!;\n      }\n    }\n\n    const { instruction, instructionType } = makeCreatorWithdrawFarmRewardInstruction({\n      programId: farmKeys.programId,\n      id: farmKeys.id,\n      authority: farmKeys.authority,\n      lpVault: farmKeys.lpVault,\n      rewardVault,\n      userRewardToken,\n      owner: this.scope.ownerPubKey,\n    });\n\n    return txBuilder\n      .addInstruction({\n        instructions: [instruction],\n        instructionTypes: [instructionType],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData<T>>;\n  }\n\n  public async harvestAllRewards<T extends TxVersion = TxVersion.LEGACY>(params: {\n    farmInfoList: Record<string, FormatFarmInfoOut>;\n    feePayer?: PublicKey;\n    useSOLBalance?: boolean;\n    associatedOnly?: boolean;\n    checkCreateATAOwner?: boolean;\n    userAuxiliaryLedgers?: string[];\n    txVersion?: T;\n    computeBudgetConfig?: ComputeBudgetConfig;\n  }): Promise<MakeMultiTxData<T>> {\n    const {\n      farmInfoList,\n      useSOLBalance,\n      feePayer,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      userAuxiliaryLedgers,\n      txVersion,\n      computeBudgetConfig,\n    } = params;\n\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    const ownerMintToAccount: { [mint: string]: PublicKey } = {};\n    for (const item of this.scope.account.tokenAccounts) {\n      if (associatedOnly) {\n        const ata = getATAAddress(this.scope.ownerPubKey, item.mint).publicKey;\n        if (item.publicKey && ata.equals(item.publicKey)) ownerMintToAccount[item.mint.toString()] = item.publicKey;\n      } else {\n        ownerMintToAccount[item.mint.toString()] = item.publicKey!;\n      }\n    }\n\n    const allFarmKeys = await this.scope.api.fetchFarmKeysById({\n      ids: Object.values(farmInfoList)\n        .map((f) => f.id)\n        .join(\",\"),\n    });\n    const farmKeyMap: { [key: string]: FormatFarmKeyOut } = allFarmKeys.reduce(\n      (acc, cur) => ({ ...acc, [cur.id]: cur }),\n      {},\n    );\n    for (const farmInfo of Object.values(farmInfoList)) {\n      const { programId, lpMint: farmLpMint, rewardInfos, id } = farmInfo;\n      const version = FARM_PROGRAM_TO_VERSION[programId];\n\n      const lpMint = farmLpMint.address;\n      const lpMintUseSOLBalance = useSOLBalance && lpMint === WSOLMint.toString();\n      let ownerLpTokenAccount = ownerMintToAccount[lpMint];\n\n      if (!ownerLpTokenAccount) {\n        const { account: _ownerLpAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          mint: new PublicKey(lpMint),\n          notUseTokenAccount: lpMintUseSOLBalance,\n          createInfo: {\n            payer: feePayer || this.scope.ownerPubKey,\n            amount: 0,\n          },\n          owner: this.scope.ownerPubKey,\n          skipCloseAccount: true,\n          associatedOnly: lpMintUseSOLBalance ? false : associatedOnly,\n          checkCreateATAOwner,\n        });\n        ownerLpTokenAccount = _ownerLpAccount!;\n        instructionParams && txBuilder.addInstruction(instructionParams);\n      }\n      ownerMintToAccount[lpMint.toString()] = ownerLpTokenAccount;\n\n      const rewardAccounts: PublicKey[] = [];\n      for (const itemReward of rewardInfos) {\n        const rewardUseSOLBalance = useSOLBalance && itemReward.mint.address === WSOLMint.toString();\n\n        let ownerRewardAccount = ownerMintToAccount[itemReward.mint.address];\n        if (!ownerRewardAccount) {\n          const { account: _ownerRewardAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n            mint: new PublicKey(itemReward.mint.address),\n            notUseTokenAccount: rewardUseSOLBalance,\n            createInfo: {\n              payer: feePayer || this.scope.ownerPubKey,\n              amount: 0,\n            },\n            owner: this.scope.ownerPubKey,\n            skipCloseAccount: !rewardUseSOLBalance,\n            associatedOnly: rewardUseSOLBalance ? false : associatedOnly,\n            checkCreateATAOwner,\n          });\n          ownerRewardAccount = _ownerRewardAccount!;\n          instructionParams && txBuilder.addInstruction(instructionParams);\n        }\n\n        ownerMintToAccount[itemReward.mint.address] = ownerRewardAccount;\n        rewardAccounts.push(ownerRewardAccount);\n      }\n\n      const farmKeys = farmKeyMap[id];\n      const insParams = {\n        amount: BN_ZERO,\n        owner: this.scope.ownerPubKey,\n        farmInfo,\n        farmKeys,\n        lpAccount: ownerLpTokenAccount,\n        rewardAccounts,\n        userAuxiliaryLedgers: userAuxiliaryLedgers?.map((key) => new PublicKey(key)),\n      };\n\n      const withdrawInstruction =\n        version === 6\n          ? makeWithdrawInstructionV6(insParams)\n          : version === 5\n          ? makeWithdrawInstructionV5(insParams)\n          : makeWithdrawInstructionV3(insParams);\n\n      const insType = {\n        3: InstructionType.FarmV3Withdraw,\n        5: InstructionType.FarmV5Withdraw,\n        6: InstructionType.FarmV6Withdraw,\n      };\n\n      txBuilder.addInstruction({\n        instructions: [withdrawInstruction],\n        instructionTypes: [insType[version]],\n      });\n    }\n\n    if (txVersion === TxVersion.LEGACY) return txBuilder.sizeCheckBuild() as Promise<MakeMultiTxData<T>>;\n    return txBuilder.sizeCheckBuildV0() as Promise<MakeMultiTxData<T>>;\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { createLogger } from \"@/common/logger\";\nimport { FARM_PROGRAM_ID_V3, FARM_PROGRAM_ID_V5, FARM_PROGRAM_ID_V6 } from \"@/common/programId\";\nimport { ApiV3Token, RewardInfoV345, RewardInfoV6 } from \"@/api/type\";\n\nimport {\n  FarmLedgerLayout,\n  farmLedgerLayoutV3_2,\n  farmLedgerLayoutV5_2,\n  farmLedgerLayoutV6_1,\n  FarmStateLayout,\n  farmStateV3Layout,\n  farmStateV5Layout,\n  farmStateV6Layout,\n} from \"./layout\";\n\nconst logger = createLogger(\"Raydium_farm_config\");\n\nexport type FarmVersion = 3 | 4 | 5 | 6;\nexport const FARM_LOCK_MINT = new PublicKey(\"4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R\");\nexport const FARM_LOCK_VAULT = new PublicKey(\"FrspKwj8i3pNmKwXreTveC4fu7KL5ZbGeXdZBe2XViu1\");\n\n/* ================= index ================= */\n// version => farm state layout\nexport const FARM_VERSION_TO_STATE_LAYOUT: {\n  [version in FarmVersion]?: FarmStateLayout;\n} = {\n  3: farmStateV3Layout,\n  5: farmStateV5Layout,\n  6: farmStateV6Layout,\n};\n\n// version => farm ledger layout\nexport const FARM_VERSION_TO_LEDGER_LAYOUT: {\n  [version in FarmVersion]?: FarmLedgerLayout;\n} = {\n  3: farmLedgerLayoutV3_2,\n  5: farmLedgerLayoutV5_2,\n  6: farmLedgerLayoutV6_1,\n};\n\nexport const isValidFarmVersion = (version: number): boolean => [3, 5, 6].indexOf(version) !== -1;\n\nexport const validateFarmRewards = (params: {\n  version: number;\n  rewardInfos: { mint: ApiV3Token }[];\n  rewardTokenAccountsPublicKeys: PublicKey[];\n}): (() => string | undefined) => {\n  const { version, rewardInfos, rewardTokenAccountsPublicKeys } = params;\n\n  const infoMsg = `rewardInfo:${JSON.stringify(rewardInfos)}, rewardAccount:${JSON.stringify(\n    rewardTokenAccountsPublicKeys,\n  )}`;\n\n  const validator = {\n    3: (): string | undefined => {\n      if (rewardInfos.length !== 1 || rewardTokenAccountsPublicKeys.length !== 1) {\n        return `rewardInfos or rewardTokenAccounts lengths not equal 1: ${infoMsg}`;\n      }\n    },\n    5: (): string | undefined => {\n      if (rewardInfos.length !== rewardTokenAccountsPublicKeys.length) {\n        return `rewardInfos and rewardTokenAccounts lengths not equal: ${infoMsg}`;\n      }\n    },\n    6: (): string | undefined => {\n      if (!rewardTokenAccountsPublicKeys.length || rewardInfos.length !== rewardTokenAccountsPublicKeys.length) {\n        return `no rewardTokenAccounts or rewardInfos and rewardTokenAccounts lengths not equal: ${infoMsg}`;\n      }\n    },\n  };\n\n  return validator[version]?.();\n};\n\nexport const poolTypeV6 = { \"Standard SPL\": 0, \"Option tokens\": 1 };\n\nexport const FARM_PROGRAM_TO_VERSION: Record<string, 3 | 5 | 6> = {\n  [FARM_PROGRAM_ID_V3.toString()]: 3,\n  [FARM_PROGRAM_ID_V5.toString()]: 5,\n  [FARM_PROGRAM_ID_V6.toString()]: 6,\n};\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport {\n  blob,\n  GetLayoutSchemaFromStructure,\n  GetStructureFromLayoutSchema,\n  GetStructureSchema,\n  publicKey,\n  seq,\n  struct,\n  u128,\n  u64,\n  u8,\n  i8,\n  i64,\n  bool,\n} from \"@/marshmallow\";\n\nimport { poolTypeV6 } from \"./config\";\nimport { RewardType } from \"./type\";\n\nexport const associatedLedgerAccountLayout = struct([u8(\"instruction\")]);\nexport const withdrawRewardLayout = struct([u8(\"instruction\")]);\n\nconst farmStateRewardInfoV6Layout = struct([\n  u64(\"rewardState\"),\n  u64(\"rewardOpenTime\"),\n  u64(\"rewardEndTime\"),\n  u64(\"rewardLastUpdateTime\"),\n  u64(\"totalReward\"),\n  u64(\"totalRewardEmissioned\"),\n  u64(\"rewardClaimed\"),\n  u64(\"rewardPerSecond\"),\n  u128(\"accRewardPerShare\"),\n  publicKey(\"rewardVault\"),\n  publicKey(\"rewardMint\"),\n  publicKey(\"rewardSender\"),\n  u64(\"rewardType\"),\n  seq(u64(), 15, \"padding\"),\n]);\n\nexport const realFarmStateV3Layout = struct([\n  u64(\"state\"),\n  u64(\"nonce\"),\n  publicKey(\"lpVault\"),\n  publicKey(\"rewardVault\"),\n  publicKey(),\n  publicKey(),\n  u64(),\n  u64(),\n  u64(\"totalReward\"),\n  u128(\"perShareReward\"),\n  u64(\"lastSlot\"),\n  u64(\"perSlotReward\"),\n]);\n\nexport const realFarmStateV5Layout = struct([\n  u64(\"state\"),\n  u64(\"nonce\"),\n  publicKey(\"lpVault\"),\n  publicKey(\"rewardVaultA\"),\n  u64(\"totalRewardA\"),\n  u128(\"perShareRewardA\"),\n  u64(\"perSlotRewardA\"),\n  u8(\"option\"),\n  publicKey(\"rewardVaultB\"),\n  blob(7),\n  u64(\"totalRewardB\"),\n  u128(\"perShareRewardB\"),\n  u64(\"perSlotRewardB\"),\n  u64(\"lastSlot\"),\n  publicKey(),\n]);\n\nexport const realFarmV6Layout = struct([\n  u64(),\n  u64(\"state\"),\n  u64(\"nonce\"),\n  u64(\"validRewardTokenNum\"),\n  u128(\"rewardMultiplier\"),\n  u64(\"rewardPeriodMax\"),\n  u64(\"rewardPeriodMin\"),\n  u64(\"rewardPeriodExtend\"),\n  publicKey(\"lpMint\"),\n  publicKey(\"lpVault\"),\n  seq(farmStateRewardInfoV6Layout, 5, \"rewardInfos\"),\n  publicKey(\"creator\"),\n  publicKey(),\n  seq(u64(), 32, \"padding\"),\n]);\n\nexport const farmStateV3Layout = new Proxy(\n  realFarmStateV3Layout as GetStructureFromLayoutSchema<\n    {\n      version: 3;\n      rewardInfos: {\n        rewardVault: PublicKey;\n        totalReward: BN;\n        perSlotReward: BN;\n        perShareReward: BN;\n      }[];\n    } & GetLayoutSchemaFromStructure<typeof realFarmStateV3Layout>\n  >,\n  {\n    get(target, p, receiver): any {\n      if (p === \"decode\")\n        return (...decodeParams: Parameters<typeof target[\"decode\"]>) => {\n          const originalResult = target.decode(...decodeParams);\n          return {\n            ...originalResult,\n            version: 3,\n            rewardInfos: [\n              {\n                rewardVault: originalResult.rewardVault,\n                totalReward: originalResult.totalReward,\n                perSlotReward: originalResult.perSlotReward,\n                perShareReward: originalResult.perShareReward,\n              },\n            ],\n          };\n        };\n      else return Reflect.get(target, p, receiver);\n    },\n  },\n);\n\nexport const farmStateV5Layout = new Proxy(\n  realFarmStateV5Layout as GetStructureFromLayoutSchema<\n    {\n      version: 5;\n      rewardInfos: {\n        rewardVault: PublicKey;\n        totalReward: BN;\n        perSlotReward: BN;\n        perShareReward: BN;\n      }[];\n    } & GetLayoutSchemaFromStructure<typeof realFarmStateV5Layout>\n  >,\n  {\n    get(target, p, receiver): any {\n      if (p === \"decode\")\n        return (...decodeParams: Parameters<typeof target[\"decode\"]>) => {\n          const originalResult = target.decode(...decodeParams);\n          return {\n            ...originalResult,\n            version: 5,\n            rewardInfos: [\n              {\n                rewardVault: originalResult.rewardVaultA,\n                totalReward: originalResult.totalRewardA,\n                perSlotReward: originalResult.perSlotRewardA,\n                perShareReward: originalResult.perShareRewardA,\n              },\n              {\n                rewardVault: originalResult.rewardVaultB,\n                totalReward: originalResult.totalRewardB,\n                perSlotReward: originalResult.perSlotRewardB,\n                perShareReward: originalResult.perShareRewardB,\n              },\n            ],\n          };\n        };\n      else return Reflect.get(target, p, receiver);\n    },\n  },\n);\n\nexport const farmStateV6Layout = new Proxy(\n  realFarmV6Layout as GetStructureFromLayoutSchema<\n    {\n      version: 6;\n      rewardInfos: {\n        rewardState: BN;\n        rewardOpenTime: BN;\n        rewardEndTime: BN;\n        rewardLastUpdateTime: BN;\n        totalReward: BN;\n        totalRewardEmissioned: BN;\n        rewardClaimed: BN;\n        rewardPerSecond: BN;\n        accRewardPerShare: BN;\n        rewardVault: PublicKey;\n        rewardMint: PublicKey;\n        rewardSender: PublicKey;\n        rewardType: RewardType;\n      }[];\n    } & GetLayoutSchemaFromStructure<typeof realFarmV6Layout>\n  >,\n  {\n    get(target, p, receiver): any {\n      if (p === \"decode\")\n        return (...decodeParams: Parameters<typeof target[\"decode\"]>) => {\n          const originalResult = target.decode(...decodeParams);\n          return {\n            ...originalResult,\n            version: 6,\n            rewardInfos: originalResult.rewardInfos.map((item) => ({\n              ...item,\n              rewardType: (Object.entries(poolTypeV6).find((i) => String(i[1]) === item.rewardType.toString()) ?? [\n                \"Standard SPL\",\n              ])[0],\n            })),\n          };\n        };\n      else return Reflect.get(target, p, receiver);\n    },\n  },\n);\n\nexport const farmRewardTimeInfoLayout = struct([\n  u64(\"isSet\"),\n  u64(\"rewardPerSecond\"),\n  u64(\"rewardOpenTime\"),\n  u64(\"rewardEndTime\"),\n  u64(\"rewardType\"),\n]);\n\nexport const farmRewardLayout = struct([\n  u8(\"instruction\"),\n  u64(\"nonce\"),\n  seq(farmRewardTimeInfoLayout, 5, \"rewardTimeInfo\"),\n]);\n\nexport const farmRewardRestartLayout = struct([\n  u8(\"instruction\"),\n  u64(\"rewardReopenTime\"),\n  u64(\"rewardEndTime\"),\n  u64(\"rewardPerSecond\"),\n]);\n\nexport const farmAddRewardLayout = struct([\n  u8(\"instruction\"),\n  u64(\"isSet\"),\n  u64(\"rewardPerSecond\"),\n  u64(\"rewardOpenTime\"),\n  u64(\"rewardEndTime\"),\n  u64(\"rewardType\"),\n]);\n\nexport type FarmStateLayoutV3 = typeof farmStateV3Layout;\nexport type FarmStateLayoutV5 = typeof farmStateV5Layout;\nexport type FarmStateLayoutV6 = typeof farmStateV6Layout;\n\nexport type FarmStateV3 = GetStructureSchema<FarmStateLayoutV3>;\nexport type FarmStateV5 = GetStructureSchema<FarmStateLayoutV5>;\nexport type FarmStateV6 = GetStructureSchema<FarmStateLayoutV6>;\n\nexport type FarmState = FarmStateV3 | FarmStateV5 | FarmStateV6;\n// farmStateLayoutV3\nexport type FarmStateLayout = FarmStateLayoutV3 | FarmStateLayoutV5 | FarmStateLayoutV6;\n\n/* ================= ledger layouts ================= */\nexport const farmLedgerLayoutV3_1 = struct([\n  u64(\"state\"),\n  publicKey(\"id\"),\n  publicKey(\"owner\"),\n  u64(\"deposited\"),\n  seq(u64(), 1, \"rewardDebts\"),\n]);\n\nexport const farmLedgerLayoutV3_2 = struct([\n  u64(\"state\"),\n  publicKey(\"id\"),\n  publicKey(\"owner\"),\n  u64(\"deposited\"),\n  seq(u128(), 1, \"rewardDebts\"),\n  u64(\"\"),\n  u64(\"voteLockedBalance\"),\n  seq(u64(), 15),\n]);\n\nexport const farmLedgerLayoutV5_1 = struct([\n  u64(\"state\"),\n  publicKey(\"id\"),\n  publicKey(\"owner\"),\n  u64(\"deposited\"),\n  seq(u64(), 2, \"rewardDebts\"),\n]);\n\nexport const farmLedgerLayoutV5_2 = struct([\n  u64(\"state\"),\n  publicKey(\"id\"),\n  publicKey(\"owner\"),\n  u64(\"deposited\"),\n  seq(u128(), 2, \"rewardDebts\"),\n  seq(u64(), 17),\n]);\n\nexport const farmLedgerLayoutV6_1 = struct([\n  u64(),\n  u64(\"state\"),\n  publicKey(\"id\"),\n  publicKey(\"owner\"),\n  u64(\"deposited\"),\n  seq(u128(), 5, \"rewardDebts\"),\n  seq(u64(), 16),\n]);\n\nexport type FarmLedgerLayoutV3_1 = typeof farmLedgerLayoutV3_1;\nexport type FarmLedgerLayoutV3_2 = typeof farmLedgerLayoutV3_2;\nexport type FarmLedgerLayoutV5_1 = typeof farmLedgerLayoutV5_1;\nexport type FarmLedgerLayoutV5_2 = typeof farmLedgerLayoutV5_2;\nexport type FarmLedgerLayoutV6_1 = typeof farmLedgerLayoutV6_1;\nexport type FarmLedgerLayout =\n  | FarmLedgerLayoutV3_1\n  | FarmLedgerLayoutV3_2\n  | FarmLedgerLayoutV5_1\n  | FarmLedgerLayoutV5_2\n  | FarmLedgerLayoutV6_1;\n\nexport type FarmLedgerV3_1 = GetStructureSchema<FarmLedgerLayoutV3_1>;\nexport type FarmLedgerV3_2 = GetStructureSchema<FarmLedgerLayoutV3_2>;\nexport type FarmLedgerV5_1 = GetStructureSchema<FarmLedgerLayoutV5_1>;\nexport type FarmLedgerV5_2 = GetStructureSchema<FarmLedgerLayoutV5_2>;\nexport type FarmLedgerV6_1 = GetStructureSchema<FarmLedgerLayoutV6_1>;\nexport type FarmLedger = FarmLedgerV3_1 | FarmLedgerV3_2 | FarmLedgerV5_1 | FarmLedgerV5_2 | FarmLedgerV6_1;\n\nexport const dwLayout = struct([u8(\"instruction\"), u64(\"amount\")]);\n\nexport const VoterVotingMintConfig = struct([\n  publicKey(\"mint\"),\n  publicKey(\"grantAuthority\"),\n  u64(\"baselineVoteWeightScaledFactor\"),\n  u64(\"maxExtraLockupVoteWeightScaledFactor\"),\n  u64(\"lockupSaturationSecs\"),\n\n  i8(\"digitShift\"), // TODO\n  seq(u8(), 7, \"reserved1\"),\n  seq(u64(), 7, \"reserved2\"),\n]);\n\nexport const VoterRegistrar = struct([\n  blob(8),\n  publicKey(\"governanceProgramId\"),\n  publicKey(\"realm\"),\n  publicKey(\"realmGoverningTokenMint\"),\n  publicKey(\"realmAuthority\"),\n\n  seq(u8(), 32, \"reserved1\"),\n  seq(VoterVotingMintConfig, 4, \"votingMints\"),\n\n  i64(\"timeOffset\"),\n  u8(\"bump\"),\n  seq(u8(), 7, \"reserved2\"),\n  seq(u64(), 11, \"reserved3\"),\n]);\n\nexport const VoterLockup = struct([i64(\"startTime\"), i64(\"endTime\"), u8(\"kind\"), seq(u8(), 15, \"reserved\")]);\n\nexport const VoterDepositEntry = struct([\n  seq(VoterLockup, 1, \"lockup\"),\n  u64(\"amountDeposited_native\"),\n  u64(\"amountInitiallyLockedNative\"),\n  bool(\"isUsed\"),\n  bool(\"allowClawback\"),\n  u8(\"votingMintConfigIdx\"),\n  seq(u8(), 29, \"reserved\"),\n]);\n\nexport const Voter = struct([\n  blob(8),\n  publicKey(\"voterAuthority\"),\n  publicKey(\"registrar\"),\n\n  seq(VoterDepositEntry, 32, \"deposits\"),\n\n  u8(\"voterBump\"),\n  u8(\"voterWweightRecordBump\"),\n  seq(u8(), 94, \"reserved\"),\n]);\n","import {\n  PublicKey,\n  SystemProgram,\n  SYSVAR_RENT_PUBKEY,\n  SYSVAR_CLOCK_PUBKEY,\n  TransactionInstruction,\n  Connection,\n} from \"@solana/web3.js\";\nimport {\n  createAssociatedTokenAccountInstruction,\n  TOKEN_PROGRAM_ID,\n  ASSOCIATED_TOKEN_PROGRAM_ID,\n} from \"@solana/spl-token\";\nimport BN from \"bn.js\";\n\nimport { struct, u8, u64, u32, bool } from \"@/marshmallow\";\nimport { FormatFarmKeyOut } from \"@/api/type\";\nimport { getATAAddress } from \"@/common/pda\";\nimport { createLogger } from \"@/common/logger\";\nimport { parseBigNumberish } from \"@/common/bignumber\";\nimport {\n  accountMeta,\n  commonSystemAccountMeta,\n  SOLMint,\n  RENT_PROGRAM_ID,\n  INSTRUCTION_PROGRAM_ID,\n} from \"@/common/pubKey\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { InstructionReturn } from \"../type\";\nimport {\n  associatedLedgerAccountLayout,\n  farmRewardLayout,\n  withdrawRewardLayout,\n  farmLedgerLayoutV3_2,\n  farmAddRewardLayout,\n} from \"./layout\";\nimport { FarmRewardInfoConfig, RewardInfoKey, RewardType } from \"./type\";\nimport {\n  getRegistrarAddress,\n  getVotingTokenMint,\n  getVotingMintAuthority,\n  getVoterAddress,\n  getVoterWeightRecordAddress,\n  getTokenOwnerRecordAddress,\n} from \"./pda\";\nimport { dwLayout, farmRewardRestartLayout } from \"./layout\";\nimport { getAssociatedLedgerAccount, getDepositEntryIndex } from \"./util\";\nimport { poolTypeV6 } from \"./config\";\n\nconst logger = createLogger(\"Raydium_farm_instruction\");\n\nconst anchorDataBuf = {\n  voterStakeRegistryCreateVoter: Buffer.from([6, 24, 245, 52, 243, 255, 148, 25]), // CreateVoter\n  voterStakeRegistryCreateDepositEntry: Buffer.from([185, 131, 167, 186, 159, 125, 19, 67]), // CreateDepositEntry\n  voterStakeRegistryDeposit: Buffer.from([242, 35, 198, 137, 82, 225, 242, 182]), // Deposit\n  voterStakeRegistryWithdraw: Buffer.from([183, 18, 70, 156, 148, 109, 161, 34]), // Withdraw\n  voterStakeRegistryUpdateVoterWeightRecord: Buffer.from([45, 185, 3, 36, 109, 190, 115, 169]), // UpdateVoterWeightRecord\n};\n\nexport function createAssociatedLedgerAccountInstruction(params: {\n  version: number;\n  id: PublicKey;\n  programId: PublicKey;\n  ledger: PublicKey;\n  owner: PublicKey;\n}): InstructionReturn {\n  const { version, id, ledger, programId, owner } = params;\n  const instruction = { 3: 9, 5: 10 }[version];\n  if (!instruction) logger.logWithError(`invalid farm pool version: ${version}`);\n\n  const data = Buffer.alloc(associatedLedgerAccountLayout.span);\n  associatedLedgerAccountLayout.encode(\n    {\n      instruction: instruction!,\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: ledger }),\n    accountMeta({ pubkey: owner, isWritable: false }),\n    accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n    accountMeta({ pubkey: SYSVAR_RENT_PUBKEY, isWritable: false }),\n  ];\n\n  return {\n    instruction: new TransactionInstruction({\n      programId,\n      keys,\n      data,\n    }),\n    instructionType: InstructionType.FarmV3CreateLedger,\n  };\n}\n\ninterface CreateFarmInstruction {\n  farmId: PublicKey;\n  farmAuthority: PublicKey;\n  lpVault: PublicKey;\n  lpMint: PublicKey;\n  lockVault: PublicKey;\n  lockMint: PublicKey;\n  lockUserAccount?: PublicKey;\n  programId: PublicKey;\n  owner: PublicKey;\n  rewardInfo: RewardInfoKey[];\n  rewardInfoConfig: FarmRewardInfoConfig[];\n  nonce: number;\n}\nexport function makeCreateFarmInstruction(params: CreateFarmInstruction): InstructionReturn {\n  const data = Buffer.alloc(farmRewardLayout.span);\n  farmRewardLayout.encode(\n    {\n      instruction: 0,\n      nonce: new BN(params.nonce),\n      rewardTimeInfo: params.rewardInfoConfig,\n    },\n    data,\n  );\n\n  const keys = [\n    ...commonSystemAccountMeta,\n    accountMeta({ pubkey: params.farmId }),\n    accountMeta({ pubkey: params.farmAuthority, isWritable: false }),\n    accountMeta({ pubkey: params.lpVault }),\n    accountMeta({ pubkey: params.lpMint, isWritable: false }),\n    accountMeta({ pubkey: params.lockVault }),\n    accountMeta({ pubkey: params.lockMint, isWritable: false }),\n    accountMeta({ pubkey: params.lockUserAccount ?? SOLMint }),\n    accountMeta({ pubkey: params.owner, isWritable: false, isSigner: true }),\n  ];\n\n  for (const item of params.rewardInfo) {\n    keys.push(\n      ...[\n        accountMeta({ pubkey: item.rewardMint, isWritable: false }),\n        accountMeta({ pubkey: item.rewardVault }),\n        accountMeta({ pubkey: item.userRewardToken }),\n      ],\n    );\n  }\n\n  return {\n    instruction: new TransactionInstruction({ programId: params.programId, keys, data }),\n    instructionType: InstructionType.FarmV6Create,\n  };\n}\n\ninterface CreatorWithdrawFarmRewardInstruction {\n  id: PublicKey;\n  programId: PublicKey;\n  authority: PublicKey;\n  lpVault: PublicKey;\n  rewardVault: PublicKey;\n  userRewardToken: PublicKey;\n  owner: PublicKey;\n}\n\nexport function makeCreatorWithdrawFarmRewardInstruction(\n  params: CreatorWithdrawFarmRewardInstruction,\n): InstructionReturn {\n  const data = Buffer.alloc(withdrawRewardLayout.span);\n  withdrawRewardLayout.encode({ instruction: 5 }, data);\n\n  const keys = [\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    accountMeta({ pubkey: params.id }),\n    accountMeta({ pubkey: params.authority, isWritable: false }),\n    accountMeta({ pubkey: params.lpVault, isWritable: false }),\n    accountMeta({ pubkey: params.rewardVault }),\n    accountMeta({ pubkey: params.userRewardToken }),\n    accountMeta({ pubkey: params.owner, isWritable: false, isSigner: true }),\n  ];\n\n  return {\n    instruction: new TransactionInstruction({ programId: params.programId, keys, data }),\n    instructionType: InstructionType.FarmV6CreatorWithdraw,\n  };\n}\n\nexport function voterStakeRegistryDeposit(\n  programId: PublicKey,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterVault: PublicKey,\n  depositToken: PublicKey,\n  depositAuthority: PublicKey,\n\n  userStakerInfoV2: PublicKey,\n  pool: PublicKey,\n  votingMint: PublicKey,\n  votingMintAuthority: PublicKey,\n  stakeProgramId: PublicKey,\n\n  depositEntryIndex: number,\n  amount: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"depositEntryIndex\"), u64(\"amount\")]);\n\n  const keys = [\n    { pubkey: registrar, isSigner: false, isWritable: false },\n    { pubkey: voter, isSigner: false, isWritable: true },\n    { pubkey: voterVault, isSigner: false, isWritable: true },\n    { pubkey: depositToken, isSigner: false, isWritable: true },\n    { pubkey: depositAuthority, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n\n    { pubkey: userStakerInfoV2, isSigner: false, isWritable: true },\n    { pubkey: pool, isSigner: false, isWritable: false },\n    { pubkey: votingMint, isSigner: false, isWritable: true },\n\n    { pubkey: votingMintAuthority, isSigner: false, isWritable: false },\n    { pubkey: stakeProgramId, isSigner: false, isWritable: false },\n    { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      depositEntryIndex,\n      amount,\n    },\n    data,\n  );\n  const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryDeposit, ...data]);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport function voterStakeRegistryUpdateVoterWeightRecord(\n  programId: PublicKey,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterWeightRecord: PublicKey,\n): TransactionInstruction {\n  const dataLayout = struct([]);\n\n  const keys = [\n    { pubkey: registrar, isSigner: false, isWritable: false },\n    { pubkey: voter, isSigner: false, isWritable: false },\n    { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode({}, data);\n  const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryUpdateVoterWeightRecord, ...data]);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport function voterStakeRegistryWithdraw(\n  programId: PublicKey,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterAuthority: PublicKey,\n  tokenOwnerRecord: PublicKey,\n  voterWeightRecord: PublicKey,\n  vault: PublicKey,\n  destination: PublicKey,\n\n  userStakerInfoV2: PublicKey,\n  pool: PublicKey,\n  votingMint: PublicKey,\n  votingMintAuthority: PublicKey,\n  stakeProgramId: PublicKey,\n\n  depositEntryIndex: number,\n  amount: BN,\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"depositEntryIndex\"), u64(\"amount\")]);\n\n  const keys = [\n    { pubkey: registrar, isSigner: false, isWritable: false },\n    { pubkey: voter, isSigner: false, isWritable: true },\n    { pubkey: voterAuthority, isSigner: true, isWritable: false },\n    { pubkey: tokenOwnerRecord, isSigner: false, isWritable: false },\n\n    { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n    { pubkey: vault, isSigner: false, isWritable: true },\n    { pubkey: destination, isSigner: false, isWritable: true },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n\n    { pubkey: userStakerInfoV2, isSigner: false, isWritable: true },\n    { pubkey: pool, isSigner: false, isWritable: false },\n    { pubkey: votingMint, isSigner: false, isWritable: true },\n\n    { pubkey: votingMintAuthority, isSigner: false, isWritable: false },\n    { pubkey: stakeProgramId, isSigner: false, isWritable: false },\n    { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      depositEntryIndex,\n      amount,\n    },\n    data,\n  );\n  const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryWithdraw, ...data]);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport function governanceCreateTokenOwnerRecord(\n  programId: PublicKey,\n  realm: PublicKey,\n  governingTokenOwner: PublicKey,\n  governingTokenMint: PublicKey,\n  payer: PublicKey,\n  tokenOwnerRecordAddress: PublicKey,\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"ins\")]);\n\n  const keys = [\n    { pubkey: realm, isSigner: false, isWritable: false },\n    { pubkey: governingTokenOwner, isSigner: false, isWritable: false },\n\n    { pubkey: tokenOwnerRecordAddress, isSigner: false, isWritable: true },\n\n    { pubkey: governingTokenMint, isSigner: false, isWritable: false },\n\n    { pubkey: payer, isSigner: true, isWritable: true },\n\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode({ ins: 23 }, data);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data,\n  });\n}\n\nexport function voterStakeRegistryCreateVoter(\n  programId: PublicKey,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterWeightRecord: PublicKey,\n  voterAuthority: PublicKey,\n  payer: PublicKey,\n\n  voterBump: number,\n  voterWeightRecordBump: number,\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"voterBump\"), u8(\"voterWeightRecordBump\")]);\n\n  const keys = [\n    { pubkey: registrar, isSigner: false, isWritable: false },\n    { pubkey: voter, isSigner: false, isWritable: true },\n    { pubkey: voterAuthority, isSigner: true, isWritable: false },\n    { pubkey: voterWeightRecord, isSigner: false, isWritable: true },\n    { pubkey: payer, isSigner: true, isWritable: true },\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: INSTRUCTION_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode({ voterBump, voterWeightRecordBump }, data);\n  const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryCreateVoter, ...data]);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport function voterStakeRegistryCreateDepositEntry(\n  programId: PublicKey,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterVault: PublicKey,\n  voterAuthority: PublicKey,\n  payer: PublicKey,\n  depositMint: PublicKey,\n\n  depositEntryIndex: number,\n  kind: number,\n  startTs: BN | undefined,\n  periods: number,\n  allowClawback: boolean,\n): TransactionInstruction {\n  const dataLayout = struct([\n    u8(\"depositEntryIndex\"),\n    u8(\"kind\"),\n    u8(\"option\"),\n    u64(\"startTs\"),\n    u32(\"periods\"),\n    bool(\"allowClawback\"),\n  ]);\n\n  const keys = [\n    { pubkey: registrar, isSigner: false, isWritable: false },\n    { pubkey: voter, isSigner: false, isWritable: true },\n    { pubkey: voterVault, isSigner: false, isWritable: true },\n    { pubkey: voterAuthority, isSigner: true, isWritable: false },\n    { pubkey: payer, isSigner: true, isWritable: true },\n    { pubkey: depositMint, 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: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      depositEntryIndex,\n      kind,\n      option: startTs === undefined ? 0 : 1,\n      startTs: startTs!,\n      periods,\n      allowClawback,\n    },\n    data,\n  );\n  const aData = Buffer.from([...anchorDataBuf.voterStakeRegistryCreateDepositEntry, ...data]);\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data: aData,\n  });\n}\n\nexport async function makeDepositTokenInstruction({\n  connection,\n  programId,\n  governanceProgramId,\n  voteWeightAddinProgramId,\n  realm,\n  communityTokenMint,\n  owner,\n  poolId,\n  tokenProgram,\n}: {\n  connection: Connection;\n  programId: PublicKey;\n  governanceProgramId: PublicKey;\n  voteWeightAddinProgramId: PublicKey;\n  realm: PublicKey;\n  communityTokenMint: PublicKey;\n  owner: PublicKey;\n  poolId: PublicKey;\n  tokenProgram?: PublicKey;\n}): Promise<TransactionInstruction[]> {\n  const registrar = getRegistrarAddress(voteWeightAddinProgramId, realm, communityTokenMint).publicKey;\n  const ownerPda = getAssociatedLedgerAccount({ programId, poolId, owner, version: 3 });\n  const ownerAccountInfo = await connection.getAccountInfo(ownerPda);\n  if (ownerAccountInfo === null) {\n    throw Error(\"user is not staker\");\n  }\n  const ownerInfo = farmLedgerLayoutV3_2.decode(ownerAccountInfo.data);\n  const mintAmount = ownerInfo.deposited.sub(ownerInfo.voteLockedBalance);\n  console.log(\"amount\", mintAmount.toString());\n  if (mintAmount.eq(new BN(0))) {\n    throw Error(\"user do not has new stake amount\");\n  }\n\n  const votingMint = getVotingTokenMint(programId, poolId).publicKey;\n  const votingMintAuthority = getVotingMintAuthority(programId, poolId).publicKey;\n  const { publicKey: voter, nonce: voterBump } = getVoterAddress(voteWeightAddinProgramId, registrar, owner);\n  const voterVault = getATAAddress(voter, votingMint, tokenProgram).publicKey;\n\n  const { publicKey: voterWeightRecord, nonce: voterWeightRecordBump } = getVoterWeightRecordAddress(\n    voteWeightAddinProgramId,\n    registrar,\n    owner,\n  );\n\n  const tokenOwnerRecordAddress = getTokenOwnerRecordAddress(\n    governanceProgramId,\n    realm,\n    communityTokenMint,\n    owner,\n  ).publicKey;\n\n  const instructions: TransactionInstruction[] = [];\n\n  const depositToken = getATAAddress(owner, votingMint, tokenProgram).publicKey;\n  const depositTokenAccountInfo = await connection.getAccountInfo(depositToken);\n  if (depositTokenAccountInfo === null) {\n    instructions.push(createAssociatedTokenAccountInstruction(owner, depositToken, owner, votingMint));\n  }\n  const voterAccountInfo = await connection.getAccountInfo(voter);\n  if (voterAccountInfo === null) {\n    const createTokenOwnerRecodeIns = governanceCreateTokenOwnerRecord(\n      governanceProgramId,\n      realm,\n      owner,\n      communityTokenMint,\n      owner,\n      tokenOwnerRecordAddress,\n    );\n\n    instructions.push(\n      createTokenOwnerRecodeIns,\n      voterStakeRegistryCreateVoter(\n        voteWeightAddinProgramId,\n        registrar,\n        voter,\n        voterWeightRecord,\n        owner,\n        owner,\n        voterBump,\n        voterWeightRecordBump,\n      ),\n    );\n  }\n\n  const { index: depositEntryIndex, isInit: depositEntryInit } = await getDepositEntryIndex(\n    connection,\n    registrar,\n    voter,\n    votingMint,\n  );\n  if (!depositEntryInit) {\n    instructions.push(\n      voterStakeRegistryCreateDepositEntry(\n        voteWeightAddinProgramId,\n        registrar,\n        voter,\n        voterVault,\n        owner,\n        owner,\n        votingMint,\n\n        depositEntryIndex,\n        0,\n        undefined,\n        0,\n        false,\n      ),\n    );\n  }\n\n  instructions.push(\n    voterStakeRegistryDeposit(\n      voteWeightAddinProgramId,\n      registrar,\n      voter,\n      voterVault,\n      depositToken,\n      owner,\n\n      ownerPda,\n      poolId,\n      votingMint,\n      votingMintAuthority,\n      programId,\n\n      depositEntryIndex,\n      mintAmount,\n    ),\n    voterStakeRegistryUpdateVoterWeightRecord(voteWeightAddinProgramId, registrar, voter, voterWeightRecord),\n  );\n\n  return instructions;\n}\n\nexport async function makeWithdrawTokenInstruction({\n  connection,\n  programId,\n  governanceProgramId,\n  voteWeightAddinProgramId,\n  realm,\n  communityTokenMint,\n  owner,\n  poolId,\n  tokenProgram,\n}: {\n  connection: Connection;\n  programId: PublicKey;\n\n  governanceProgramId: PublicKey;\n  voteWeightAddinProgramId: PublicKey;\n  realm: PublicKey;\n  communityTokenMint: PublicKey;\n  owner: PublicKey;\n  poolId: PublicKey;\n  tokenProgram?: PublicKey;\n}): Promise<TransactionInstruction[]> {\n  const registrar = getRegistrarAddress(voteWeightAddinProgramId, realm, communityTokenMint).publicKey;\n  const ownerPda = getAssociatedLedgerAccount({ programId, poolId, owner, version: 3 });\n  const ownerAccountInfo = await connection.getAccountInfo(ownerPda);\n  if (ownerAccountInfo === null) {\n    throw Error(\"user is not staker\");\n  }\n  const ownerInfo = farmLedgerLayoutV3_2.decode(ownerAccountInfo.data);\n  if (ownerInfo.voteLockedBalance.eq(new BN(0))) {\n    throw Error(\"user has vote locked balance = 0\");\n  }\n\n  const votingMint = getVotingTokenMint(programId, poolId).publicKey;\n  const votingMintAuthority = getVotingMintAuthority(programId, poolId).publicKey;\n  const { publicKey: voter } = getVoterAddress(voteWeightAddinProgramId, registrar, owner);\n  const voterVault = getATAAddress(voter, votingMint, tokenProgram).publicKey;\n  const { publicKey: voterWeightRecord } = getVoterWeightRecordAddress(voteWeightAddinProgramId, registrar, owner);\n\n  const tokenOwnerRecordAddress = getTokenOwnerRecordAddress(\n    governanceProgramId,\n    realm,\n    communityTokenMint,\n    owner,\n  ).publicKey;\n\n  const instructions: TransactionInstruction[] = [];\n\n  const { index: depositEntryIndex, isInit: depositEntryInit } = await getDepositEntryIndex(\n    connection,\n    registrar,\n    voter,\n    votingMint,\n  );\n  if (!depositEntryInit) throw Error(\"deposit entry index check error\");\n\n  instructions.push(\n    voterStakeRegistryWithdraw(\n      voteWeightAddinProgramId,\n      registrar,\n      voter,\n      owner,\n      tokenOwnerRecordAddress,\n      voterWeightRecord,\n      voterVault,\n      getATAAddress(owner, votingMint, tokenProgram).publicKey,\n      ownerPda,\n      poolId,\n      votingMint,\n      votingMintAuthority,\n      programId,\n\n      depositEntryIndex,\n      ownerInfo.voteLockedBalance,\n    ),\n  );\n\n  return instructions;\n}\n\nexport function makeRestartRewardInstruction({\n  payer,\n  rewardVault,\n  userRewardTokenPub,\n  farmKeys,\n  rewardInfo,\n}: {\n  payer: PublicKey;\n  rewardVault: PublicKey;\n  userRewardTokenPub: PublicKey;\n  farmKeys: {\n    id: PublicKey;\n    programId: PublicKey;\n    lpVault: PublicKey;\n  };\n  rewardInfo: {\n    openTime: number;\n    endTime: number;\n    perSecond: string;\n  };\n}): TransactionInstruction {\n  const data = Buffer.alloc(farmRewardRestartLayout.span);\n  farmRewardRestartLayout.encode(\n    {\n      instruction: 3,\n      rewardReopenTime: parseBigNumberish(rewardInfo.openTime),\n      rewardEndTime: parseBigNumberish(rewardInfo.endTime),\n      rewardPerSecond: parseBigNumberish(rewardInfo.perSecond),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    accountMeta({ pubkey: farmKeys.id }),\n    accountMeta({ pubkey: farmKeys.lpVault, isWritable: false }),\n    accountMeta({ pubkey: rewardVault }),\n    accountMeta({ pubkey: userRewardTokenPub! }),\n    accountMeta({ pubkey: payer, isWritable: false, isSigner: true }),\n  ];\n\n  return new TransactionInstruction({ programId: farmKeys.programId, keys, data });\n}\n\nexport function makeAddNewRewardInstruction({\n  payer,\n  userRewardTokenPub,\n  farmKeys,\n  rewardVault,\n  rewardInfo,\n}: {\n  payer: PublicKey;\n  userRewardTokenPub: PublicKey;\n  rewardVault: PublicKey;\n  farmKeys: {\n    id: PublicKey;\n    programId: PublicKey;\n    authority: PublicKey;\n  };\n  rewardInfo: {\n    mint: PublicKey;\n    openTime: number;\n    endTime: number;\n    perSecond: string;\n    rewardType: RewardType;\n  };\n}): TransactionInstruction {\n  const data = Buffer.alloc(farmAddRewardLayout.span);\n  farmAddRewardLayout.encode(\n    {\n      instruction: 4,\n      isSet: new BN(1),\n      rewardPerSecond: parseBigNumberish(rewardInfo.perSecond),\n      rewardOpenTime: parseBigNumberish(rewardInfo.openTime),\n      rewardEndTime: parseBigNumberish(rewardInfo.endTime),\n      rewardType: parseBigNumberish(poolTypeV6[rewardInfo.rewardType]),\n    },\n    data,\n  );\n\n  const keys = [\n    ...commonSystemAccountMeta,\n    accountMeta({ pubkey: farmKeys.id }),\n    accountMeta({ pubkey: farmKeys.authority, isWritable: false }),\n    accountMeta({ pubkey: rewardInfo.mint, isWritable: false }),\n    accountMeta({ pubkey: rewardVault }),\n    accountMeta({ pubkey: userRewardTokenPub! }),\n    accountMeta({ pubkey: payer, isWritable: false, isSigner: true }),\n  ];\n\n  return new TransactionInstruction({ programId: farmKeys.programId, keys, data });\n}\n\nexport function makeDepositWithdrawInstruction(params: {\n  instruction: number;\n  amount: BN;\n  farmInfo: { id: string; programId: string };\n  farmKeys: FormatFarmKeyOut;\n  lpAccount: PublicKey;\n  owner: PublicKey;\n  rewardAccounts: PublicKey[];\n  deposit?: boolean;\n  version: 3 | 5 | 6;\n}): TransactionInstruction {\n  const { farmInfo, farmKeys, version, lpAccount, rewardAccounts, owner, instruction, amount, deposit } = params;\n\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction,\n      amount,\n    },\n    data,\n  );\n\n  const keys =\n    version === 6\n      ? [\n          accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n          ...(deposit ? [accountMeta({ pubkey: SystemProgram.programId, isWritable: false })] : []),\n          accountMeta({ pubkey: id }),\n          accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n          accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n          accountMeta({ pubkey: ledgerAddress }),\n          accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n          accountMeta({ pubkey: lpAccount }),\n        ]\n      : [\n          accountMeta({ pubkey: id }),\n          accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n          accountMeta({ pubkey: ledgerAddress }),\n          accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n          accountMeta({ pubkey: lpAccount }),\n          accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n          accountMeta({ pubkey: rewardAccounts[0] }),\n          accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n          // system\n          accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n          accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n        ];\n\n  if (version === 5) {\n    for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n      keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n      keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n    }\n  }\n\n  if (version === 6) {\n    for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n      keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n      keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n    }\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\ninterface DepositWithdrawParams {\n  amount: BN;\n  farmInfo: { id: string; programId: string };\n  farmKeys: FormatFarmKeyOut;\n  lpAccount: PublicKey;\n  owner: PublicKey;\n  rewardAccounts: PublicKey[];\n  userAuxiliaryLedgers?: PublicKey[];\n}\n\nexport function makeWithdrawInstructionV6(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 6,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 2,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n\n    accountMeta({ pubkey: id }),\n\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n  ];\n\n  for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n    keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n    keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeWithdrawInstructionV5(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 5,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 12,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: rewardAccounts[0] }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n    // system\n    accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n  ];\n\n  for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n    keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n    keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n  }\n\n  if (userAuxiliaryLedgers) {\n    for (const auxiliaryLedger of userAuxiliaryLedgers) {\n      keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n    }\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeWithdrawInstructionV3(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 3,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 11,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: rewardAccounts[0] }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n    // system\n    accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n  ];\n\n  if (userAuxiliaryLedgers) {\n    for (const auxiliaryLedger of userAuxiliaryLedgers) {\n      keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n    }\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV3(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 3,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 10,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: rewardAccounts[0] }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n    // system\n    accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n  ];\n\n  if (userAuxiliaryLedgers) {\n    for (const auxiliaryLedger of userAuxiliaryLedgers) {\n      keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n    }\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV5(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount, userAuxiliaryLedgers } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 5,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 11,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: rewardAccounts[0] }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[0].vault) }),\n    // system\n    accountMeta({ pubkey: SYSVAR_CLOCK_PUBKEY, isWritable: false }),\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n  ];\n\n  for (let index = 1; index < farmKeys.rewardInfos.length; index++) {\n    keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n    keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n  }\n\n  if (userAuxiliaryLedgers) {\n    for (const auxiliaryLedger of userAuxiliaryLedgers) {\n      keys.push(accountMeta({ pubkey: auxiliaryLedger }));\n    }\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n\nexport function makeDepositInstructionV6(params: DepositWithdrawParams): TransactionInstruction {\n  const { farmInfo, farmKeys, lpAccount, rewardAccounts, owner, amount } = params;\n  const [programId, id] = [new PublicKey(farmInfo.programId), new PublicKey(farmInfo.id)];\n\n  const ledgerAddress = getAssociatedLedgerAccount({\n    programId,\n    poolId: id,\n    owner,\n    version: 6,\n  });\n\n  const data = Buffer.alloc(dwLayout.span);\n  dwLayout.encode(\n    {\n      instruction: 1,\n      amount: parseBigNumberish(amount),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n    accountMeta({ pubkey: id }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(farmKeys.lpVault) }),\n    accountMeta({ pubkey: ledgerAddress }),\n    accountMeta({ pubkey: owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: lpAccount }),\n  ];\n\n  for (let index = 0; index < farmKeys.rewardInfos.length; index++) {\n    keys.push(accountMeta({ pubkey: new PublicKey(farmKeys.rewardInfos[index].vault) }));\n    keys.push(accountMeta({ pubkey: rewardAccounts[index] }));\n  }\n\n  return new TransactionInstruction({ programId, keys, data });\n}\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { GetMultipleAccountsInfoConfig, getMultipleAccountsInfoWithCustomFlags } from \"@/common/accountInfo\";\nimport { parseBigNumberish } from \"@/common/bignumber\";\nimport { createLogger } from \"@/common/logger\";\nimport { findProgramAddress, ProgramAddress } from \"@/common/txTool/txUtils\";\nimport { DateParam, isDateAfter, isDateBefore } from \"@/common/date\";\nimport { jsonInfo2PoolKeys } from \"@/common/utility\";\nimport { RewardInfoV6 } from \"@/api/type\";\n\nimport { splAccountLayout } from \"../account/layout\";\nimport { SplAccount } from \"../account/types\";\nimport { FARM_VERSION_TO_LEDGER_LAYOUT, FARM_VERSION_TO_STATE_LAYOUT, poolTypeV6 } from \"./config\";\nimport { FarmLedger, FarmLedgerLayout, FarmState, FarmStateLayout } from \"./layout\";\nimport { FarmRewardInfo, FarmRewardInfoConfig } from \"./type\";\n\nimport { VoterRegistrar, Voter } from \"./layout\";\n\nconst logger = createLogger(\"Raydium.farm.util\");\ninterface AssociatedLedgerPoolAccount {\n  programId: PublicKey;\n  poolId: PublicKey;\n  mint: PublicKey;\n  type: \"lpVault\" | \"rewardVault\";\n}\n\nexport function getAssociatedLedgerPoolAccount({\n  programId,\n  poolId,\n  mint,\n  type,\n}: AssociatedLedgerPoolAccount): PublicKey {\n  const { publicKey } = findProgramAddress(\n    [\n      poolId.toBuffer(),\n      mint.toBuffer(),\n      Buffer.from(\n        type === \"lpVault\" ? \"lp_vault_associated_seed\" : type === \"rewardVault\" ? \"reward_vault_associated_seed\" : \"\",\n        \"utf-8\",\n      ),\n    ],\n    programId,\n  );\n  return publicKey;\n}\n\nexport function getAssociatedLedgerAccount({\n  programId,\n  poolId,\n  owner,\n  version,\n}: {\n  programId: PublicKey;\n  poolId: PublicKey;\n  owner: PublicKey;\n  version: 6 | 5 | 3;\n}): PublicKey {\n  const { publicKey } = findProgramAddress(\n    [\n      poolId.toBuffer(),\n      owner.toBuffer(),\n      Buffer.from(version === 6 ? \"farmer_info_associated_seed\" : \"staker_info_v2_associated_seed\", \"utf-8\"),\n    ],\n    programId,\n  );\n  return publicKey;\n}\n\nexport const getAssociatedAuthority = ({\n  programId,\n  poolId,\n}: {\n  programId: PublicKey;\n  poolId: PublicKey;\n}): ProgramAddress => findProgramAddress([poolId.toBuffer()], programId);\n\nexport function farmRewardInfoToConfig(data: FarmRewardInfo): FarmRewardInfoConfig {\n  return {\n    isSet: new BN(1),\n    rewardPerSecond: parseBigNumberish(data.perSecond),\n    rewardOpenTime: parseBigNumberish(data.openTime),\n    rewardEndTime: parseBigNumberish(data.endTime),\n    rewardType: parseBigNumberish(poolTypeV6[data.rewardType]),\n  };\n}\n\nexport function calFarmRewardAmount(data: Pick<RewardInfoV6, \"openTime\" | \"endTime\"> & { perSecond: string }): BN {\n  return parseBigNumberish(data.endTime).sub(parseBigNumberish(data.openTime)).mul(parseBigNumberish(data.perSecond));\n}\n\nexport function getFarmLedgerLayout(version: number): FarmLedgerLayout | undefined {\n  const ledgerLayout = FARM_VERSION_TO_LEDGER_LAYOUT[version];\n  if (!ledgerLayout) logger.logWithError(\"invalid version\", version);\n  return ledgerLayout;\n}\n\nexport function getFarmStateLayout(version: number): FarmStateLayout | undefined {\n  const stateLayout = FARM_VERSION_TO_STATE_LAYOUT[version];\n  if (!stateLayout) logger.logWithError(\"invalid version\", version);\n  return stateLayout;\n}\n\nexport function updateFarmPoolInfo(\n  poolInfo: FarmState,\n  lpVault: SplAccount,\n  slot: number,\n  chainTime: number,\n): FarmState {\n  if (poolInfo.version === 3 || poolInfo.version === 5) {\n    if (poolInfo.lastSlot.gte(new BN(slot))) return poolInfo;\n\n    const spread = new BN(slot).sub(poolInfo.lastSlot);\n    poolInfo.lastSlot = new BN(slot);\n\n    for (const itemRewardInfo of poolInfo.rewardInfos) {\n      if (lpVault.amount.eq(new BN(0))) continue;\n\n      const reward = itemRewardInfo.perSlotReward.mul(spread);\n      itemRewardInfo.perShareReward = itemRewardInfo.perShareReward.add(\n        reward.mul(new BN(10).pow(new BN(poolInfo.version === 3 ? 9 : 15))).div(lpVault.amount),\n      );\n      itemRewardInfo.totalReward = itemRewardInfo.totalReward.add(reward);\n    }\n  } else if (poolInfo.version === 6) {\n    for (const itemRewardInfo of poolInfo.rewardInfos) {\n      if (itemRewardInfo.rewardState.eq(new BN(0))) continue;\n      const updateTime = BN.min(new BN(chainTime), itemRewardInfo.rewardEndTime);\n      if (itemRewardInfo.rewardOpenTime.gte(updateTime)) continue;\n      const spread = updateTime.sub(itemRewardInfo.rewardLastUpdateTime);\n      let reward = spread.mul(itemRewardInfo.rewardPerSecond);\n      const leftReward = itemRewardInfo.totalReward.sub(itemRewardInfo.totalRewardEmissioned);\n      if (leftReward.lt(reward)) {\n        reward = leftReward;\n        itemRewardInfo.rewardLastUpdateTime = itemRewardInfo.rewardLastUpdateTime.add(\n          leftReward.div(itemRewardInfo.rewardPerSecond),\n        );\n      } else {\n        itemRewardInfo.rewardLastUpdateTime = updateTime;\n      }\n      if (lpVault.amount.eq(new BN(0))) continue;\n      itemRewardInfo.accRewardPerShare = itemRewardInfo.accRewardPerShare.add(\n        reward.mul(poolInfo.rewardMultiplier).div(lpVault.amount),\n      );\n      itemRewardInfo.totalRewardEmissioned = itemRewardInfo.totalRewardEmissioned.add(reward);\n    }\n  }\n  return poolInfo;\n}\n\ninterface FarmPoolsInfo {\n  [id: string]: {\n    state: FarmState;\n    lpVault: SplAccount;\n    ledger?: FarmLedger;\n    wrapped?: { pendingRewards: BN[] };\n  };\n}\n\nexport interface FarmFetchMultipleInfoParams {\n  connection: Connection;\n  farmPools: any[];\n  owner?: PublicKey;\n  config?: GetMultipleAccountsInfoConfig;\n  chainTime: number;\n}\n\nexport async function fetchMultipleFarmInfoAndUpdate({\n  connection,\n  farmPools,\n  owner,\n  config,\n  chainTime,\n}: FarmFetchMultipleInfoParams): Promise<FarmPoolsInfo> {\n  let hasNotV6Pool = false;\n  let hasV6Pool = false;\n  const tenBN = new BN(10);\n\n  const publicKeys: {\n    pubkey: PublicKey;\n    version: number;\n    key: \"state\" | \"lpVault\" | \"ledger\";\n    poolId: PublicKey;\n  }[] = [];\n\n  for (const poolInfo of farmPools) {\n    const pool = jsonInfo2PoolKeys(poolInfo);\n    if (pool.version === 6) hasV6Pool = true;\n    else hasNotV6Pool = true;\n\n    publicKeys.push(\n      {\n        pubkey: pool.id,\n        version: pool.version,\n        key: \"state\",\n        poolId: pool.id,\n      },\n      {\n        pubkey: pool.lpVault,\n        version: pool.version,\n        key: \"lpVault\",\n        poolId: pool.id,\n      },\n    );\n\n    if (owner) {\n      publicKeys.push({\n        pubkey: getAssociatedLedgerAccount({\n          programId: pool.programId,\n          poolId: pool.id,\n          owner,\n          version: poolInfo.version as 6 | 5 | 3,\n        }),\n        version: pool.version,\n        key: \"ledger\",\n        poolId: pool.id,\n      });\n    }\n  }\n\n  const poolsInfo: FarmPoolsInfo = {};\n  const accountsInfo = await getMultipleAccountsInfoWithCustomFlags(connection, publicKeys, config);\n  for (const { pubkey, version, key, poolId, accountInfo } of accountsInfo) {\n    const _poolId = poolId.toBase58();\n    poolsInfo[_poolId] = { ...poolsInfo[_poolId] };\n    if (key === \"state\") {\n      const stateLayout = getFarmStateLayout(version);\n      if (!accountInfo || !accountInfo.data || accountInfo.data.length !== stateLayout!.span)\n        logger.logWithError(`invalid farm state account info, pools.id, ${pubkey}`);\n      poolsInfo[_poolId].state = stateLayout!.decode(accountInfo!.data);\n    } else if (key === \"lpVault\") {\n      if (!accountInfo || !accountInfo.data || accountInfo.data.length !== splAccountLayout.span)\n        logger.logWithError(`invalid farm lp vault account info, pools.lpVault, ${pubkey}`);\n      poolsInfo[_poolId].lpVault = splAccountLayout.decode(accountInfo!.data);\n    } else if (key === \"ledger\") {\n      const legerLayout = getFarmLedgerLayout(version)!;\n      if (accountInfo && accountInfo.data) {\n        if (accountInfo.data.length !== legerLayout.span)\n          logger.logWithError(`invalid farm ledger account info, ledger, ${pubkey}`);\n        poolsInfo[_poolId].ledger = legerLayout.decode(accountInfo.data);\n      }\n    }\n  }\n\n  const slot = hasV6Pool || hasNotV6Pool ? await connection.getSlot() : 0;\n\n  for (const poolId of Object.keys(poolsInfo)) {\n    if (poolsInfo[poolId] === undefined) continue;\n    poolsInfo[poolId].state = updateFarmPoolInfo(poolsInfo[poolId].state, poolsInfo[poolId].lpVault, slot, chainTime);\n  }\n\n  for (const [poolId, { state, ledger }] of Object.entries(poolsInfo)) {\n    if (ledger) {\n      const multiplier =\n        state.version === 6\n          ? state.rewardMultiplier\n          : state.rewardInfos.length === 1\n          ? tenBN.pow(new BN(9))\n          : tenBN.pow(new BN(15));\n\n      const pendingRewards = state.rewardInfos.map((rewardInfo, index) => {\n        const rewardDebt = ledger.rewardDebts[index];\n        const pendingReward = ledger.deposited\n          .mul(state.version === 6 ? rewardInfo.accRewardPerShare : rewardInfo.perShareReward)\n          .div(multiplier)\n          .sub(rewardDebt);\n\n        return pendingReward;\n      });\n\n      poolsInfo[poolId].wrapped = {\n        ...poolsInfo[poolId].wrapped,\n        pendingRewards,\n      };\n    }\n  }\n\n  return poolsInfo;\n}\n/** deprecated */\nexport function judgeFarmType(\n  info: any,\n  currentTime: DateParam = Date.now(),\n): \"closed pool\" | \"normal fusion pool\" | \"dual fusion pool\" | undefined | \"upcoming pool\" {\n  if (info.version === 6) {\n    const rewardInfos = info.state.rewardInfos;\n    if (rewardInfos.every(({ rewardOpenTime }) => isDateBefore(currentTime, rewardOpenTime.toNumber(), { unit: \"s\" })))\n      return \"upcoming pool\";\n    if (rewardInfos.every(({ rewardEndTime }) => isDateAfter(currentTime, rewardEndTime.toNumber(), { unit: \"s\" })))\n      return \"closed pool\";\n  } else {\n    const perSlotRewards = info.state.rewardInfos.map(({ perSlotReward }) => perSlotReward);\n    if (perSlotRewards.length === 2) {\n      // v5\n      if (String(perSlotRewards[0]) === \"0\" && String(perSlotRewards[1]) !== \"0\") {\n        return \"normal fusion pool\"; // reward xxx token\n      }\n      if (String(perSlotRewards[0]) !== \"0\" && String(perSlotRewards[1]) !== \"0\") {\n        return \"dual fusion pool\"; // reward ray and xxx token\n      }\n      if (String(perSlotRewards[0]) === \"0\" && String(perSlotRewards[1]) === \"0\") {\n        return \"closed pool\";\n      }\n    } else if (perSlotRewards.length === 1) {\n      // v3\n      if (String(perSlotRewards[0]) === \"0\") {\n        return \"closed pool\";\n      }\n    }\n  }\n}\n\nexport async function getDepositEntryIndex(\n  connection: Connection,\n  registrar: PublicKey,\n  voter: PublicKey,\n  voterMint: PublicKey,\n): Promise<{ index: number; isInit: boolean }> {\n  const registrarAccountData = await connection.getAccountInfo(registrar);\n  if (registrarAccountData === null) throw Error(\"registrar info check error\");\n  const registrarData = VoterRegistrar.decode(registrarAccountData.data);\n\n  const votingMintConfigIndex = registrarData.votingMints.findIndex((i) => i.mint.equals(voterMint));\n\n  if (votingMintConfigIndex === -1) throw Error(\"find voter mint error\");\n\n  const voterAccountData = await connection.getAccountInfo(voter);\n  if (voterAccountData === null) return { index: votingMintConfigIndex, isInit: false }; // throw Error('voter info check error')\n\n  const voterData = Voter.decode(voterAccountData.data);\n\n  const depositEntryIndex = voterData.deposits.findIndex(\n    (i) => i.isUsed && i.votingMintConfigIdx === votingMintConfigIndex,\n  );\n  if (depositEntryIndex === -1) return { index: votingMintConfigIndex, isInit: false };\n  else return { index: depositEntryIndex, isInit: true };\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport { NATIVE_MINT, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport {\n  ApiV3PoolInfoConcentratedItem,\n  ApiV3PoolInfoStandardItem,\n  AmmV4Keys,\n  AmmV5Keys,\n  ClmmKeys,\n  FormatFarmInfoOutV6,\n} from \"@/api/type\";\nimport { Token, TokenAmount, Percent } from \"@/module\";\nimport { solToWSol } from \"@/common/pubKey\";\nimport { toToken } from \"../token\";\nimport { BN_ZERO, BN_ONE, divCeil } from \"@/common/bignumber\";\nimport { getATAAddress } from \"@/common/pda\";\nimport { InstructionType, TxVersion } from \"@/common/txTool/txType\";\nimport { MakeMultiTxData, MakeTxData } from \"@/common/txTool/txTool\";\n\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport { AmountSide, AddLiquidityParams, RemoveParams, CreatePoolParam, CreatePoolAddress } from \"./type\";\nimport { makeAddLiquidityInstruction } from \"./instruction\";\nimport { ComputeBudgetConfig } from \"../type\";\nimport { removeLiquidityInstruction, createPoolV4InstructionV2 } from \"./instruction\";\nimport { ClmmInstrument } from \"../clmm/instrument\";\nimport { getAssociatedPoolKeys, getAssociatedConfigId } from \"./utils\";\nimport { createPoolFeeLayout } from \"./layout\";\nimport {\n  FARM_PROGRAM_TO_VERSION,\n  makeWithdrawInstructionV3,\n  makeWithdrawInstructionV5,\n  makeWithdrawInstructionV6,\n} from \"@/raydium/farm\";\n\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nexport default class LiquidityModule extends ModuleBase {\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  public async load(): Promise<void> {\n    this.checkDisabled();\n  }\n\n  public computePairAmount({\n    poolInfo,\n    amount,\n    // anotherToken,\n    slippage,\n    baseIn,\n  }: {\n    poolInfo: ApiV3PoolInfoStandardItem;\n    amount: string | Decimal;\n    // anotherToken: Token;\n    slippage: Percent;\n    baseIn?: boolean;\n  }): { anotherAmount: TokenAmount; maxAnotherAmount: TokenAmount; liquidity: BN } {\n    const inputAmount = new BN(new Decimal(amount).mul(10 ** poolInfo[baseIn ? \"mintA\" : \"mintB\"].decimals).toFixed(0));\n    const _anotherToken = toToken(poolInfo[baseIn ? \"mintB\" : \"mintA\"]);\n\n    const [baseReserve, quoteReserve] = [\n      new BN(new Decimal(poolInfo.mintAmountA).mul(10 ** poolInfo.mintA.decimals).toString()),\n      new BN(new Decimal(poolInfo.mintAmountB).mul(10 ** poolInfo.mintB.decimals).toString()),\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      \"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    // round up\n    let amountRaw = BN_ZERO;\n    if (!inputAmount.isZero()) {\n      amountRaw =\n        input === \"base\"\n          ? divCeil(inputAmount.mul(quoteReserve), baseReserve)\n          : divCeil(inputAmount.mul(baseReserve), quoteReserve);\n    }\n\n    const liquidity = divCeil(\n      inputAmount.mul(new BN(poolInfo.lpAmount).mul(new BN(10).pow(new BN(poolInfo.lpMint.decimals)))),\n      new BN(input === \"base\" ? poolInfo.mintAmountA : poolInfo.mintAmountB).mul(\n        new BN(10).pow(new BN(poolInfo[input === \"base\" ? \"mintA\" : \"mintB\"].decimals)),\n      ),\n    );\n\n    const _slippage = new Percent(BN_ONE).add(slippage);\n    const slippageAdjustedAmount = _slippage.mul(amountRaw).quotient;\n\n    const _anotherAmount = new TokenAmount(_anotherToken, amountRaw);\n    const _maxAnotherAmount = new TokenAmount(_anotherToken, slippageAdjustedAmount);\n    this.logDebug(\"anotherAmount:\", _anotherAmount.toFixed(), \"maxAnotherAmount:\", _maxAnotherAmount.toFixed());\n\n    return {\n      anotherAmount: _anotherAmount,\n      maxAnotherAmount: _maxAnotherAmount,\n      liquidity,\n    };\n  }\n\n  public async addLiquidity<T extends TxVersion>(params: AddLiquidityParams<T>): Promise<MakeTxData<T>> {\n    const { poolInfo, amountInA: _amountInA, amountInB: _amountInB, fixedSide, config, txVersion } = params;\n\n    if (this.scope.availability.addStandardPosition === false)\n      this.logAndCreateError(\"add liquidity feature disabled in your region\");\n\n    const amountInA = this.scope.mintToTokenAmount({\n      mint: solToWSol(poolInfo.mintA.address),\n      amount: _amountInA.toString(),\n    });\n    const amountInB = this.scope.mintToTokenAmount({\n      mint: solToWSol(poolInfo.mintB.address),\n      amount: _amountInB.toString(),\n    });\n\n    this.logDebug(\"amountInA:\", amountInA, \"amountInB:\", amountInB);\n    if (amountInA.isZero() || amountInB.isZero())\n      this.logAndCreateError(\"amounts must greater than zero\", \"amountInA & amountInB\", {\n        amountInA: amountInA.toFixed(),\n        amountInB: amountInB.toFixed(),\n      });\n    const { account } = this.scope;\n    const { bypassAssociatedCheck, checkCreateATAOwner } = {\n      // default\n      ...{ bypassAssociatedCheck: false, checkCreateATAOwner: false },\n      // custom\n      ...config,\n    };\n    const [tokenA, tokenB] = [amountInA.token, amountInB.token];\n    const tokenAccountA = await account.getCreatedTokenAccount({\n      mint: tokenA.mint,\n      associatedOnly: false,\n    });\n    const tokenAccountB = await account.getCreatedTokenAccount({\n      mint: tokenB.mint,\n      associatedOnly: false,\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    const tokens = [tokenA, tokenB];\n    const _tokenAccounts = [tokenAccountA, tokenAccountB];\n    const rawAmounts = [amountInA.raw, amountInB.raw];\n\n    // handle amount a & b and direction\n    const sideA = amountInA.token.mint.toBase58() === poolInfo.mintA.address ? \"base\" : \"quote\";\n    let _fixedSide: AmountSide = \"base\";\n    if (![\"quote\", \"base\"].includes(sideA)) this.logAndCreateError(\"invalid fixedSide\", \"fixedSide\", fixedSide);\n    if (sideA === \"quote\") {\n      tokens.reverse();\n      _tokenAccounts.reverse();\n      rawAmounts.reverse();\n      _fixedSide = fixedSide === \"a\" ? \"quote\" : \"base\";\n    } else if (sideA === \"base\") {\n      _fixedSide = fixedSide === \"a\" ? \"base\" : \"quote\";\n    }\n\n    const [baseToken, quoteToken] = tokens;\n    const [baseTokenAccount, quoteTokenAccount] = _tokenAccounts;\n    const [baseAmountRaw, quoteAmountRaw] = rawAmounts;\n\n    const poolKeys = await this.scope.api.fetchPoolKeysById({ id: poolInfo.id });\n\n    const txBuilder = this.createTxBuilder();\n\n    const { tokenAccount: _baseTokenAccount, ...baseInstruction } = await account.handleTokenAccount({\n      side: \"in\",\n      amount: baseAmountRaw,\n      mint: baseToken.mint,\n      tokenAccount: baseTokenAccount,\n      bypassAssociatedCheck,\n      checkCreateATAOwner,\n    });\n    txBuilder.addInstruction(baseInstruction);\n    const { tokenAccount: _quoteTokenAccount, ...quoteInstruction } = await account.handleTokenAccount({\n      side: \"in\",\n      amount: quoteAmountRaw,\n      mint: quoteToken.mint,\n      tokenAccount: quoteTokenAccount,\n      bypassAssociatedCheck,\n      checkCreateATAOwner,\n    });\n    txBuilder.addInstruction(quoteInstruction);\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    txBuilder.addInstruction({\n      instructions: [\n        makeAddLiquidityInstruction({\n          poolInfo,\n          poolKeys: poolKeys as AmmV4Keys | AmmV5Keys,\n          userKeys: {\n            baseTokenAccount: _baseTokenAccount!,\n            quoteTokenAccount: _quoteTokenAccount!,\n            lpTokenAccount: _lpTokenAccount!,\n            owner: this.scope.ownerPubKey,\n          },\n          baseAmountIn: baseAmountRaw,\n          quoteAmountIn: quoteAmountRaw,\n          fixedSide: _fixedSide,\n        }),\n      ],\n      instructionTypes: [\n        poolInfo.pooltype.includes(\"StablePool\")\n          ? InstructionType.AmmV5AddLiquidity\n          : InstructionType.AmmV4AddLiquidity,\n      ],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    });\n    if (txVersion === TxVersion.V0) (await txBuilder.buildV0()) as MakeTxData<T>;\n    return txBuilder.build() as MakeTxData<T>;\n  }\n\n  public async removeLiquidity<T extends TxVersion>(params: RemoveParams<T>): Promise<Promise<MakeTxData<T>>> {\n    if (this.scope.availability.removeStandardPosition === false)\n      this.logAndCreateError(\"remove liquidity feature disabled in your region\");\n    const { poolInfo, amountIn, config, txVersion } = params;\n    const poolKeys = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as AmmV4Keys | AmmV5Keys;\n    const [baseMint, quoteMint, lpMint] = [\n      new PublicKey(poolInfo.mintA.address),\n      new PublicKey(poolInfo.mintB.address),\n      new PublicKey(poolInfo.lpMint.address),\n    ];\n    this.logDebug(\"amountIn:\", amountIn);\n    if (amountIn.isZero()) this.logAndCreateError(\"amount must greater than zero\", \"amountIn\", amountIn.toString());\n\n    const { account } = this.scope;\n    const lpTokenAccount = await account.getCreatedTokenAccount({\n      mint: lpMint,\n      associatedOnly: false,\n    });\n    if (!lpTokenAccount) this.logAndCreateError(\"cannot found lpTokenAccount\", \"tokenAccounts\", account.tokenAccounts);\n\n    const baseTokenAccount = await account.getCreatedTokenAccount({\n      mint: baseMint,\n    });\n    const quoteTokenAccount = await account.getCreatedTokenAccount({\n      mint: quoteMint,\n    });\n\n    const txBuilder = this.createTxBuilder();\n    const { bypassAssociatedCheck, checkCreateATAOwner } = {\n      // default\n      ...{ bypassAssociatedCheck: false, checkCreateATAOwner: false },\n      // custom\n      ...config,\n    };\n\n    const { tokenAccount: _baseTokenAccount, ...baseInstruction } = await account.handleTokenAccount({\n      side: \"out\",\n      amount: 0,\n      mint: baseMint,\n      tokenAccount: baseTokenAccount,\n      bypassAssociatedCheck,\n      checkCreateATAOwner,\n    });\n    txBuilder.addInstruction(baseInstruction);\n    const { tokenAccount: _quoteTokenAccount, ...quoteInstruction } = await account.handleTokenAccount({\n      side: \"out\",\n      amount: 0,\n      mint: quoteMint,\n      tokenAccount: quoteTokenAccount,\n      bypassAssociatedCheck,\n      checkCreateATAOwner,\n    });\n    txBuilder.addInstruction(quoteInstruction);\n\n    txBuilder.addInstruction({\n      instructions: [\n        removeLiquidityInstruction({\n          poolInfo,\n          poolKeys,\n          userKeys: {\n            lpTokenAccount: lpTokenAccount!,\n            baseTokenAccount: _baseTokenAccount!,\n            quoteTokenAccount: _quoteTokenAccount!,\n            owner: this.scope.ownerPubKey,\n          },\n          amountIn,\n        }),\n      ],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n      instructionTypes: [\n        poolInfo.pooltype.includes(\"StablePool\")\n          ? InstructionType.AmmV5RemoveLiquidity\n          : InstructionType.AmmV4RemoveLiquidity,\n      ],\n    });\n    if (txVersion === TxVersion.V0) return (await txBuilder.buildV0()) as MakeTxData<T>;\n    return txBuilder.build() as MakeTxData<T>;\n  }\n\n  public async removeAllLpAndCreateClmmPosition<T extends TxVersion>({\n    poolInfo,\n    clmmPoolInfo,\n    removeLpAmount,\n    createPositionInfo,\n    farmInfo,\n    userFarmLpAmount,\n    base,\n    computeBudgetConfig,\n    payer,\n    tokenProgram = TOKEN_PROGRAM_ID,\n    checkCreateATAOwner = true,\n    getEphemeralSigners,\n    txVersion,\n  }: {\n    poolInfo: ApiV3PoolInfoStandardItem;\n    clmmPoolInfo: ApiV3PoolInfoConcentratedItem;\n    removeLpAmount: BN;\n    createPositionInfo: {\n      tickLower: number;\n      tickUpper: number;\n      baseAmount: BN;\n      otherAmountMax: BN;\n    };\n    farmInfo?: FormatFarmInfoOutV6;\n    userFarmLpAmount?: BN;\n    base: \"MintA\" | \"MintB\";\n    payer?: PublicKey;\n    computeBudgetConfig?: ComputeBudgetConfig;\n    tokenProgram?: PublicKey;\n    checkCreateATAOwner?: boolean;\n    txVersion?: T;\n    getEphemeralSigners?: (k: number) => any;\n  }): Promise<MakeMultiTxData<T>> {\n    if (\n      this.scope.availability.removeStandardPosition === false ||\n      this.scope.availability.createConcentratedPosition === false\n    )\n      this.logAndCreateError(\"remove liquidity or create position feature disabled in your region\");\n\n    if (\n      !(poolInfo.mintA.address === clmmPoolInfo.mintA.address || poolInfo.mintA.address === clmmPoolInfo.mintB.address)\n    )\n      throw Error(\"mint check error\");\n    if (\n      !(poolInfo.mintB.address === clmmPoolInfo.mintA.address || poolInfo.mintB.address === clmmPoolInfo.mintB.address)\n    )\n      throw Error(\"mint check error\");\n\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    const mintToAccount: { [mint: string]: PublicKey } = {};\n    for (const item of this.scope.account.tokenAccountRawInfos) {\n      if (\n        mintToAccount[item.accountInfo.mint.toString()] === undefined ||\n        getATAAddress(this.scope.ownerPubKey, item.accountInfo.mint, TOKEN_PROGRAM_ID).publicKey.equals(item.pubkey)\n      ) {\n        mintToAccount[item.accountInfo.mint.toString()] = item.pubkey;\n      }\n    }\n\n    const lpTokenAccount = mintToAccount[poolInfo.lpMint.address];\n    if (lpTokenAccount === undefined) throw Error(\"find lp account error in trade accounts\");\n\n    const amountIn = removeLpAmount.add(userFarmLpAmount ?? new BN(0));\n    const mintBaseUseSOLBalance = poolInfo.mintA.address === Token.WSOL.mint.toString();\n    const mintQuoteUseSOLBalance = poolInfo.mintB.address === Token.WSOL.mint.toString();\n\n    const { account: baseTokenAccount, instructionParams: ownerTokenAccountBaseInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: TOKEN_PROGRAM_ID,\n        mint: new PublicKey(poolInfo.mintA.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo: mintBaseUseSOLBalance\n          ? {\n              payer: this.scope.ownerPubKey,\n            }\n          : undefined,\n        skipCloseAccount: !mintBaseUseSOLBalance,\n        notUseTokenAccount: mintBaseUseSOLBalance,\n        associatedOnly: true,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(ownerTokenAccountBaseInstruction || {});\n    if (baseTokenAccount === undefined) throw new Error(\"base token account not found\");\n\n    const { account: quoteTokenAccount, instructionParams: ownerTokenAccountQuoteInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: TOKEN_PROGRAM_ID,\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n        createInfo: mintQuoteUseSOLBalance\n          ? {\n              payer: this.scope.ownerPubKey!,\n              amount: 0,\n            }\n          : undefined,\n        skipCloseAccount: !mintQuoteUseSOLBalance,\n        notUseTokenAccount: mintQuoteUseSOLBalance,\n        associatedOnly: true,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(ownerTokenAccountQuoteInstruction || {});\n    if (quoteTokenAccount === undefined) throw new Error(\"quote token account not found\");\n\n    mintToAccount[poolInfo.mintA.address] = baseTokenAccount;\n    mintToAccount[poolInfo.mintB.address] = quoteTokenAccount;\n\n    if (farmInfo !== undefined && !userFarmLpAmount?.isZero()) {\n      const rewardTokenAccounts: PublicKey[] = [];\n      for (const item of farmInfo.rewardInfos) {\n        const rewardIsWsol = item.mint.address === Token.WSOL.mint.toString();\n        if (mintToAccount[item.mint.address]) rewardTokenAccounts.push(mintToAccount[item.mint.address]);\n        else {\n          const { account: farmRewardAccount, instructionParams: ownerTokenAccountFarmInstruction } =\n            await this.scope.account.getOrCreateTokenAccount({\n              mint: new PublicKey(item.mint.address),\n              tokenProgram,\n              owner: this.scope.ownerPubKey,\n              skipCloseAccount: !rewardIsWsol,\n              createInfo: {\n                payer: payer || this.scope.ownerPubKey,\n              },\n              associatedOnly: true,\n              checkCreateATAOwner,\n            });\n          if (!farmRewardAccount) this.logAndCreateError(\"farm reward account not found:\", item.mint.address);\n          ownerTokenAccountFarmInstruction && txBuilder.addInstruction(ownerTokenAccountFarmInstruction);\n          rewardTokenAccounts.push(farmRewardAccount!);\n        }\n      }\n      const farmKeys = (await this.scope.api.fetchFarmKeysById({ ids: farmInfo.id }))[0];\n      const insParams = {\n        amount: userFarmLpAmount!,\n        owner: this.scope.ownerPubKey,\n        farmInfo,\n        farmKeys,\n        lpAccount: lpTokenAccount,\n        rewardAccounts: rewardTokenAccounts,\n      };\n      const version = FARM_PROGRAM_TO_VERSION[farmInfo.programId];\n      const newInstruction =\n        version === 6\n          ? makeWithdrawInstructionV6(insParams)\n          : version === 5\n          ? makeWithdrawInstructionV5(insParams)\n          : makeWithdrawInstructionV3(insParams);\n      const insType = {\n        3: InstructionType.FarmV3Withdraw,\n        5: InstructionType.FarmV5Withdraw,\n        6: InstructionType.FarmV6Withdraw,\n      };\n      txBuilder.addInstruction({\n        instructions: [newInstruction],\n        instructionTypes: [insType[version]],\n      });\n    }\n\n    const poolKeys = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as AmmV4Keys | AmmV5Keys;\n\n    const removeIns = removeLiquidityInstruction({\n      poolInfo,\n      poolKeys,\n      userKeys: {\n        lpTokenAccount,\n        baseTokenAccount,\n        quoteTokenAccount,\n        owner: this.scope.ownerPubKey,\n      },\n      amountIn,\n    });\n\n    txBuilder.addInstruction({\n      instructions: [removeIns],\n      instructionTypes: [\n        !poolInfo.pooltype.includes(\"StablePool\")\n          ? InstructionType.AmmV4RemoveLiquidity\n          : InstructionType.AmmV5RemoveLiquidity,\n      ],\n      lookupTableAddress: poolKeys.lookupTableAccount ? [poolKeys.lookupTableAccount] : [],\n    });\n\n    const [tokenAccountA, tokenAccountB] =\n      poolInfo.mintA.address === clmmPoolInfo.mintA.address\n        ? [baseTokenAccount, quoteTokenAccount]\n        : [quoteTokenAccount, baseTokenAccount];\n\n    const clmmPoolKeys = (await this.scope.api.fetchPoolKeysById({ id: clmmPoolInfo.id })) as ClmmKeys;\n\n    const createPositionIns = await ClmmInstrument.openPositionFromBaseInstructions({\n      poolInfo: clmmPoolInfo,\n      poolKeys: clmmPoolKeys,\n      ownerInfo: {\n        feePayer: this.scope.ownerPubKey,\n        wallet: this.scope.ownerPubKey,\n        tokenAccountA,\n        tokenAccountB,\n      },\n      withMetadata: \"create\",\n      ...createPositionInfo,\n      base,\n      getEphemeralSigners,\n    });\n\n    txBuilder.addInstruction({\n      instructions: [...createPositionIns.instructions],\n      signers: createPositionIns.signers,\n      instructionTypes: [...createPositionIns.instructionTypes],\n      lookupTableAddress: clmmPoolKeys.lookupTableAccount ? [clmmPoolKeys.lookupTableAccount] : [],\n    });\n\n    if (txVersion === TxVersion.V0) return txBuilder.sizeCheckBuildV0() as Promise<MakeMultiTxData<T>>;\n    return txBuilder.sizeCheckBuild() as Promise<MakeMultiTxData<T>>;\n  }\n\n  // calComputeBudget\n  public async createPoolV4<T extends TxVersion>({\n    programId,\n    marketInfo,\n    baseMintInfo,\n    quoteMintInfo,\n    baseAmount,\n    quoteAmount,\n    startTime,\n    ownerInfo,\n    associatedOnly = false,\n    checkCreateATAOwner = false,\n    tokenProgram,\n    txVersion,\n    feeDestinationId,\n    computeBudgetConfig,\n  }: CreatePoolParam<T>): Promise<MakeTxData<T, { address: CreatePoolAddress }>> {\n    const payer = ownerInfo.feePayer || this.scope.owner?.publicKey;\n    const mintAUseSOLBalance = ownerInfo.useSOLBalance && baseMintInfo.mint.equals(NATIVE_MINT);\n    const mintBUseSOLBalance = ownerInfo.useSOLBalance && quoteMintInfo.mint.equals(NATIVE_MINT);\n\n    const txBuilder = this.createTxBuilder();\n\n    const { account: ownerTokenAccountBase, instructionParams: ownerTokenAccountBaseInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: baseMintInfo.mint,\n        owner: this.scope.ownerPubKey,\n        createInfo: mintAUseSOLBalance\n          ? {\n              payer: payer!,\n              amount: baseAmount,\n            }\n          : undefined,\n        notUseTokenAccount: mintAUseSOLBalance,\n        skipCloseAccount: !mintAUseSOLBalance,\n        associatedOnly: mintAUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(ownerTokenAccountBaseInstruction || {});\n\n    const { account: ownerTokenAccountQuote, instructionParams: ownerTokenAccountQuoteInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: quoteMintInfo.mint,\n        owner: this.scope.ownerPubKey,\n        createInfo: mintBUseSOLBalance\n          ? {\n              payer: payer!,\n              amount: quoteAmount,\n            }\n          : undefined,\n\n        notUseTokenAccount: mintBUseSOLBalance,\n        skipCloseAccount: !mintBUseSOLBalance,\n        associatedOnly: mintBUseSOLBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    txBuilder.addInstruction(ownerTokenAccountQuoteInstruction || {});\n\n    if (ownerTokenAccountBase === undefined || ownerTokenAccountQuote === undefined)\n      throw Error(\"you don't has some token account\");\n\n    const poolInfo = getAssociatedPoolKeys({\n      version: 4,\n      marketVersion: 3,\n      marketId: marketInfo.marketId,\n      baseMint: baseMintInfo.mint,\n      quoteMint: quoteMintInfo.mint,\n      baseDecimals: baseMintInfo.decimals,\n      quoteDecimals: quoteMintInfo.decimals,\n      programId,\n      marketProgramId: marketInfo.programId,\n    });\n\n    const createPoolKeys = {\n      programId,\n      ammId: poolInfo.id,\n      ammAuthority: poolInfo.authority,\n      ammOpenOrders: poolInfo.openOrders,\n      lpMint: poolInfo.lpMint,\n      coinMint: poolInfo.baseMint,\n      pcMint: poolInfo.quoteMint,\n      coinVault: poolInfo.baseVault,\n      pcVault: poolInfo.quoteVault,\n      withdrawQueue: poolInfo.withdrawQueue,\n      ammTargetOrders: poolInfo.targetOrders,\n      poolTempLp: poolInfo.lpVault,\n      marketProgramId: poolInfo.marketProgramId,\n      marketId: poolInfo.marketId,\n      ammConfigId: poolInfo.configId,\n      feeDestinationId,\n    };\n\n    const { instruction, instructionType } = createPoolV4InstructionV2({\n      ...createPoolKeys,\n      userWallet: this.scope.ownerPubKey,\n      userCoinVault: ownerTokenAccountBase,\n      userPcVault: ownerTokenAccountQuote,\n      userLpVault: getATAAddress(this.scope.ownerPubKey, poolInfo.lpMint, tokenProgram).publicKey,\n\n      nonce: poolInfo.nonce,\n      openTime: startTime,\n      coinAmount: baseAmount,\n      pcAmount: quoteAmount,\n    });\n\n    txBuilder.addInstruction({\n      instructions: [instruction],\n      instructionTypes: [instructionType],\n    });\n\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n\n    return txBuilder.versionBuild({\n      txVersion,\n      extInfo: {\n        address: createPoolKeys,\n      },\n    }) as Promise<MakeTxData<T, { address: CreatePoolAddress }>>;\n  }\n\n  public async getCreatePoolFee({ programId }: { programId: PublicKey }): Promise<BN> {\n    const configId = getAssociatedConfigId({ programId });\n\n    const account = await this.scope.connection.getAccountInfo(configId, { dataSlice: { offset: 536, length: 8 } });\n    if (account === null) throw Error(\"get config account error\");\n\n    return createPoolFeeLayout.decode(account.data).fee;\n  }\n}\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 } from \"@solana/spl-token\";\nimport { Token, TokenAmount } from \"@/module\";\nimport { BigNumberish } from \"@/common/bignumber\";\nimport { TokenInfo } from \"./type\";\nimport { SOL_INFO, TOKEN_WSOL } from \"./constant\";\n\nimport { ApiV3Token } from \"@/api\";\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  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: props.address,\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","import { TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { PublicKey, TransactionInstruction, SystemProgram, SYSVAR_RENT_PUBKEY } from \"@solana/web3.js\";\n\nimport { parseBigNumberish, BN_ZERO, BN_ONE } from \"@/common/bignumber\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { createLogger } from \"@/common/logger\";\nimport { accountMeta, RENT_PROGRAM_ID } from \"@/common/pubKey\";\nimport { AmmV4Keys, AmmV5Keys } from \"@/api/type\";\nimport { struct, u8, u64 } from \"@/marshmallow\";\n\nimport {\n  addLiquidityLayout,\n  removeLiquidityLayout,\n  fixedSwapInLayout,\n  fixedSwapOutLayout,\n  initPoolLayout,\n} from \"./layout\";\nimport { MODEL_DATA_PUBKEY } from \"./stable\";\nimport {\n  LiquidityAddInstructionParams,\n  RemoveLiquidityInstruction,\n  SwapFixedInInstructionParamsV4,\n  SwapFixedOutInstructionParamsV4,\n  SwapInstructionParams,\n  InitPoolInstructionParamsV4,\n} from \"./type\";\nimport { jsonInfo2PoolKeys } from \"@/common/utility\";\nimport { InstructionReturn } from \"../type\";\nimport BN from \"bn.js\";\n\nconst logger = createLogger(\"Raydium_liquidity_instruction\");\nexport function makeAddLiquidityInstruction(params: LiquidityAddInstructionParams): TransactionInstruction {\n  const { poolInfo, poolKeys, userKeys, baseAmountIn, quoteAmountIn, fixedSide } = params;\n\n  const data = Buffer.alloc(addLiquidityLayout.span);\n  addLiquidityLayout.encode(\n    {\n      instruction: 3,\n      baseAmountIn: parseBigNumberish(baseAmountIn),\n      quoteAmountIn: parseBigNumberish(quoteAmountIn),\n      fixedSide: fixedSide === \"base\" ? BN_ZERO : BN_ONE,\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    // amm\n    accountMeta({ pubkey: new PublicKey(poolInfo.id) }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.openOrders), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.targetOrders) }),\n    accountMeta({ pubkey: new PublicKey(poolInfo.lpMint.address) }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.A) }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.B) }),\n  ];\n\n  if (poolInfo.pooltype.includes(\"StablePool\")) {\n    keys.push(accountMeta({ pubkey: MODEL_DATA_PUBKEY }));\n  }\n\n  keys.push(\n    // serum\n    accountMeta({ pubkey: new PublicKey(poolInfo.marketId), isWritable: false }),\n    // user\n    accountMeta({ pubkey: userKeys.baseTokenAccount }),\n    accountMeta({ pubkey: userKeys.quoteTokenAccount }),\n    accountMeta({ pubkey: userKeys.lpTokenAccount }),\n    accountMeta({ pubkey: userKeys.owner, isWritable: false, isSigner: true }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.marketEventQueue), isWritable: false }),\n  );\n\n  return new TransactionInstruction({\n    programId: new PublicKey(poolInfo.programId),\n    keys,\n    data,\n  });\n}\n\nexport function removeLiquidityInstruction(params: RemoveLiquidityInstruction): TransactionInstruction {\n  const { poolInfo, poolKeys: poolKeyProps, userKeys, amountIn } = params;\n  const poolKeys = jsonInfo2PoolKeys(poolKeyProps);\n\n  let version = 4;\n  if (poolInfo.pooltype.includes(\"StablePool\")) version = 5;\n\n  if (version === 4 || version === 5) {\n    const data = Buffer.alloc(removeLiquidityLayout.span);\n    removeLiquidityLayout.encode(\n      {\n        instruction: 4,\n        amountIn: parseBigNumberish(amountIn),\n      },\n      data,\n    );\n\n    const keys = [\n      // system\n      accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n      // amm\n      accountMeta({ pubkey: poolKeys.id }),\n      accountMeta({ pubkey: poolKeys.authority, isWritable: false }),\n      accountMeta({ pubkey: poolKeys.openOrders }),\n      accountMeta({ pubkey: poolKeys.targetOrders }),\n      accountMeta({ pubkey: poolKeys.mintLp.address }),\n      accountMeta({ pubkey: poolKeys.vault.A }),\n      accountMeta({ pubkey: poolKeys.vault.B }),\n    ];\n\n    if (version === 5) {\n      keys.push(accountMeta({ pubkey: MODEL_DATA_PUBKEY }));\n    } else {\n      keys.push(accountMeta({ pubkey: poolKeys.withdrawQueue }));\n      keys.push(accountMeta({ pubkey: poolKeys.vault.Lp }));\n    }\n\n    keys.push(\n      // serum\n      accountMeta({ pubkey: poolKeys.marketProgramId, isWritable: false }),\n      accountMeta({ pubkey: poolKeys.marketId }),\n      accountMeta({ pubkey: poolKeys.marketBaseVault }),\n      accountMeta({ pubkey: poolKeys.marketQuoteVault }),\n      accountMeta({ pubkey: poolKeys.marketAuthority, isWritable: false }),\n      // user\n      accountMeta({ pubkey: userKeys.lpTokenAccount }),\n      accountMeta({ pubkey: userKeys.baseTokenAccount }),\n      accountMeta({ pubkey: userKeys.quoteTokenAccount }),\n      accountMeta({ pubkey: userKeys.owner, isWritable: false, isSigner: true }),\n      // serum orderbook\n      accountMeta({ pubkey: poolKeys.marketEventQueue }),\n      accountMeta({ pubkey: poolKeys.marketBids }),\n      accountMeta({ pubkey: poolKeys.marketAsks }),\n    );\n\n    return new TransactionInstruction({\n      programId: poolKeys.programId,\n      keys,\n      data,\n    });\n  }\n\n  // logger.logWithError(\"invalid version\", \"poolKeys.version\", version);\n  return new TransactionInstruction({ programId: poolKeys.programId, keys: [] }); // won't reach\n}\n\nexport function createPoolV4InstructionV2({\n  programId,\n  ammId,\n  ammAuthority,\n  ammOpenOrders,\n  lpMint,\n  coinMint,\n  pcMint,\n  coinVault,\n  pcVault,\n  withdrawQueue,\n  ammTargetOrders,\n  poolTempLp,\n  marketProgramId,\n  marketId,\n  userWallet,\n  userCoinVault,\n  userPcVault,\n  userLpVault,\n  nonce,\n  openTime,\n  coinAmount,\n  pcAmount,\n  ammConfigId,\n  feeDestinationId,\n}: {\n  programId: PublicKey;\n  ammId: PublicKey;\n  ammAuthority: PublicKey;\n  ammOpenOrders: PublicKey;\n  lpMint: PublicKey;\n  coinMint: PublicKey;\n  pcMint: PublicKey;\n  coinVault: PublicKey;\n  pcVault: PublicKey;\n  withdrawQueue: PublicKey;\n  ammTargetOrders: PublicKey;\n  poolTempLp: PublicKey;\n  marketProgramId: PublicKey;\n  marketId: PublicKey;\n  userWallet: PublicKey;\n  userCoinVault: PublicKey;\n  userPcVault: PublicKey;\n  userLpVault: PublicKey;\n  ammConfigId: PublicKey;\n  feeDestinationId: PublicKey;\n\n  nonce: number;\n  openTime: BN;\n  coinAmount: BN;\n  pcAmount: BN;\n}): InstructionReturn {\n  const dataLayout = struct([u8(\"instruction\"), u8(\"nonce\"), u64(\"openTime\"), u64(\"pcAmount\"), u64(\"coinAmount\")]);\n\n  const keys = [\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: ammId, isSigner: false, isWritable: true },\n    { pubkey: ammAuthority, isSigner: false, isWritable: false },\n    { pubkey: ammOpenOrders, isSigner: false, isWritable: true },\n    { pubkey: lpMint, isSigner: false, isWritable: true },\n    { pubkey: coinMint, isSigner: false, isWritable: false },\n    { pubkey: pcMint, isSigner: false, isWritable: false },\n    { pubkey: coinVault, isSigner: false, isWritable: true },\n    { pubkey: pcVault, isSigner: false, isWritable: true }, //12\n    { pubkey: ammTargetOrders, isSigner: false, isWritable: true }, //13\n    { pubkey: ammConfigId, isSigner: false, isWritable: false },\n    { pubkey: feeDestinationId, isSigner: false, isWritable: true },\n    { pubkey: marketProgramId, isSigner: false, isWritable: false },\n    { pubkey: marketId, isSigner: false, isWritable: false },\n    { pubkey: userWallet, isSigner: true, isWritable: true },\n    { pubkey: userCoinVault, isSigner: false, isWritable: true },\n    { pubkey: userPcVault, isSigner: false, isWritable: true },\n    { pubkey: userLpVault, isSigner: false, isWritable: true },\n  ];\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode({ instruction: 1, nonce, openTime, coinAmount, pcAmount }, data);\n\n  return {\n    instruction: new TransactionInstruction({\n      keys,\n      programId,\n      data,\n    }),\n    instructionType: InstructionType.AmmV4CreatePool,\n  };\n}\n\nexport function simulatePoolInfoInstruction(poolKeys: AmmV4Keys | AmmV5Keys): TransactionInstruction {\n  const simulatePoolLayout = struct([u8(\"instruction\"), u8(\"simulateType\")]);\n  const data = Buffer.alloc(simulatePoolLayout.span);\n  simulatePoolLayout.encode(\n    {\n      instruction: 12,\n      simulateType: 0,\n    },\n    data,\n  );\n\n  const keys = [\n    // amm\n    accountMeta({ pubkey: new PublicKey(poolKeys.id), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.openOrders), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.A), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.B), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.mintLp.address), isWritable: false }),\n    // serum\n    accountMeta({ pubkey: new PublicKey(poolKeys.marketId), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.marketEventQueue), isWritable: false }),\n  ];\n\n  return new TransactionInstruction({\n    programId: new PublicKey(poolKeys.programId),\n    keys,\n    data,\n  });\n}\n\nexport function makeSwapFixedInInstruction(\n  { poolKeys: propPoolKeys, userKeys, amountIn, minAmountOut }: SwapFixedInInstructionParamsV4,\n  version: number,\n): TransactionInstruction {\n  const poolKeys = jsonInfo2PoolKeys(propPoolKeys);\n  const data = Buffer.alloc(fixedSwapInLayout.span);\n  fixedSwapInLayout.encode(\n    {\n      instruction: 9,\n      amountIn: parseBigNumberish(amountIn),\n      minAmountOut: parseBigNumberish(minAmountOut),\n    },\n    data,\n  );\n  const keys = [\n    // amm\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.id }),\n    accountMeta({ pubkey: poolKeys.authority, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.openOrders }),\n  ];\n\n  if (version === 4) keys.push(accountMeta({ pubkey: poolKeys.targetOrders }));\n  keys.push(accountMeta({ pubkey: poolKeys.vault.A }), accountMeta({ pubkey: poolKeys.vault.B }));\n  if (version === 5) keys.push(accountMeta({ pubkey: MODEL_DATA_PUBKEY }));\n  keys.push(\n    // serum\n    accountMeta({ pubkey: poolKeys.marketProgramId, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.marketId }),\n    accountMeta({ pubkey: poolKeys.marketBids }),\n    accountMeta({ pubkey: poolKeys.marketAsks }),\n    accountMeta({ pubkey: poolKeys.marketEventQueue }),\n    accountMeta({ pubkey: poolKeys.marketBaseVault }),\n    accountMeta({ pubkey: poolKeys.marketQuoteVault }),\n    accountMeta({ pubkey: poolKeys.marketAuthority, isWritable: false }),\n    // user\n    accountMeta({ pubkey: userKeys.tokenAccountIn }),\n    accountMeta({ pubkey: userKeys.tokenAccountOut }),\n    accountMeta({ pubkey: userKeys.owner, isWritable: false }),\n  );\n\n  return new TransactionInstruction({\n    programId: poolKeys.programId,\n    keys,\n    data,\n  });\n}\n\nexport function makeSwapFixedOutInstruction(\n  { poolKeys: propPoolKeys, userKeys, maxAmountIn, amountOut }: SwapFixedOutInstructionParamsV4,\n  version: number,\n): TransactionInstruction {\n  const poolKeys = jsonInfo2PoolKeys(propPoolKeys);\n  const data = Buffer.alloc(fixedSwapOutLayout.span);\n  fixedSwapOutLayout.encode(\n    {\n      instruction: 11,\n      maxAmountIn: parseBigNumberish(maxAmountIn),\n      amountOut: parseBigNumberish(amountOut),\n    },\n    data,\n  );\n\n  const keys = [\n    accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n    // amm\n    accountMeta({ pubkey: poolKeys.id }),\n    accountMeta({ pubkey: poolKeys.authority, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.openOrders }),\n    accountMeta({ pubkey: poolKeys.targetOrders }),\n    accountMeta({ pubkey: poolKeys.vault.A }),\n    accountMeta({ pubkey: poolKeys.vault.B }),\n  ];\n\n  if (version === 5) keys.push(accountMeta({ pubkey: MODEL_DATA_PUBKEY }));\n\n  keys.push(\n    // serum\n    accountMeta({ pubkey: poolKeys.marketProgramId, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.marketId }),\n    accountMeta({ pubkey: poolKeys.marketBids }),\n    accountMeta({ pubkey: poolKeys.marketAsks }),\n    accountMeta({ pubkey: poolKeys.marketEventQueue }),\n    accountMeta({ pubkey: poolKeys.marketBaseVault }),\n    accountMeta({ pubkey: poolKeys.marketQuoteVault }),\n    accountMeta({ pubkey: poolKeys.marketAuthority, isWritable: false }),\n    accountMeta({ pubkey: userKeys.tokenAccountIn }),\n    accountMeta({ pubkey: userKeys.tokenAccountOut }),\n    accountMeta({ pubkey: userKeys.owner, isWritable: false, isSigner: true }),\n  );\n\n  return new TransactionInstruction({\n    programId: poolKeys.programId,\n    keys,\n    data,\n  });\n}\n\nexport function makeAMMSwapInstruction(params: SwapInstructionParams): TransactionInstruction {\n  const { poolKeys, version, userKeys, amountIn, amountOut, fixedSide } = params;\n  if (version === 4 || version === 5) {\n    const props = { poolKeys, userKeys };\n    if (fixedSide === \"in\") {\n      return makeSwapFixedInInstruction(\n        {\n          ...props,\n          amountIn,\n          minAmountOut: amountOut,\n        },\n        version,\n      );\n    } else if (fixedSide === \"out\") {\n      return makeSwapFixedOutInstruction(\n        {\n          ...props,\n          maxAmountIn: amountIn,\n          amountOut,\n        },\n        version,\n      );\n    }\n    logger.logWithError(\"invalid params\", \"params\", params);\n  }\n\n  logger.logWithError(\"invalid version\", \"poolKeys.version\", version);\n  throw new Error(\"invalid version\");\n}\n\nexport function makeInitPoolInstructionV4({\n  poolKeys: propPoolKeys,\n  userKeys,\n  startTime,\n}: InitPoolInstructionParamsV4): TransactionInstruction {\n  const data = Buffer.alloc(initPoolLayout.span);\n  initPoolLayout.encode(\n    {\n      instruction: 0,\n      // nonce: poolKeys.nonce, // to do fix\n      nonce: 5,\n      startTime: parseBigNumberish(startTime),\n    },\n    data,\n  );\n  const poolKeys = jsonInfo2PoolKeys(propPoolKeys);\n\n  const keys = [\n    // system\n    accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n    accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n    accountMeta({ pubkey: SYSVAR_RENT_PUBKEY, isWritable: false }),\n    // amm\n    accountMeta({ pubkey: poolKeys.id }),\n    accountMeta({ pubkey: poolKeys.authority, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.openOrders }),\n    accountMeta({ pubkey: poolKeys.mintLp.address }),\n    accountMeta({ pubkey: poolKeys.mintA.address, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.mintB.address, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.vault.A, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.vault.B, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.withdrawQueue }),\n    accountMeta({ pubkey: poolKeys.targetOrders }),\n    accountMeta({ pubkey: userKeys.lpTokenAccount }),\n    accountMeta({ pubkey: poolKeys.vault.Lp, isWritable: false }),\n    // serum\n    accountMeta({ pubkey: poolKeys.marketProgramId, isWritable: false }),\n    accountMeta({ pubkey: poolKeys.marketId, isWritable: false }),\n    // user\n    accountMeta({ pubkey: userKeys.payer, isSigner: true }),\n  ];\n\n  return new TransactionInstruction({\n    programId: poolKeys.programId,\n    keys,\n    data,\n  });\n}\n\nexport function makeSimulatePoolInfoInstruction({ poolKeys }: { poolKeys: AmmV4Keys | AmmV5Keys }): {\n  instruction: TransactionInstruction;\n} {\n  const LAYOUT = struct([u8(\"instruction\"), u8(\"simulateType\")]);\n  const data = Buffer.alloc(LAYOUT.span);\n  LAYOUT.encode(\n    {\n      instruction: 12,\n      simulateType: 0,\n    },\n    data,\n  );\n\n  const keys = [\n    // amm\n    accountMeta({ pubkey: new PublicKey(poolKeys.id), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.authority), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.openOrders), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.A), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.vault.B), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.mintLp.address), isWritable: false }),\n    // serum\n    accountMeta({ pubkey: new PublicKey(poolKeys.marketId), isWritable: false }),\n    accountMeta({ pubkey: new PublicKey(poolKeys.marketEventQueue), isWritable: false }),\n  ];\n\n  return {\n    instruction: new TransactionInstruction({\n      programId: new PublicKey(poolKeys.programId),\n      keys,\n      data,\n    }),\n  };\n}\n","import { GetStructureSchema, publicKey, seq, struct, u128, u64, u8 } from \"@/marshmallow\";\n\nexport const fixedSwapInLayout = struct([u8(\"instruction\"), u64(\"amountIn\"), u64(\"minAmountOut\")]);\nexport const fixedSwapOutLayout = struct([u8(\"instruction\"), u64(\"maxAmountIn\"), u64(\"amountOut\")]);\n\nexport const createPoolV4Layout = struct([u8(\"instruction\"), u8(\"nonce\")]);\nexport const initPoolLayout = struct([u8(\"instruction\"), u8(\"nonce\"), u64(\"startTime\")]);\n/* ================= state layouts ================= */\nexport const liquidityStateV4Layout = struct([\n  u64(\"status\"),\n  u64(\"nonce\"),\n  u64(\"maxOrder\"),\n  u64(\"depth\"),\n  u64(\"baseDecimal\"),\n  u64(\"quoteDecimal\"),\n  u64(\"state\"),\n  u64(\"resetFlag\"),\n  u64(\"minSize\"),\n  u64(\"volMaxCutRatio\"),\n  u64(\"amountWaveRatio\"),\n  u64(\"baseLotSize\"),\n  u64(\"quoteLotSize\"),\n  u64(\"minPriceMultiplier\"),\n  u64(\"maxPriceMultiplier\"),\n  u64(\"systemDecimalValue\"),\n  u64(\"minSeparateNumerator\"),\n  u64(\"minSeparateDenominator\"),\n  u64(\"tradeFeeNumerator\"),\n  u64(\"tradeFeeDenominator\"),\n  u64(\"pnlNumerator\"),\n  u64(\"pnlDenominator\"),\n  u64(\"swapFeeNumerator\"),\n  u64(\"swapFeeDenominator\"),\n  u64(\"baseNeedTakePnl\"),\n  u64(\"quoteNeedTakePnl\"),\n  u64(\"quoteTotalPnl\"),\n  u64(\"baseTotalPnl\"),\n  u64(\"poolOpenTime\"),\n  u64(\"punishPcAmount\"),\n  u64(\"punishCoinAmount\"),\n  u64(\"orderbookToInitTime\"),\n  // u128('poolTotalDepositPc'),\n  // u128('poolTotalDepositCoin'),\n  u128(\"swapBaseInAmount\"),\n  u128(\"swapQuoteOutAmount\"),\n  u64(\"swapBase2QuoteFee\"),\n  u128(\"swapQuoteInAmount\"),\n  u128(\"swapBaseOutAmount\"),\n  u64(\"swapQuote2BaseFee\"),\n  // amm vault\n  publicKey(\"baseVault\"),\n  publicKey(\"quoteVault\"),\n  // mint\n  publicKey(\"baseMint\"),\n  publicKey(\"quoteMint\"),\n  publicKey(\"lpMint\"),\n  // market\n  publicKey(\"openOrders\"),\n  publicKey(\"marketId\"),\n  publicKey(\"marketProgramId\"),\n  publicKey(\"targetOrders\"),\n  publicKey(\"withdrawQueue\"),\n  publicKey(\"lpVault\"),\n  publicKey(\"owner\"),\n  // true circulating supply without lock up\n  u64(\"lpReserve\"),\n  seq(u64(), 3, \"padding\"),\n]);\n\nexport type LiquidityStateLayoutV4 = typeof liquidityStateV4Layout;\nexport type LiquidityStateV4 = GetStructureSchema<LiquidityStateLayoutV4>;\n\nexport const liquidityStateV5Layout = struct([\n  u64(\"accountType\"),\n  u64(\"status\"),\n  u64(\"nonce\"),\n  u64(\"maxOrder\"),\n  u64(\"depth\"),\n  u64(\"baseDecimal\"),\n  u64(\"quoteDecimal\"),\n  u64(\"state\"),\n  u64(\"resetFlag\"),\n  u64(\"minSize\"),\n  u64(\"volMaxCutRatio\"),\n  u64(\"amountWaveRatio\"),\n  u64(\"baseLotSize\"),\n  u64(\"quoteLotSize\"),\n  u64(\"minPriceMultiplier\"),\n  u64(\"maxPriceMultiplier\"),\n  u64(\"systemDecimalsValue\"),\n  u64(\"abortTradeFactor\"),\n  u64(\"priceTickMultiplier\"),\n  u64(\"priceTick\"),\n  // Fees\n  u64(\"minSeparateNumerator\"),\n  u64(\"minSeparateDenominator\"),\n  u64(\"tradeFeeNumerator\"),\n  u64(\"tradeFeeDenominator\"),\n  u64(\"pnlNumerator\"),\n  u64(\"pnlDenominator\"),\n  u64(\"swapFeeNumerator\"),\n  u64(\"swapFeeDenominator\"),\n  // OutPutData\n  u64(\"baseNeedTakePnl\"),\n  u64(\"quoteNeedTakePnl\"),\n  u64(\"quoteTotalPnl\"),\n  u64(\"baseTotalPnl\"),\n  u64(\"poolOpenTime\"),\n  u64(\"punishPcAmount\"),\n  u64(\"punishCoinAmount\"),\n  u64(\"orderbookToInitTime\"),\n  u128(\"swapBaseInAmount\"),\n  u128(\"swapQuoteOutAmount\"),\n  u128(\"swapQuoteInAmount\"),\n  u128(\"swapBaseOutAmount\"),\n  u64(\"swapQuote2BaseFee\"),\n  u64(\"swapBase2QuoteFee\"),\n\n  publicKey(\"baseVault\"),\n  publicKey(\"quoteVault\"),\n  publicKey(\"baseMint\"),\n  publicKey(\"quoteMint\"),\n  publicKey(\"lpMint\"),\n\n  publicKey(\"modelDataAccount\"),\n  publicKey(\"openOrders\"),\n  publicKey(\"marketId\"),\n  publicKey(\"marketProgramId\"),\n  publicKey(\"targetOrders\"),\n  publicKey(\"owner\"),\n  seq(u64(), 64, \"padding\"),\n]);\n\nexport const addLiquidityLayout = struct([\n  u8(\"instruction\"),\n  u64(\"baseAmountIn\"),\n  u64(\"quoteAmountIn\"),\n  u64(\"fixedSide\"),\n]);\n\nexport const removeLiquidityLayout = struct([u8(\"instruction\"), u64(\"amountIn\")]);\n\nexport type LiquidityStateLayoutV5 = typeof liquidityStateV5Layout;\nexport type LiquidityStateV5 = GetStructureSchema<LiquidityStateLayoutV5>;\n\nexport type LiquidityState = LiquidityStateV4 | LiquidityStateV5;\nexport type LiquidityStateLayout = LiquidityStateLayoutV4 | LiquidityStateLayoutV5;\n\n/* ================= index ================= */\n// version => liquidity state layout\nexport const LIQUIDITY_VERSION_TO_STATE_LAYOUT: {\n  [version: number]: LiquidityStateLayout;\n} = {\n  4: liquidityStateV4Layout,\n  5: liquidityStateV5Layout,\n};\n\nexport const createPoolFeeLayout = struct([u64(\"fee\")]);\n","import { Connection, PublicKey } from \"@solana/web3.js\";\n\nimport { seq, struct, u64 } from \"@/marshmallow\";\n\nexport const MODEL_DATA_PUBKEY = new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\");\nconst ELEMENT_SIZE = 50000;\n\nexport const DataElement = struct([u64(\"x\"), u64(\"y\"), u64(\"price\")]);\n\nexport const modelDataInfoLayout = struct([\n  u64(\"accountType\"),\n  u64(\"status\"),\n  u64(\"multiplier\"),\n  u64(\"validDataCount\"),\n  seq(DataElement, ELEMENT_SIZE, \"DataElement\"),\n]);\n\nexport interface StableModelLayout {\n  accountType: number;\n  status: number;\n  multiplier: number;\n  validDataCount: number;\n  DataElement: { x: number; y: number; price: number }[];\n}\n\nfunction estimateRangeByXyReal(_xReal: number, _yReal: number): number[] {\n  return [0, ELEMENT_SIZE - 2];\n}\n\nfunction estimateRangeByX(_x: number): number[] {\n  return [0, ELEMENT_SIZE - 2];\n}\n\nfunction estimateRangeByY(_y: number): number[] {\n  return [0, ELEMENT_SIZE - 2];\n}\n\nfunction getMininumRangeByXyReal(\n  layoutData: StableModelLayout,\n  xReal: number,\n  yReal: number,\n): [number, number, boolean] {\n  const [min, max] = estimateRangeByXyReal(xReal, yReal);\n  let minRangeIdx = min;\n  let maxRangeIdx = max;\n  let mid = 0;\n  const target = (xReal * layoutData.multiplier) / yReal;\n  while (minRangeIdx <= maxRangeIdx) {\n    mid = Math.floor((maxRangeIdx + minRangeIdx) / 2);\n    if (mid === 0 || mid >= ELEMENT_SIZE - 2) {\n      return [mid, mid, false];\n    }\n    const cur = (layoutData.DataElement[mid].x * layoutData.multiplier) / layoutData.DataElement[mid].y;\n    const left = (layoutData.DataElement[mid - 1].x * layoutData.multiplier) / layoutData.DataElement[mid - 1].y;\n    const right = (layoutData.DataElement[mid + 1].x * layoutData.multiplier) / layoutData.DataElement[mid + 1].y;\n\n    if (target === cur) {\n      return [mid, mid, true];\n    } else if (target === left) {\n      return [mid - 1, mid - 1, true];\n    } else if (target === right) {\n      return [mid + 1, mid + 1, true];\n    } else if (target < left) {\n      maxRangeIdx = mid - 1;\n    } else if (target > left && target < cur) {\n      return [mid - 1, mid, true];\n    } else if (target > cur && target < right) {\n      return [mid, mid + 1, true];\n    } else {\n      minRangeIdx = mid + 1;\n    }\n  }\n  return [mid, mid, false];\n}\nfunction getRatio(layoutData: StableModelLayout, xReal: number, yReal: number): number {\n  const [minRangeIdx, maxRangeIdx, find] = getMininumRangeByXyReal(layoutData, xReal, yReal);\n\n  if (!find) {\n    return 0;\n  }\n\n  if (minRangeIdx === maxRangeIdx) {\n    const x = layoutData.DataElement[minRangeIdx].x;\n    const ratio = (xReal * layoutData.multiplier) / x;\n    return ratio;\n  } else {\n    const x1 = layoutData.DataElement[minRangeIdx].x;\n    const y1 = layoutData.DataElement[minRangeIdx].y;\n    const x2 = layoutData.DataElement[maxRangeIdx].x;\n    const y2 = layoutData.DataElement[maxRangeIdx].y;\n\n    const xDenominator = yReal * (x2 * y1 - x1 * y2);\n    const xNumerator1 = x1 * xDenominator;\n    const xNumerator2 = (x2 - x1) * (xReal * y1 - x1 * yReal) * y2;\n\n    const xNumerator = xNumerator1 + xNumerator2;\n    const ratio = (xReal * layoutData.multiplier * xDenominator) / xNumerator;\n    return ratio;\n  }\n}\n\nfunction realToTable(layoutData: StableModelLayout, realValue: number, ratio: number): number {\n  return (realValue * layoutData.multiplier) / ratio;\n}\n\nfunction tableToReal(layoutData: StableModelLayout, tableValue: number, ratio: number): number {\n  return (tableValue * ratio) / layoutData.multiplier;\n}\n\nfunction getMinimumRangeByX(layoutData: StableModelLayout, x: number): [number, number, boolean] {\n  const [min, max] = estimateRangeByX(x);\n  let minRangeIdx = min;\n  let maxRangeIdx = max;\n  let mid = 0;\n  const target = x;\n  while (minRangeIdx < maxRangeIdx) {\n    mid = Math.floor((maxRangeIdx + minRangeIdx) / 2);\n\n    if (mid <= 0 || mid > ELEMENT_SIZE - 2) {\n      return [mid, mid, false];\n    }\n    const cur = layoutData.DataElement[mid].x;\n    const left = layoutData.DataElement[mid - 1].x;\n    const right = layoutData.DataElement[mid + 1].x;\n\n    if (target === cur) return [mid, mid, true];\n    else if (target === left) return [mid - 1, mid - 1, true];\n    else if (target === right) return [mid + 1, mid + 1, true];\n    else if (target < left) maxRangeIdx = mid - 1;\n    else if (target > left && target < cur) return [mid - 1, mid, true];\n    else if (target > cur && target < right) return [mid, mid + 1, true];\n    else minRangeIdx = mid + 1;\n  }\n  return [mid, mid, false];\n}\n\nfunction getMinimumRangeByY(layoutData: StableModelLayout, y: number): [number, number, boolean] {\n  const [min, max] = estimateRangeByY(y);\n  let minRangeIdx = min;\n  let maxRangeIdx = max;\n  let mid = 0;\n  const target = y;\n  while (minRangeIdx <= maxRangeIdx) {\n    mid = Math.floor((maxRangeIdx + minRangeIdx) / 2);\n    if (mid <= 0 || mid >= ELEMENT_SIZE - 2) {\n      return [mid, mid, false];\n    }\n\n    const cur = layoutData.DataElement[mid].y;\n    const left = layoutData.DataElement[mid - 1].y;\n    const right = layoutData.DataElement[mid + 1].y;\n    if (target === cur) return [mid, mid, true];\n    else if (target === left) return [mid - 1, mid - 1, true];\n    else if (target === right) return [mid + 1, mid + 1, true];\n    else if (target < right) {\n      minRangeIdx = mid + 1;\n    } else if (target < left && target > cur) return [mid - 1, mid, true];\n    else if (target < cur && target > right) return [mid, mid + 1, true];\n    else maxRangeIdx = mid - 1;\n  }\n  return [mid, mid, false];\n}\n\nfunction getDataByX(\n  layoutData: StableModelLayout,\n  x: number,\n  dx: number,\n  priceUp: boolean,\n): [number, number, boolean, boolean] {\n  const xWithDx = priceUp ? x + dx : x - dx;\n  const [minIdx, maxIdx, find] = getMinimumRangeByX(layoutData, xWithDx);\n  if (!find) return [0, 0, false, find];\n\n  if (minIdx === maxIdx) return [layoutData.DataElement[maxIdx].price, layoutData.DataElement[maxIdx].y, false, find];\n  else {\n    const x1 = layoutData.DataElement[minIdx].x;\n    const x2 = layoutData.DataElement[maxIdx].x;\n    const p1 = layoutData.DataElement[minIdx].price;\n    const p2 = layoutData.DataElement[maxIdx].price;\n    const y1 = layoutData.DataElement[minIdx].y;\n    const y2 = layoutData.DataElement[maxIdx].y;\n\n    if (x >= x1 && x <= x2) {\n      if (priceUp) return [p2, y2, true, find];\n      else return [p1, y1, true, find];\n    } else {\n      let p, y;\n      if (priceUp) {\n        p = p1 + ((p2 - p1) * (x - x1)) / (x2 - x1);\n        y = y1 - ((xWithDx - x1) * layoutData.multiplier) / p2;\n      } else {\n        p = p1 + ((p2 - p1) * (x - x1)) / (x2 - x1);\n        y = y2 + ((x2 - xWithDx) * layoutData.multiplier) / p1;\n      }\n      return [p, y, false, find];\n    }\n  }\n}\n\nfunction getDataByY(\n  layoutData: StableModelLayout,\n  y: number,\n  dy: number,\n  priceUp: boolean,\n): [number, number, boolean, boolean] {\n  const yWithDy = priceUp ? y - dy : y + dy;\n  const [minIdx, maxIdx, find] = getMinimumRangeByY(layoutData, yWithDy);\n  if (!find) return [0, 0, false, find];\n  if (minIdx === maxIdx) return [layoutData.DataElement[maxIdx].price, layoutData.DataElement[maxIdx].x, false, find];\n  else {\n    const x1 = layoutData.DataElement[minIdx].x;\n    const x2 = layoutData.DataElement[maxIdx].x;\n    const p1 = layoutData.DataElement[minIdx].price;\n    const p2 = layoutData.DataElement[maxIdx].price;\n    const y1 = layoutData.DataElement[minIdx].y;\n    const y2 = layoutData.DataElement[maxIdx].y;\n\n    if (y >= y2 && y <= y1) {\n      return priceUp ? [p2, x2, true, find] : [p1, x1, true, find];\n    } else {\n      let p, x;\n      if (priceUp) {\n        p = p1 + ((p2 - p1) * (y1 - y)) / (y1 - y2);\n        x = x1 + (p2 * (y1 - yWithDy)) / layoutData.multiplier;\n      } else {\n        p = p1 + ((p2 - p1) * (y1 - y)) / (y1 - y2);\n        x = x2 - (p1 * (yWithDy - y2)) / layoutData.multiplier;\n      }\n      return [p, x, false, find];\n    }\n  }\n}\n\nfunction getMidPrice(layoutData: StableModelLayout, x: number): number {\n  const ret = getDataByX(layoutData, x, 0, false);\n  if (ret[3]) return ret[0];\n  else return 0;\n}\n\nexport function getDyByDxBaseIn(layoutData: StableModelLayout, xReal: number, yReal: number, dxReal: number): number {\n  const ratio = getRatio(layoutData, xReal, yReal);\n  const x = realToTable(layoutData, xReal, ratio);\n  const y = realToTable(layoutData, yReal, ratio);\n  const dx = realToTable(layoutData, dxReal, ratio);\n  const priceUp = true;\n  const [p, y2, lessTrade, find] = getDataByX(layoutData, x, dx, priceUp);\n  if (!find) return 0;\n  if (lessTrade) {\n    const dyReal = (dxReal * layoutData.multiplier) / p;\n    return dyReal;\n  } else {\n    const dy = y - y2;\n    const dyReal = tableToReal(layoutData, dy, ratio);\n    return dyReal;\n  }\n}\n\nexport function getDxByDyBaseIn(layoutData: StableModelLayout, xReal: number, yReal: number, dyReal: number): number {\n  const ratio = getRatio(layoutData, xReal, yReal);\n  const x = realToTable(layoutData, xReal, ratio);\n  const y = realToTable(layoutData, yReal, ratio);\n  const dy = realToTable(layoutData, dyReal, ratio);\n  const priceUp = false;\n  const [p, x2, lessTrade, find] = getDataByY(layoutData, y, dy, priceUp);\n  if (!find) return 0;\n  if (lessTrade) {\n    const dxReal = (dyReal * p) / layoutData.multiplier;\n    return dxReal;\n  } else {\n    const dx = x - x2;\n    const dxReal = tableToReal(layoutData, dx, ratio);\n    return dxReal;\n  }\n}\n\nexport function formatLayout(buffer: Buffer): StableModelLayout {\n  const layoutInfo = modelDataInfoLayout.decode(buffer);\n  return {\n    accountType: layoutInfo.accountType.toNumber(),\n    status: layoutInfo.status.toNumber(),\n    multiplier: layoutInfo.multiplier.toNumber(),\n    validDataCount: layoutInfo.validDataCount.toNumber(),\n    DataElement: layoutInfo.DataElement.map((item: any) => ({\n      x: item.x.toNumber(),\n      y: item.y.toNumber(),\n      price: item.price.toNumber(),\n    })),\n  };\n}\n\nexport function getStablePrice(\n  layoutData: StableModelLayout,\n  coinReal: number,\n  pcReal: number,\n  baseCoin: boolean,\n): number {\n  const price =\n    getMidPrice(layoutData, realToTable(layoutData, coinReal, getRatio(layoutData, coinReal, pcReal))) /\n    layoutData.multiplier;\n  return baseCoin ? price : 1 / price;\n}\n\nexport class StableLayout {\n  private readonly connection: Connection;\n  private _layoutData: StableModelLayout = {\n    accountType: 0,\n    status: 0,\n    multiplier: 0,\n    validDataCount: 0,\n    DataElement: [],\n  };\n\n  constructor({ connection }: { connection: Connection }) {\n    this.connection = connection;\n  }\n\n  get stableModelData(): StableModelLayout {\n    return this._layoutData;\n  }\n\n  public async initStableModelLayout(): Promise<void> {\n    if (this._layoutData.validDataCount === 0) {\n      if (this.connection) {\n        const acc = await this.connection.getAccountInfo(MODEL_DATA_PUBKEY);\n        if (acc) this._layoutData = formatLayout(acc?.data);\n      }\n    }\n  }\n}\n","import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport {\n  PublicKey,\n  TransactionInstruction,\n  ComputeBudgetProgram,\n  SystemProgram,\n  Connection,\n  Keypair,\n  Signer,\n} from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport {\n  createLogger,\n  parseBigNumberish,\n  RENT_PROGRAM_ID,\n  METADATA_PROGRAM_ID,\n  InstructionType,\n  getATAAddress,\n  MEMO_PROGRAM_ID,\n} from \"@/common\";\nimport { bool, s32, struct, u128, u64, u8 } from \"@/marshmallow\";\nimport {\n  ReturnTypeMakeInstructions,\n  ClmmPoolPersonalPosition,\n  OpenPositionFromLiquidityExtInfo,\n  ManipulateLiquidityExtInfo,\n  ClosePositionExtInfo,\n  InitRewardExtInfo,\n  OpenPositionFromBaseExtInfo,\n} from \"./type\";\nimport { ClmmPositionLayout, ObservationInfoLayout } from \"./layout\";\nimport {\n  getPdaPoolId,\n  getPdaPoolVaultId,\n  getPdaTickArrayAddress,\n  getPdaMetadataKey,\n  getPdaProtocolPositionAddress,\n  getPdaPersonalPositionAddress,\n  getPdaOperationAccount,\n  getPdaExBitmapAccount,\n  getPdaPoolRewardVaulId,\n} from \"./utils/pda\";\nimport { TickUtils } from \"./utils/tick\";\nimport { PoolUtils } from \"./utils/pool\";\nimport { generatePubKey } from \"../account/util\";\nimport { ApiV3Token, ApiV3PoolInfoConcentratedItem, ClmmKeys } from \"@/api/type\";\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  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\ninterface CreatePoolInstruction {\n  connection: Connection;\n  programId: PublicKey;\n  owner: PublicKey;\n  mintA: ApiV3Token;\n  mintB: ApiV3Token;\n  ammConfigId: PublicKey;\n  initialPriceX64: BN;\n  startTime: BN;\n  forerunCreate?: boolean;\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    startTime: BN,\n  ): TransactionInstruction {\n    const dataLayout = struct([u128(\"sqrtPriceX64\"), u64(\"startTime\")]);\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: false },\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    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode(\n      {\n        sqrtPriceX64,\n        startTime,\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      mintAVault: PublicKey;\n      mintBVault: PublicKey;\n    }>\n  > {\n    const { connection, programId, owner, mintA, mintB, ammConfigId, initialPriceX64, startTime, forerunCreate } =\n      props;\n    const observationId = generatePubKey({ fromPublicKey: owner, programId });\n    const [mintAAddress, mintBAddress] = [new PublicKey(mintA.address), new PublicKey(mintB.address)];\n    const ins = [\n      SystemProgram.createAccountWithSeed({\n        fromPubkey: owner,\n        basePubkey: owner,\n        seed: observationId.seed,\n        newAccountPubkey: observationId.publicKey,\n        lamports: forerunCreate ? 0 : await connection.getMinimumBalanceForRentExemption(ObservationInfoLayout.span),\n        space: ObservationInfoLayout.span,\n        programId,\n      }),\n    ];\n\n    const { publicKey: poolId } = getPdaPoolId(programId, ammConfigId, mintAAddress, mintBAddress);\n    const { publicKey: mintAVault } = getPdaPoolVaultId(programId, poolId, mintAAddress);\n    const { publicKey: mintBVault } = getPdaPoolVaultId(programId, poolId, mintBAddress);\n\n    ins.push(\n      this.createPoolInstruction(\n        programId,\n        poolId,\n        owner,\n        ammConfigId,\n        observationId.publicKey,\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        getPdaExBitmapAccount(programId, poolId).publicKey,\n        initialPriceX64,\n        startTime,\n      ),\n    );\n\n    return {\n      signers: [],\n      instructions: ins,\n      instructionTypes: [InstructionType.CreateAccount, InstructionType.ClmmCreatePool],\n      address: { poolId, observationId: observationId.publicKey, 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 async openPositionInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    amountMaxA,\n    amountMaxB,\n    withMetadata,\n    getEphemeralSigners,\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  }): 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 } = 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 = 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    );\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  }: {\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  }): 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 } = 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 = 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 async openPositionFromLiquidityInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    tickLower,\n    tickUpper,\n    liquidity,\n    amountMaxA,\n    amountMaxB,\n    withMetadata,\n    getEphemeralSigners,\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  }): 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 } = 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 = 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  ): 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: 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  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n    ownerInfo: {\n      wallet: PublicKey;\n    };\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 { 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      ),\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  }: {\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  }): 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 } = 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  }: {\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  }): 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 } = 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  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n    ownerPosition: ClmmPositionLayout;\n\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  }): 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 } = getATAAddress(ownerInfo.wallet, ownerPosition.nftMint, programId);\n\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    ins.push(\n      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    );\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    ownerInfo,\n    inputMint,\n    amountIn,\n    amountOutMin,\n    sqrtPriceLimitX64,\n    remainingAccounts,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\n\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    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        // poolInfo.observationId, // to do get from api\n        mintAVault,\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 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 swapBaseOutInstructions({\n    poolInfo,\n    poolKeys,\n    ownerInfo,\n    outputMint,\n    amountOut,\n    amountInMax,\n    sqrtPriceLimitX64,\n    remainingAccounts,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    poolKeys: ClmmKeys;\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.toString();\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 ? mintA : mintB,\n        isInputMintA ? mintB : mintA,\n\n        remainingAccounts,\n        // poolInfo.observationId, // to do\n        mintAVault,\n        amountOut,\n        amountInMax,\n        sqrtPriceLimitX64,\n        false,\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","import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { TickArrayBitmapExtensionType } from \"../type\";\nimport { TickQuery } from \"./tickQuery\";\nimport { MIN_TICK, MAX_TICK } from \"./constants\";\nimport { SqrtPriceMath, TickMath } from \"./math\";\nimport { ClmmPoolInfo } from \"../type\";\nimport { ApiV3PoolInfoConcentratedItem } from \"@/api/type\";\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      0,\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\";\nexport function 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 i16ToBytes(num: number): Uint8Array {\n  const arr = new ArrayBuffer(2);\n  const view = new DataView(arr);\n  view.setInt16(0, num, false);\n  return new Uint8Array(arr);\n}\n\nexport function u32ToBytes(num: number): Uint8Array {\n  const arr = new ArrayBuffer(4);\n  const view = new DataView(arr);\n  view.setUint32(0, num, false);\n  return new Uint8Array(arr);\n}\n\nexport function i32ToBytes(num: number): Uint8Array {\n  const arr = new ArrayBuffer(4);\n  const view = new DataView(arr);\n  view.setInt32(0, num, false);\n  return new Uint8Array(arr);\n}\n\nexport function leadingZeros(bitNum: number, data: BN): number {\n  let i = 0;\n  for (let j = bitNum - 1; j >= 0; j--) {\n    if (!data.testn(j)) {\n      i++;\n    } else {\n      break;\n    }\n  }\n  return i;\n}\n\nexport function trailingZeros(bitNum: number, data: BN) {\n  let i = 0;\n  for (let j = 0; j < bitNum; j++) {\n    if (!data.testn(j)) {\n      i++;\n    } else {\n      break;\n    }\n  }\n  return i;\n}\n\nexport function isZero(bitNum: number, data: BN): boolean {\n  for (let i = 0; i < bitNum; i++) {\n    if (data.testn(i)) return false;\n  }\n  return true;\n}\n\nexport function mostSignificantBit(bitNum: number, data: BN): number | null {\n  if (isZero(bitNum, data)) return null;\n  else return leadingZeros(bitNum, data);\n}\n\nexport function leastSignificantBit(bitNum: number, data: BN): number | null {\n  if (isZero(bitNum, data)) return null;\n  else return trailingZeros(bitNum, data);\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\");\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","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\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  observationIndex: 0,\n  observationUpdateDuration: 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 { Connection, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { getMultipleAccountsInfo } from \"@/common\";\nimport { TickArrayLayout } from \"../layout\";\n\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { Tick, TICK_ARRAY_SIZE, TickArray, TickUtils } from \"./tick\";\nimport { TickArrayBitmapExtensionType } from \"../type\";\n\nexport const FETCH_TICKARRAY_COUNT = 15;\n\nexport declare type PoolVars = {\n  key: PublicKey;\n  tokenA: PublicKey;\n  tokenB: PublicKey;\n  fee: number;\n};\n\nexport class TickQuery {\n  public static async getTickArrays(\n    connection: Connection,\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickCurrent: number,\n    tickSpacing: number,\n    tickArrayBitmapArray: BN[],\n    exTickArrayBitmap: TickArrayBitmapExtensionType,\n  ): Promise<{ [key: string]: TickArray }> {\n    const tickArraysToFetch: PublicKey[] = [];\n    const currentTickArrayStartIndex = TickUtils.getTickArrayStartIndexByTick(tickCurrent, tickSpacing);\n\n    const startIndexArray = TickUtils.getInitializedTickArrayInRange(\n      tickArrayBitmapArray,\n      exTickArrayBitmap,\n      tickSpacing,\n      currentTickArrayStartIndex,\n      Math.floor(FETCH_TICKARRAY_COUNT / 2),\n    );\n    for (let i = 0; i < startIndexArray.length; i++) {\n      const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, startIndexArray[i]);\n      tickArraysToFetch.push(tickArrayAddress);\n    }\n\n    const fetchedTickArrays = (await getMultipleAccountsInfo(connection, tickArraysToFetch)).map((i) =>\n      i !== null ? TickArrayLayout.decode(i.data) : null,\n    );\n\n    const tickArrayCache: { [key: string]: TickArray } = {};\n    for (let i = 0; i < tickArraysToFetch.length; i++) {\n      const _info = fetchedTickArrays[i];\n      if (_info === null) continue;\n\n      tickArrayCache[_info.startTickIndex] = {\n        ..._info,\n        address: tickArraysToFetch[i],\n      };\n    }\n    return tickArrayCache;\n  }\n\n  public static nextInitializedTick(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickArrayCache: { [key: string]: TickArray },\n    tickIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n  ): {\n    nextTick: Tick;\n    tickArrayAddress: PublicKey | undefined;\n    tickArrayStartTickIndex: number;\n  } {\n    let {\n      initializedTick: nextTick,\n      tickArrayAddress,\n      tickArrayStartTickIndex,\n    } = this.nextInitializedTickInOneArray(programId, poolId, tickArrayCache, tickIndex, tickSpacing, zeroForOne);\n    while (nextTick == undefined || nextTick.liquidityGross.lten(0)) {\n      tickArrayStartTickIndex = TickUtils.getNextTickArrayStartIndex(tickArrayStartTickIndex, tickSpacing, zeroForOne);\n      if (this.checkIsValidStartIndex(tickArrayStartTickIndex, tickSpacing)) {\n        throw new Error(\"No enough initialized tickArray\");\n      }\n      const cachedTickArray = tickArrayCache[tickArrayStartTickIndex];\n\n      if (cachedTickArray === undefined) continue;\n\n      const {\n        nextTick: _nextTick,\n        tickArrayAddress: _tickArrayAddress,\n        tickArrayStartTickIndex: _tickArrayStartTickIndex,\n      } = this.firstInitializedTickInOneArray(programId, poolId, cachedTickArray, zeroForOne);\n      [nextTick, tickArrayAddress, tickArrayStartTickIndex] = [_nextTick, _tickArrayAddress, _tickArrayStartTickIndex];\n    }\n    if (nextTick == undefined) {\n      throw new Error(\"No invaild tickArray cache\");\n    }\n    return { nextTick, tickArrayAddress, tickArrayStartTickIndex };\n  }\n\n  public static nextInitializedTickArray(\n    tickIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n    tickArrayBitmap: BN[],\n    exBitmapInfo: TickArrayBitmapExtensionType,\n  ): {\n    isExist: boolean;\n    nextStartIndex: number;\n  } {\n    const currentOffset = Math.floor(tickIndex / TickQuery.tickCount(tickSpacing));\n    const result: number[] = zeroForOne\n      ? TickUtils.searchLowBitFromStart(tickArrayBitmap, exBitmapInfo, currentOffset - 1, 1, tickSpacing)\n      : TickUtils.searchHightBitFromStart(tickArrayBitmap, exBitmapInfo, currentOffset + 1, 1, tickSpacing);\n\n    return result.length > 0 ? { isExist: true, nextStartIndex: result[0] } : { isExist: false, nextStartIndex: 0 };\n  }\n\n  public static firstInitializedTickInOneArray(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickArray: TickArray,\n    zeroForOne: boolean,\n  ): {\n    nextTick: Tick | undefined;\n    tickArrayAddress: PublicKey;\n    tickArrayStartTickIndex: number;\n  } {\n    let nextInitializedTick: Tick | undefined = undefined;\n    if (zeroForOne) {\n      let i = TICK_ARRAY_SIZE - 1;\n      while (i >= 0) {\n        const tickInArray = tickArray.ticks[i];\n        if (tickInArray.liquidityGross.gtn(0)) {\n          nextInitializedTick = tickInArray;\n          break;\n        }\n        i = i - 1;\n      }\n    } else {\n      let i = 0;\n      while (i < TICK_ARRAY_SIZE) {\n        const tickInArray = tickArray.ticks[i];\n        if (tickInArray.liquidityGross.gtn(0)) {\n          nextInitializedTick = tickInArray;\n          break;\n        }\n        i = i + 1;\n      }\n    }\n    const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, tickArray.startTickIndex);\n    return { nextTick: nextInitializedTick, tickArrayAddress, tickArrayStartTickIndex: tickArray.startTickIndex };\n  }\n\n  public static nextInitializedTickInOneArray(\n    programId: PublicKey,\n    poolId: PublicKey,\n    tickArrayCache: { [key: string]: TickArray },\n    tickIndex: number,\n    tickSpacing: number,\n    zeroForOne: boolean,\n  ): {\n    initializedTick: Tick | undefined;\n    tickArrayAddress: PublicKey | undefined;\n    tickArrayStartTickIndex: number;\n  } {\n    const startIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n    let tickPositionInArray = Math.floor((tickIndex - startIndex) / tickSpacing);\n    const cachedTickArray = tickArrayCache[startIndex];\n    if (cachedTickArray == undefined) {\n      return {\n        initializedTick: undefined,\n        tickArrayAddress: undefined,\n        tickArrayStartTickIndex: startIndex,\n      };\n    }\n    let nextInitializedTick: Tick | undefined = undefined;\n    if (zeroForOne) {\n      while (tickPositionInArray >= 0) {\n        const tickInArray = cachedTickArray.ticks[tickPositionInArray];\n        if (tickInArray.liquidityGross.gtn(0)) {\n          nextInitializedTick = tickInArray;\n          break;\n        }\n        tickPositionInArray = tickPositionInArray - 1;\n      }\n    } else {\n      tickPositionInArray = tickPositionInArray + 1;\n      while (tickPositionInArray < TICK_ARRAY_SIZE) {\n        const tickInArray = cachedTickArray.ticks[tickPositionInArray];\n        if (tickInArray.liquidityGross.gtn(0)) {\n          nextInitializedTick = tickInArray;\n          break;\n        }\n        tickPositionInArray = tickPositionInArray + 1;\n      }\n    }\n    const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, startIndex);\n    return {\n      initializedTick: nextInitializedTick,\n      tickArrayAddress,\n      tickArrayStartTickIndex: cachedTickArray.startTickIndex,\n    };\n  }\n\n  public static getArrayStartIndex(tickIndex: number, tickSpacing: number): number {\n    const ticksInArray = this.tickCount(tickSpacing);\n    const start = Math.floor(tickIndex / ticksInArray);\n\n    return start * ticksInArray;\n  }\n\n  public static checkIsValidStartIndex(tickIndex: number, tickSpacing: number): boolean {\n    if (TickUtils.checkIsOutOfBoundary(tickIndex)) {\n      if (tickIndex > MAX_TICK) {\n        return false;\n      }\n      const minStartIndex = TickUtils.getTickArrayStartIndexByTick(MIN_TICK, tickSpacing);\n      return tickIndex == minStartIndex;\n    }\n    return tickIndex % this.tickCount(tickSpacing) == 0;\n  }\n\n  public static tickCount(tickSpacing: number): number {\n    return TICK_ARRAY_SIZE * tickSpacing;\n  }\n}\n","import { PublicKey, EpochInfo } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\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  Q64,\n  U64Resolution,\n  ZERO,\n  Q128,\n} from \"./constants\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { PoolUtils } from \"./pool\";\nimport { Tick, TickArray, TickUtils } from \"./tick\";\nimport { ReturnTypeGetLiquidityAmountOut, TickArrayBitmapExtensionType } from \"../type\";\nimport { ApiV3PoolInfoConcentratedItem } from \"@/api/type\";\nimport { getTransferAmountFeeV2, minExpirationTime } from \"@/common/transfer\";\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  ): {\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: 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        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      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  ): [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 zeroForOne = sqrtPriceX64Current.gte(sqrtPriceX64Target);\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, Connection, EpochInfo } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport {\n  ClmmPoolInfo,\n  ClmmPoolRewardInfo,\n  ClmmPoolRewardLayoutInfo,\n  ReturnTypeGetLiquidityAmountOut,\n  TickArrayBitmapExtensionType,\n  ReturnTypeFetchExBitmaps,\n  ReturnTypeFetchMultiplePoolTickArrays,\n  SDKParsedConcentratedInfo,\n  ReturnTypeComputeAmountOut,\n  ReturnTypeComputeAmountOutFormat,\n} from \"../type\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"@/api/type\";\n\nimport { ReturnTypeFetchMultipleMintInfos } from \"@/raydium/type\";\nimport { NEGATIVE_ONE, Q64, ZERO, MAX_TICK, MIN_TICK, MIN_SQRT_PRICE_X64, MAX_SQRT_PRICE_X64 } from \"./constants\";\nimport { MathUtil, SwapMath, SqrtPriceMath, LiquidityMath } from \"./math\";\nimport { getPdaTickArrayAddress, getPdaPersonalPositionAddress } from \"./pda\";\nimport { TickArray, TickUtils, TICK_ARRAY_BITMAP_SIZE, Tick } from \"./tick\";\nimport { TickArrayBitmap, TickArrayBitmapExtensionUtils } from \"./tickarrayBitmap\";\nimport { TickQuery } from \"./tickQuery\";\nimport { TickArrayBitmapExtensionLayout, PositionInfoLayout, TickArrayLayout } from \"../layout\";\nimport {\n  getMultipleAccountsInfo,\n  getMultipleAccountsInfoWithCustomFlags,\n  getTransferAmountFee,\n  getTransferAmountFeeV2,\n  minExpirationTime,\n  WSOLMint,\n  SOLMint,\n  solToWSol,\n} from \"../../../common\";\nimport { SOL_INFO } from \"../../token/constant\";\nimport { TokenAccountRaw } from \"../../account/types\";\nimport { Price, Percent, TokenAmount, Token } from \"../../../module\";\nimport { PositionUtils } from \"./position\";\nimport Decimal from \"decimal.js\";\n\nexport class PoolUtils {\n  public static getOutputAmountAndRemainAccounts(\n    poolInfo: ClmmPoolInfo,\n    tickArrayCache: { [key: string]: TickArray },\n    inputTokenMint: PublicKey,\n    inputAmount: BN,\n    sqrtPriceLimitX64?: BN,\n  ): {\n    expectedAmountOut: BN;\n    remainingAccounts: PublicKey[];\n    executionPrice: BN;\n    feeAmount: BN;\n  } {\n    const zeroForOne = inputTokenMint.equals(poolInfo.mintA.mint);\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      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    );\n    allNeededAccounts.push(...reaminAccounts);\n    return {\n      expectedAmountOut: outputAmount.mul(NEGATIVE_ONE),\n      remainingAccounts: allNeededAccounts,\n      executionPrice,\n      feeAmount,\n    };\n  }\n\n  public static getInputAmountAndRemainAccounts(\n    poolInfo: ClmmPoolInfo,\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.equals(poolInfo.mintB.mint);\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: ClmmPoolInfo,\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: ClmmPoolInfo,\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 = MAX_TICK;\n    }\n    if (minTickBoundary < MIN_TICK) {\n      minTickBoundary = MIN_TICK;\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  // deprecated, new api doesn't need\n  // static async fetchMultiplePoolInfos({\n  //   connection,\n  //   poolKeys,\n  //   ownerInfo,\n  //   chainTime,\n  //   batchRequest = false,\n  //   updateOwnerRewardAndFee = true,\n  // }: {\n  //   connection: Connection;\n  //   poolKeys: ApiV3PoolInfoConcentratedItem[];\n  //   ownerInfo?: { wallet: PublicKey; tokenAccounts: TokenAccountRaw[] };\n  //   chainTime: number;\n  //   batchRequest?: boolean;\n  //   updateOwnerRewardAndFee?: boolean;\n  // }): Promise<ReturnTypeFetchMultiplePoolInfos> {\n  //   const poolAccountInfos = await getMultipleAccountsInfo(\n  //     connection,\n  //     poolKeys.map((i) => new PublicKey(i.id)),\n  //     { batchRequest },\n  //   );\n  //   const exBitmapAddress: { [poolId: string]: PublicKey } = {};\n  //   for (let index = 0; index < poolKeys.length; index++) {\n  //     const apiPoolInfo = poolKeys[index];\n  //     const accountInfo = poolAccountInfos[index];\n\n  //     if (accountInfo === null) continue;\n  //     exBitmapAddress[apiPoolInfo.id] = getPdaExBitmapAccount(\n  //       accountInfo.owner,\n  //       new PublicKey(apiPoolInfo.id),\n  //     ).publicKey;\n  //   }\n\n  //   const exBitmapAccountInfos = await this.fetchExBitmaps({\n  //     connection,\n  //     exBitmapAddress: Object.values(exBitmapAddress),\n  //     batchRequest,\n  //   });\n\n  //   const programIds: PublicKey[] = [];\n\n  //   const poolsInfo: ReturnTypeFetchMultiplePoolInfos = {};\n\n  //   const updateRewardInfos: ClmmPoolRewardInfo[] = [];\n\n  //   for (let index = 0; index < poolKeys.length; index++) {\n  //     const apiPoolInfo = poolKeys[index];\n  //     const accountInfo = poolAccountInfos[index];\n  //     const exBitmapInfo = exBitmapAccountInfos[exBitmapAddress[apiPoolInfo.id].toString()];\n\n  //     if (accountInfo === null) continue;\n\n  //     const layoutAccountInfo = PoolInfoLayout.decode(accountInfo.data);\n  //     poolsInfo[apiPoolInfo.id] = {\n  //       state: {\n  //         id: new PublicKey(apiPoolInfo.id),\n  //         mintA: {\n  //           programId: new PublicKey(apiPoolInfo.mintA.programId),\n  //           mint: layoutAccountInfo.mintA,\n  //           vault: layoutAccountInfo.vaultA,\n  //           decimals: layoutAccountInfo.mintDecimalsA,\n  //         },\n  //         mintB: {\n  //           programId: new PublicKey(apiPoolInfo.mintB.programId),\n  //           mint: layoutAccountInfo.mintB,\n  //           vault: layoutAccountInfo.vaultB,\n  //           decimals: layoutAccountInfo.mintDecimalsB,\n  //         },\n  //         observationId: layoutAccountInfo.observationId,\n  //         ammConfig: {\n  //           ...apiPoolInfo.config,\n  //           fundOwner: apiPoolInfo.config.id,\n  //           id: new PublicKey(apiPoolInfo.config.id),\n  //         },\n\n  //         creator: layoutAccountInfo.creator,\n  //         programId: accountInfo.owner,\n  //         version: 6,\n\n  //         tickSpacing: layoutAccountInfo.tickSpacing,\n  //         liquidity: layoutAccountInfo.liquidity,\n  //         sqrtPriceX64: layoutAccountInfo.sqrtPriceX64,\n  //         currentPrice: SqrtPriceMath.sqrtPriceX64ToPrice(\n  //           layoutAccountInfo.sqrtPriceX64,\n  //           layoutAccountInfo.mintDecimalsA,\n  //           layoutAccountInfo.mintDecimalsB,\n  //         ),\n  //         tickCurrent: layoutAccountInfo.tickCurrent,\n  //         observationIndex: layoutAccountInfo.observationIndex,\n  //         observationUpdateDuration: layoutAccountInfo.observationUpdateDuration,\n  //         feeGrowthGlobalX64A: layoutAccountInfo.feeGrowthGlobalX64A,\n  //         feeGrowthGlobalX64B: layoutAccountInfo.feeGrowthGlobalX64B,\n  //         protocolFeesTokenA: layoutAccountInfo.protocolFeesTokenA,\n  //         protocolFeesTokenB: layoutAccountInfo.protocolFeesTokenB,\n  //         swapInAmountTokenA: layoutAccountInfo.swapInAmountTokenA,\n  //         swapOutAmountTokenB: layoutAccountInfo.swapOutAmountTokenB,\n  //         swapInAmountTokenB: layoutAccountInfo.swapInAmountTokenB,\n  //         swapOutAmountTokenA: layoutAccountInfo.swapOutAmountTokenA,\n  //         tickArrayBitmap: layoutAccountInfo.tickArrayBitmap,\n\n  //         rewardInfos: await PoolUtils.updatePoolRewardInfos({\n  //           connection,\n  //           apiPoolInfo,\n  //           chainTime,\n  //           poolLiquidity: layoutAccountInfo.liquidity,\n  //           rewardInfos: layoutAccountInfo.rewardInfos.filter((i) => !i.tokenMint.equals(PublicKey.default)),\n  //         }),\n\n  //         day: apiPoolInfo.day,\n  //         week: apiPoolInfo.week,\n  //         month: apiPoolInfo.month,\n  //         tvl: apiPoolInfo.tvl,\n  //         lookupTableAccount: new PublicKey(apiPoolInfo.lookupTableAccount),\n\n  //         startTime: layoutAccountInfo.startTime.toNumber(),\n\n  //         exBitmapInfo,\n  //       },\n  //     };\n\n  //     if (ownerInfo) {\n  //       updateRewardInfos.push(\n  //         ...poolsInfo[apiPoolInfo.id].state.rewardInfos.filter((i) => i.creator.equals(ownerInfo.wallet)),\n  //       );\n  //     }\n\n  //     if (!programIds.find((i) => i.equals(accountInfo.owner))) programIds.push(accountInfo.owner);\n  //   }\n\n  //   if (ownerInfo) {\n  //     const allMint = ownerInfo.tokenAccounts\n  //       .filter((i) => i.accountInfo.amount.eq(new BN(1)))\n  //       .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\n  //     const keyToTickArrayAddress: { [key: string]: PublicKey } = {};\n  //     for (const itemAccountInfo of positionAccountInfos) {\n  //       if (itemAccountInfo === null) continue;\n  //       const position = PositionInfoLayout.decode(itemAccountInfo.data);\n  //       const itemPoolId = position.poolId.toString();\n  //       const poolInfoA = poolsInfo[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  //       poolsInfo[itemPoolId].positionAccount = [\n  //         ...(poolsInfo[itemPoolId].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 = TickUtils.getTickArrayAddressByTick(\n  //         poolsInfo[itemPoolId].state.programId,\n  //         position.poolId,\n  //         position.tickLower,\n  //         poolsInfo[itemPoolId].state.tickSpacing,\n  //       );\n  //       const tickArrayUpperAddress = TickUtils.getTickArrayAddressByTick(\n  //         poolsInfo[itemPoolId].state.programId,\n  //         position.poolId,\n  //         position.tickUpper,\n  //         poolsInfo[itemPoolId].state.tickSpacing,\n  //       );\n  //       keyToTickArrayAddress[\n  //         `${poolsInfo[itemPoolId].state.programId.toString()}-${position.poolId.toString()}-${position.tickLower}`\n  //       ] = tickArrayLowerAddress;\n  //       keyToTickArrayAddress[\n  //         `${poolsInfo[itemPoolId].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: { [key: string]: TickArray } = {};\n  //       for (let index = 0; index < tickArrayKeys.length; index++) {\n  //         const tickArrayData = tickArrayDatas[index];\n  //         if (tickArrayData === null) continue;\n  //         const key = tickArrayKeys[index];\n  //         tickArrayLayout[key.toString()] = {\n  //           address: key,\n  //           ...TickArrayLayout.decode(tickArrayData.data),\n  //         };\n  //       }\n\n  //       for (const { state, positionAccount } of Object.values(poolsInfo)) {\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 } = PositionUtils.GetPositionFees(\n  //             state,\n  //             itemPA,\n  //             tickLowerState,\n  //             tickUpperState,\n  //           );\n  //           const rewardInfos = PositionUtils.GetPositionRewards(state, itemPA, tickLowerState, tickUpperState);\n  // itemPA.tokenFeeAmountA =\n  //             tokenFeeAmountA.gte(ZERO) && tokenFeeAmountA.lt(U64_IGNORE_RANGE) ? tokenFeeAmountA : ZERO\n  //           itemPA.tokenFeeAmountB =\n  //             tokenFeeAmountB.gte(ZERO) && tokenFeeAmountA.lt(U64_IGNORE_RANGE) ? tokenFeeAmountB : ZERO\n  //           for (let i = 0; i < rewardInfos.length; i++) {\n  //             itemPA.rewardInfos[i].pendingReward = rewardInfos[i].gte(ZERO) ? rewardInfos[i] : ZERO;\n  //           }\n  //         }\n  //       }\n  //     }\n  //   }\n\n  //   if (updateRewardInfos.length > 0) {\n  //     const vaults = updateRewardInfos.map((i) => i.tokenVault);\n  //     const rewardVaultInfos = await getMultipleAccountsInfo(connection, vaults, { batchRequest });\n  //     const rewardVaultAmount: { [mint: string]: BN } = {};\n  //     for (let index = 0; index < vaults.length; index++) {\n  //       const valutKey = vaults[index].toString();\n  //       const itemRewardVaultInfo = rewardVaultInfos[index];\n  //       if (itemRewardVaultInfo === null) continue;\n  //       const info = splAccountLayout.decode(itemRewardVaultInfo.data);\n  //       rewardVaultAmount[valutKey] = info.amount;\n  //     }\n  //     for (const item of updateRewardInfos) {\n  //       const vaultAmount = rewardVaultAmount[item.tokenVault.toString()];\n  //       item.remainingRewards =\n  //         vaultAmount !== undefined ? vaultAmount.sub(item.rewardTotalEmissioned.sub(item.rewardClaimed)) : ZERO;\n  //     }\n  //   }\n\n  //   return poolsInfo;\n  // }\n\n  static async fetchMultiplePoolTickArrays({\n    connection,\n    poolKeys,\n    batchRequest,\n  }: {\n    connection: Connection;\n    poolKeys: ClmmPoolInfo[];\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    token2022Infos,\n    epochInfo,\n    amountIn,\n    slippage,\n    priceLimit = new Decimal(0),\n  }: {\n    poolInfo: ClmmPoolInfo;\n    tickArrayCache: { [key: string]: TickArray };\n    baseMint: PublicKey;\n\n    token2022Infos: ReturnTypeFetchMultipleMintInfos;\n    epochInfo: EpochInfo;\n\n    amountIn: BN;\n    slippage: number;\n    priceLimit?: Decimal;\n  }): ReturnTypeComputeAmountOut {\n    let sqrtPriceLimitX64: BN;\n    if (priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 = baseMint.equals(poolInfo.mintA.mint)\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    const realAmountIn = getTransferAmountFee(\n      amountIn,\n      token2022Infos[baseMint.toString()]?.feeConfig,\n      epochInfo,\n      false,\n    );\n\n    const {\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    );\n\n    const outMint = poolInfo.mintA.mint.equals(baseMint) ? poolInfo.mintB.mint : poolInfo.mintA.mint;\n    const amountOut = getTransferAmountFee(\n      _expectedAmountOut,\n      token2022Infos[outMint.toString()]?.feeConfig,\n      epochInfo,\n      false,\n    );\n\n    const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      _executionPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const executionPrice = baseMint.equals(poolInfo.mintA.mint) ? _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 = getTransferAmountFee(\n      _minAmountOut,\n      token2022Infos[outMint.toString()]?.feeConfig,\n      epochInfo,\n      false,\n    );\n\n    const poolPrice = poolInfo.mintA.mint.equals(baseMint)\n      ? poolInfo.currentPrice\n      : 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      realAmountIn,\n      amountOut,\n      minAmountOut,\n      expirationTime: minExpirationTime(realAmountIn.expirationTime, amountOut.expirationTime),\n      currentPrice: poolInfo.currentPrice,\n      executionPrice,\n      priceImpact,\n      fee: feeAmount,\n\n      remainingAccounts,\n    };\n  }\n\n  static async computeAmountOutFormat({\n    poolInfo,\n    tickArrayCache,\n    token2022Infos,\n    amountIn,\n    tokenOut: _tokenOut,\n    slippage,\n    epochInfo,\n  }: {\n    poolInfo: ClmmPoolInfo;\n    tickArrayCache: { [key: string]: TickArray };\n    token2022Infos: ReturnTypeFetchMultipleMintInfos;\n    amountIn: TokenAmount;\n    tokenOut: Token;\n    slippage: Percent;\n    epochInfo: EpochInfo;\n  }): Promise<ReturnTypeComputeAmountOutFormat> {\n    const inputMint = amountIn.token.equals(Token.WSOL) ? WSOLMint : amountIn.token.mint;\n    const _slippage = slippage.numerator.toNumber() / slippage.denominator.toNumber();\n    const tokenOut = _tokenOut.mint.equals(SOLMint)\n      ? new Token({ mint: \"sol\", decimals: SOL_INFO.decimals })\n      : _tokenOut;\n\n    const {\n      realAmountIn: _realAmountIn,\n      amountOut: _amountOut,\n      minAmountOut: _minAmountOut,\n      expirationTime,\n      currentPrice,\n      executionPrice,\n      priceImpact,\n      fee,\n      remainingAccounts,\n    } = await PoolUtils.computeAmountOut({\n      poolInfo,\n      tickArrayCache,\n      baseMint: inputMint,\n      amountIn: amountIn.raw,\n      slippage: _slippage,\n      token2022Infos,\n      epochInfo,\n    });\n\n    const realAmountIn = {\n      ..._realAmountIn,\n      amount: new TokenAmount(amountIn.token, _realAmountIn.amount),\n      fee: _realAmountIn.fee === undefined ? undefined : new TokenAmount(amountIn.token, _realAmountIn.fee),\n    };\n\n    const amountOut = {\n      ..._amountOut,\n      amount: new TokenAmount(tokenOut, _amountOut.amount),\n      fee: _amountOut.fee === undefined ? undefined : new TokenAmount(tokenOut, _amountOut.fee),\n    };\n    const minAmountOut = {\n      ..._minAmountOut,\n      amount: new TokenAmount(tokenOut, _minAmountOut.amount),\n      fee: _minAmountOut.fee === undefined ? undefined : new TokenAmount(tokenOut, _minAmountOut.fee),\n    };\n\n    const _currentPrice = new Price({\n      baseToken: amountIn.token,\n      denominator: new BN(10).pow(new BN(20 + amountIn.token.decimals)),\n      quoteToken: tokenOut,\n      numerator: currentPrice.mul(new Decimal(10 ** (20 + tokenOut.decimals))).toFixed(0),\n    });\n    const _executionPrice = new Price({\n      baseToken: amountIn.token,\n      denominator: new BN(10).pow(new BN(20 + amountIn.token.decimals)),\n      quoteToken: tokenOut,\n      numerator: executionPrice.mul(new Decimal(10 ** (20 + tokenOut.decimals))).toFixed(0),\n    });\n    const _fee = new TokenAmount(amountIn.token, fee);\n\n    return {\n      realAmountIn,\n      amountOut,\n      minAmountOut,\n      expirationTime,\n      currentPrice: _currentPrice,\n      executionPrice: _executionPrice,\n      priceImpact,\n      fee: _fee,\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 = userTvl.div(poolTvl.add(userTvl)).div(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 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()).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    return PoolUtils.getAmountsFromLiquidity({\n      epochInfo,\n      poolInfo,\n      tickLower,\n      tickUpper,\n      liquidity,\n      slippage,\n      add,\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\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","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 BN from \"bn.js\";\n\nimport { ClmmPoolInfo, ClmmPoolPersonalPosition, ClmmPoolRewardInfo, SDKParsedConcentratedInfo } from \"../type\";\nimport { minExpirationTime, getTransferAmountFeeV2 } from \"@/common\";\nimport { Q64 } from \"./constants\";\nimport { MathUtil, SqrtPriceMath, LiquidityMath } from \"./math\";\nimport { Tick } from \"./tick\";\nimport { GetAmountParams, ReturnTypeGetLiquidityAmountOut } from \"../type\";\nimport Decimal from \"decimal.js\";\nimport { ClmmPositionLayout } from \"../layout\";\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 { blob, bool, i128, 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 AmmConfigLayout = 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([\n  u32(\"blockTimestamp\"),\n  u128(\"sqrtPriceX64\"),\n  u128(\"cumulativeTimePriceX64\"),\n  seq(u128(), 1, \"\"),\n]);\nexport const ObservationInfoLayout = struct([\n  blob(8),\n  bool(\"initialized\"),\n  publicKey(\"poolId\"),\n  seq(ObservationLayout, 1000, \"observations\"),\n  seq(u128(), 5, \"\"),\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  u16(\"observationIndex\"),\n  u16(\"observationUpdateDuration\"),\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","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport { AmmV4Keys, AmmV5Keys } from \"@/api/type\";\nimport {\n  findProgramAddress,\n  simulateMultipleInstruction,\n  parseSimulateLogToJson,\n  parseSimulateValue,\n} from \"@/common/txTool/txUtils\";\nimport { getSerumAssociatedAuthority } from \"./serum\";\nimport { LiquidityPoolKeys } from \"./type\";\nimport { StableLayout } from \"./stable\";\nimport { makeSimulatePoolInfoInstruction } from \"./instruction\";\nimport BN from \"bn.js\";\n\ntype AssociatedName =\n  | \"amm_associated_seed\"\n  | \"lp_mint_associated_seed\"\n  | \"coin_vault_associated_seed\"\n  | \"pc_vault_associated_seed\"\n  | \"lp_mint_associated_seed\"\n  | \"temp_lp_token_associated_seed\"\n  | \"open_order_associated_seed\"\n  | \"target_associated_seed\"\n  | \"withdraw_associated_seed\";\n\ninterface GetAssociatedParam {\n  name: AssociatedName;\n  programId: PublicKey;\n  marketId: PublicKey;\n}\n\nexport function getAssociatedConfigId({ programId }: { programId: PublicKey }): PublicKey {\n  const { publicKey } = findProgramAddress([Buffer.from(\"amm_config_account_seed\", \"utf-8\")], programId);\n  return publicKey;\n}\n\nexport function getLiquidityAssociatedId({ name, programId, marketId }: GetAssociatedParam): PublicKey {\n  const { publicKey } = findProgramAddress(\n    [programId.toBuffer(), marketId.toBuffer(), Buffer.from(name, \"utf-8\")],\n    programId,\n  );\n  return publicKey;\n}\n\nexport function getAssociatedOpenOrders({ programId, marketId }: { programId: PublicKey; marketId: PublicKey }) {\n  const { publicKey } = findProgramAddress(\n    [programId.toBuffer(), marketId.toBuffer(), Buffer.from(\"open_order_associated_seed\", \"utf-8\")],\n    programId,\n  );\n  return publicKey;\n}\n\nexport function getLiquidityAssociatedAuthority({ programId }: { programId: PublicKey }): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  return findProgramAddress([Buffer.from([97, 109, 109, 32, 97, 117, 116, 104, 111, 114, 105, 116, 121])], programId);\n}\n\nexport function getAssociatedPoolKeys({\n  version,\n  marketVersion,\n  marketId,\n  baseMint,\n  quoteMint,\n  baseDecimals,\n  quoteDecimals,\n  programId,\n  marketProgramId,\n}: {\n  version: 4 | 5;\n  marketVersion: 3;\n  marketId: PublicKey;\n  baseMint: PublicKey;\n  quoteMint: PublicKey;\n  baseDecimals: number;\n  quoteDecimals: number;\n  programId: PublicKey;\n  marketProgramId: PublicKey;\n}): LiquidityPoolKeys {\n  const id = getLiquidityAssociatedId({ name: \"amm_associated_seed\", programId, marketId });\n  const lpMint = getLiquidityAssociatedId({ name: \"lp_mint_associated_seed\", programId, marketId });\n  const { publicKey: authority, nonce } = getLiquidityAssociatedAuthority({ programId });\n  const baseVault = getLiquidityAssociatedId({ name: \"coin_vault_associated_seed\", programId, marketId });\n  const quoteVault = getLiquidityAssociatedId({ name: \"pc_vault_associated_seed\", programId, marketId });\n  const lpVault = getLiquidityAssociatedId({ name: \"temp_lp_token_associated_seed\", programId, marketId });\n  const openOrders = getAssociatedOpenOrders({ programId, marketId });\n  const targetOrders = getLiquidityAssociatedId({ name: \"target_associated_seed\", programId, marketId });\n  const withdrawQueue = getLiquidityAssociatedId({ name: \"withdraw_associated_seed\", programId, marketId });\n\n  const { publicKey: marketAuthority } = getSerumAssociatedAuthority({\n    programId: marketProgramId,\n    marketId,\n  });\n\n  return {\n    // base\n    id,\n    baseMint,\n    quoteMint,\n    lpMint,\n    baseDecimals,\n    quoteDecimals,\n    lpDecimals: baseDecimals,\n    // version\n    version,\n    programId,\n    // keys\n    authority,\n    nonce,\n    baseVault,\n    quoteVault,\n    lpVault,\n    openOrders,\n    targetOrders,\n    withdrawQueue,\n    // market version\n    marketVersion,\n    marketProgramId,\n    // market keys\n    marketId,\n    marketAuthority,\n    lookupTableAccount: PublicKey.default,\n    configId: getAssociatedConfigId({ programId }),\n  };\n}\n\nlet stableLayout: StableLayout | undefined;\n\nexport async function fetchMultipleInfo({\n  connection,\n  poolKeysList,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  config,\n}: {\n  connection: Connection;\n  poolKeysList: (AmmV4Keys | AmmV5Keys)[];\n  config: any;\n}): Promise<\n  {\n    status: BN;\n    baseDecimals: number;\n    quoteDecimals: number;\n    lpDecimals: number;\n    baseReserve: BN;\n    quoteReserve: BN;\n    lpSupply: BN;\n    startTime: BN;\n  }[]\n> {\n  if (!stableLayout) {\n    stableLayout = new StableLayout({ connection });\n    await stableLayout.initStableModelLayout();\n  }\n\n  const instructions = poolKeysList.map((pool) => makeSimulatePoolInfoInstruction({ poolKeys: pool }));\n  const logs = await simulateMultipleInstruction(\n    connection,\n    instructions.map((i) => i.instruction),\n    \"GetPoolData\",\n  );\n\n  const poolsInfo = logs.map((log) => {\n    const json = parseSimulateLogToJson(log, \"GetPoolData\");\n\n    const status = new BN(parseSimulateValue(json, \"status\"));\n    const baseDecimals = Number(parseSimulateValue(json, \"coin_decimals\"));\n    const quoteDecimals = Number(parseSimulateValue(json, \"pc_decimals\"));\n    const lpDecimals = Number(parseSimulateValue(json, \"lp_decimals\"));\n    const baseReserve = new BN(parseSimulateValue(json, \"pool_coin_amount\"));\n    const quoteReserve = new BN(parseSimulateValue(json, \"pool_pc_amount\"));\n    const lpSupply = new BN(parseSimulateValue(json, \"pool_lp_supply\"));\n    // TODO fix it when split stable\n    let startTime = \"0\";\n    try {\n      startTime = parseSimulateValue(json, \"pool_open_time\");\n    } catch (error) {\n      //\n    }\n\n    return {\n      status,\n      baseDecimals,\n      quoteDecimals,\n      lpDecimals,\n      baseReserve,\n      quoteReserve,\n      lpSupply,\n      startTime: new BN(startTime),\n    };\n  });\n\n  return poolsInfo;\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport { LIQUIDITY_VERSION_TO_SERUM_VERSION } from \"./constant\";\nimport { SerumVersion } from \"../serum\";\nimport { createLogger } from \"@/common/logger\";\n\nconst logger = createLogger(\"Raydium_liquidity_serum\");\n\nexport function getSerumVersion(version: number): SerumVersion {\n  const serumVersion = LIQUIDITY_VERSION_TO_SERUM_VERSION[version];\n  if (!serumVersion) logger.logWithError(\"invalid version\", \"version\", version);\n\n  return serumVersion;\n}\n\nexport function getSerumAssociatedAuthority({ programId, marketId }: { programId: PublicKey; marketId: PublicKey }): {\n  publicKey: PublicKey;\n  nonce: number;\n} {\n  const seeds = [marketId.toBuffer()];\n\n  let nonce = 0;\n  let publicKey: PublicKey;\n\n  while (nonce < 100) {\n    try {\n      const seedsWithNonce = seeds.concat(Buffer.from([nonce]), Buffer.alloc(7));\n      publicKey = PublicKey.createProgramAddressSync(seedsWithNonce, programId);\n    } catch (err) {\n      if (err instanceof TypeError) {\n        throw err;\n      }\n      nonce++;\n      continue;\n    }\n    return { publicKey, nonce };\n  }\n\n  logger.logWithError(\"unable to find a viable program address nonce\", \"params\", {\n    programId,\n    marketId,\n  });\n  throw new Error(\"unable to find a viable program address nonce\");\n}\n","import BN from \"bn.js\";\nimport { SerumVersion } from \"../serum\";\n\nexport const LIQUIDITY_FEES_NUMERATOR = new BN(25);\nexport const LIQUIDITY_FEES_DENOMINATOR = new BN(10000);\n\n// liquidity version => serum version\nexport const LIQUIDITY_VERSION_TO_SERUM_VERSION: {\n  [key in 4 | 5]?: SerumVersion;\n} = {\n  4: 3,\n  5: 3,\n};\n","import { PublicKey } from \"@solana/web3.js\";\nimport Decimal from \"decimal.js\";\nimport { InstructionType, WSOLMint, getTransferAmountFee } from \"@/common\";\nimport { Percent } from \"@/module/percent\";\nimport { ApiV3PoolInfoConcentratedItem, ClmmKeys } from \"@/api/type\";\nimport { MakeTxData, MakeMultiTxData } from \"@/common/txTool/txTool\";\nimport { TxVersion } from \"@/common/txTool/txType\";\nimport { getATAAddress } from \"@/common\";\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport { mockV3CreatePoolInfo, MAX_SQRT_PRICE_X64, MIN_SQRT_PRICE_X64, ONE } from \"./utils/constants\";\nimport { SqrtPriceMath } from \"./utils/math\";\nimport { PoolUtils } from \"./utils/pool\";\nimport {\n  CreateConcentratedPool,\n  IncreasePositionFromLiquidity,\n  IncreasePositionFromBase,\n  DecreaseLiquidity,\n  OpenPositionFromBase,\n  OpenPositionFromLiquidity,\n  InitRewardParams,\n  InitRewardsParams,\n  SetRewardParams,\n  SetRewardsParams,\n  CollectRewardParams,\n  CollectRewardsParams,\n  ManipulateLiquidityExtInfo,\n  ReturnTypeComputeAmountOutBaseOut,\n  OpenPositionFromLiquidityExtInfo,\n  OpenPositionFromBaseExtInfo,\n  ClosePositionExtInfo,\n  InitRewardExtInfo,\n  HarvestAllRewardsParams,\n} from \"./type\";\nimport { ClmmInstrument } from \"./instrument\";\nimport { LoadParams, MakeTransaction, ReturnTypeFetchMultipleMintInfos } from \"../type\";\nimport { MathUtil } from \"./utils/math\";\nimport { TickArray } from \"./utils/tick\";\nimport { getPdaOperationAccount } from \"./utils/pda\";\nimport { ClmmPositionLayout, OperationLayout } from \"./layout\";\nimport BN from \"bn.js\";\n\nexport class Clmm extends ModuleBase {\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  public async load(params?: LoadParams): Promise<void> {\n    await this.scope.token.load(params);\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      startTime,\n      computeBudgetConfig,\n      forerunCreate,\n      txVersion,\n    } = props;\n    const txBuilder = this.createTxBuilder();\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 insInfo = await ClmmInstrument.createPoolInstructions({\n      connection: this.scope.connection,\n      programId,\n      owner,\n      mintA,\n      mintB,\n      ammConfigId: ammConfig.id,\n      initialPriceX64,\n      startTime,\n      forerunCreate,\n    });\n\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\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          programId: programId.toString(),\n          id: insInfo.address.poolId.toString(),\n          mintA,\n          mintB,\n          openTime: startTime.toNumber(),\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          id: insInfo.address.poolId.toString(),\n          mintA,\n          mintB,\n          feeRate: ammConfig.tradeFeeRate,\n          openTime: startTime.toNumber(),\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          ...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    associatedOnly = true,\n    checkCreateATAOwner = false,\n    withMetadata = \"create\",\n    getEphemeralSigners,\n    computeBudgetConfig,\n    txVersion,\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();\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\", this.scope.account.tokenAccounts);\n\n    const poolKeys = propPoolKeys || ((await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys);\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    });\n\n    txBuilder.addInstruction(insInfo);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n    return txBuilder.versionBuild<OpenPositionFromBaseExtInfo>({ txVersion, extInfo: insInfo.address }) as Promise<\n      MakeTxData<T, OpenPositionFromBaseExtInfo>\n    >;\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    getEphemeralSigners,\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();\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: mintAUseSOLBalance\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: mintBUseSOLBalance\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys);\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    });\n    txBuilder.addInstruction(makeOpenPositionInstructions);\n\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      ownerPosition,\n      amountMaxA,\n      amountMaxB,\n      liquidity,\n      ownerInfo,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txVersion,\n    } = props;\n    const txBuilder = this.createTxBuilder();\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\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: mintAUseSOLBalance\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\n    const { account: _ownerTokenAccountB, instructionParams: _tokenAccountBInstruction } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo: mintBUseSOLBalance\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 = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    });\n    txBuilder.addInstruction(ins);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n\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      txVersion,\n    } = props;\n    const txBuilder = this.createTxBuilder();\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: mintAUseSOLBalance\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        mint: new PublicKey(poolInfo.mintB.address),\n        owner: this.scope.ownerPubKey,\n\n        createInfo: mintBUseSOLBalance\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    });\n    txBuilder.addInstruction(ins);\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n\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      ownerPosition,\n      ownerInfo,\n      amountMinA,\n      amountMinB,\n      liquidity,\n      associatedOnly = true,\n      checkCreateATAOwner = false,\n      computeBudgetConfig,\n      txVersion,\n    } = props;\n    if (this.scope.availability.removeConcentratedPosition === false)\n      this.logAndCreateError(\"remove position feature disabled in your region\");\n    const txBuilder = this.createTxBuilder();\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 = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    });\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      });\n      txBuilder.addInstruction({\n        endInstructions: closeInsInfo.instructions,\n        endInstructionTypes: closeInsInfo.instructionTypes,\n      });\n      extInfo = { ...extInfo, ...closeInsInfo.address };\n    }\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\n\n    return txBuilder.versionBuild<ManipulateLiquidityExtInfo>({\n      txVersion,\n      extInfo: { address: extInfo },\n    }) as Promise<MakeTxData<T, ManipulateLiquidityExtInfo>>;\n  }\n\n  public async closePosition<T extends TxVersion>({\n    poolInfo,\n    ownerPosition,\n    txVersion,\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    ownerPosition: ClmmPositionLayout;\n    txVersion: T;\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();\n    const poolKeys = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\n    const ins = ClmmInstrument.closePositionInstructions({\n      poolInfo,\n      poolKeys,\n      ownerInfo: { wallet: this.scope.ownerPubKey },\n      ownerPosition,\n    });\n\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  }: 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();\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    ownerInfo,\n    rewardInfos,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txVersion,\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();\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 = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    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    txVersion,\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();\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    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    ownerInfo,\n    rewardInfos,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    computeBudgetConfig,\n    txVersion,\n  }: SetRewardsParams<T>): Promise<MakeTxData<T, { address: Record<string, PublicKey> }>> {\n    const txBuilder = this.createTxBuilder();\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 = (await this.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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    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({\n    poolInfo,\n    ownerInfo,\n    rewardMint,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n  }: CollectRewardParams): Promise<MakeTransaction> {\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();\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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\n    return txBuilder.build<{ address: Record<string, PublicKey> }>({ address: insInfo.address });\n  }\n\n  public async collectRewards({\n    poolInfo,\n    ownerInfo,\n    rewardMints,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n  }: CollectRewardsParams): Promise<MakeTransaction> {\n    const txBuilder = this.createTxBuilder();\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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\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\n    return txBuilder.build<{ address: Record<string, PublicKey> }>({ address });\n  }\n\n  public async harvestAllRewards<T extends TxVersion = TxVersion.LEGACY>({\n    allPoolInfo,\n    allPositions,\n    ownerInfo,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    programId,\n    txVersion,\n    computeBudgetConfig,\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 txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(computeBudgetConfig);\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: true,\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: true,\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      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.scope.api.fetchPoolKeysById({ id: poolInfo.id })) as ClmmKeys;\n\n      for (const itemPosition of allPositions[itemInfo.id]) {\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        });\n        txBuilder.addInstruction(insData);\n      }\n    }\n\n    if (txVersion === TxVersion.V0) return txBuilder.sizeCheckBuildV0() as Promise<MakeMultiTxData<T>>;\n    return txBuilder.sizeCheckBuild() 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 computeAmountIn({\n    poolInfo,\n    tickArrayCache,\n    baseMint,\n    token2022Infos,\n    amountOut,\n    slippage,\n    priceLimit = new Decimal(0),\n  }: {\n    poolInfo: ApiV3PoolInfoConcentratedItem;\n    tickArrayCache: { [key: string]: TickArray };\n    baseMint: PublicKey;\n    token2022Infos: ReturnTypeFetchMultipleMintInfos;\n    amountOut: BN;\n    slippage: number;\n    priceLimit?: Decimal;\n  }): Promise<ReturnTypeComputeAmountOutBaseOut> {\n    const epochInfo = await this.scope.fetchEpochInfo();\n\n    let sqrtPriceLimitX64: BN;\n    if (priceLimit.equals(new Decimal(0))) {\n      sqrtPriceLimitX64 =\n        baseMint.toString() === poolInfo.mintB.address ? MIN_SQRT_PRICE_X64.add(ONE) : MAX_SQRT_PRICE_X64.sub(ONE);\n    } else {\n      sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n        priceLimit,\n        poolInfo.mintA.decimals,\n        poolInfo.mintB.decimals,\n      );\n    }\n\n    const realAmountOut = getTransferAmountFee(\n      amountOut,\n      token2022Infos[baseMint.toString()]?.feeConfig,\n      epochInfo,\n      true,\n    );\n\n    const {\n      expectedAmountIn,\n      remainingAccounts,\n      executionPrice: _executionPriceX64,\n      feeAmount,\n    } = PoolUtils.getInputAmountAndRemainAccounts(\n      poolInfo as any, // todo\n      tickArrayCache,\n      baseMint,\n      realAmountOut.amount.sub(realAmountOut.fee || new BN(0)),\n      sqrtPriceLimitX64,\n    );\n\n    const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n      _executionPriceX64,\n      poolInfo.mintA.decimals,\n      poolInfo.mintB.decimals,\n    );\n    const executionPrice =\n      baseMint.toString() === poolInfo.mintA.address ? _executionPrice : new Decimal(1).div(_executionPrice);\n\n    const maxAmountIn = expectedAmountIn.mul(new BN(Math.floor((1 + slippage) * 10000000000))).div(new BN(10000000000));\n\n    const poolPrice =\n      poolInfo.mintA.address === baseMint.toString() ? poolInfo.price : new Decimal(1).div(poolInfo.price);\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: expectedAmountIn,\n      maxAmountIn,\n      currentPrice: new Decimal(poolInfo.price),\n      executionPrice,\n      priceImpact,\n      fee: feeAmount,\n\n      remainingAccounts,\n    };\n  }\n}\n","import { PublicKey, TransactionInstruction } from \"@solana/web3.js\";\nimport { createTransferInstruction } from \"@solana/spl-token\";\nimport { forecastTransactionSize, solToWSol, TxBuilder, BN_ZERO, SOLMint, WSOLMint, addComputeBudget } from \"@/common\";\nimport { Token } from \"@/module\";\nimport { StableLayout } from \"../liquidity/stable\";\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport {\n  ComputeAmountOutLayout,\n  ComputeAmountOutRouteLayout,\n  PoolAccountInfoV4,\n  ReturnTypeGetAddLiquidityDefaultPool,\n} from \"./type\";\nimport { makeSwapInstruction } from \"./instrument\";\nimport { MakeMultiTransaction, MakeTransaction } from \"../type\";\nimport { InstructionType } from \"@/common/txTool/txType\";\nimport { BigNumberish, parseBigNumberish } from \"@/common/bignumber\";\nimport {\n  createWSolAccountInstructions,\n  closeAccountInstruction,\n  makeTransferInstruction,\n} from \"../account/instruction\";\nimport { TokenAccount } from \"../account/types\";\nimport { ComputeBudgetConfig } from \"@/raydium/type\";\n\ntype LiquidityPoolJsonInfo = any;\nexport default class TradeV2 extends ModuleBase {\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  static getAddLiquidityDefaultPool({\n    addLiquidityPools,\n    poolInfosCache,\n  }: {\n    addLiquidityPools: LiquidityPoolJsonInfo[];\n    poolInfosCache: { [ammId: string]: PoolAccountInfoV4 };\n  }): ReturnTypeGetAddLiquidityDefaultPool {\n    if (addLiquidityPools.length === 0) return undefined;\n    if (addLiquidityPools.length === 1) return addLiquidityPools[0];\n    addLiquidityPools.sort((a, b) => b.version - a.version);\n    if (addLiquidityPools[0].version !== addLiquidityPools[1].version) return addLiquidityPools[0];\n\n    const _addLiquidityPools = addLiquidityPools.filter((i) => i.version === addLiquidityPools[0].version);\n\n    _addLiquidityPools.sort((a, b) => this.comparePoolSize(a, b, poolInfosCache));\n    return _addLiquidityPools[0];\n  }\n\n  private static comparePoolSize(\n    a: LiquidityPoolJsonInfo,\n    b: LiquidityPoolJsonInfo,\n    ammIdToPoolInfo: { [ammId: string]: PoolAccountInfoV4 },\n  ): number {\n    const aInfo = ammIdToPoolInfo[a.id];\n    const bInfo = ammIdToPoolInfo[b.id];\n    if (aInfo === undefined) return 1;\n    if (bInfo === undefined) return -1;\n\n    if (a.baseMint === b.baseMint) {\n      const sub = aInfo.baseReserve.sub(bInfo.baseReserve);\n      return sub.gte(BN_ZERO) ? -1 : 1;\n    } else {\n      const sub = aInfo.baseReserve.sub(bInfo.quoteReserve);\n      return sub.gte(BN_ZERO) ? -1 : 1;\n    }\n  }\n\n  // public async getAllRouteComputeAmountOut({\n  //   inputTokenAmount,\n  //   outputToken: orgOut,\n  //   directPath,\n  //   routePathDict,\n  //   simulateCache,\n  //   tickCache,\n  //   slippage,\n  //   chainTime,\n  //   feeConfig,\n  //   mintInfos,\n  // }: {\n  //   directPath: PoolType[];\n  //   routePathDict: RoutePathType;\n  //   simulateCache: ReturnTypeFetchMultipleInfo;\n  //   tickCache: ReturnTypeFetchMultiplePoolTickArrays;\n  //   inputTokenAmount: TokenAmount;\n  //   outputToken: Token;\n  //   slippage: Percent;\n  //   chainTime: number;\n  //   feeConfig?: {\n  //     feeBps: BN;\n  //     feeAccount: PublicKey;\n  //   };\n  //   mintInfos: ReturnTypeFetchMultipleMintInfos;\n  // }): Promise<{\n  //   routes: ComputeAmountOutLayout[];\n  //   best?: ComputeAmountOutLayout;\n  // }> {\n  //   const epochInfo = await this.scope.fetchEpochInfo();\n  //   const input = this.scope.solToWsolTokenAmount(inputTokenAmount);\n  //   const _amountIn =\n  //     feeConfig === undefined ? BN_ZERO : input.raw.mul(new BN(10000 - feeConfig.feeBps.toNumber())).div(new BN(10000));\n  //   const amountIn = feeConfig === undefined ? input : new TokenAmount(input.token, _amountIn, true);\n  //   const _inFeeConfig =\n  //     feeConfig === undefined\n  //       ? undefined\n  //       : {\n  //           feeAmount: _amountIn,\n  //           feeAccount: feeConfig.feeAccount,\n  //         };\n\n  //   const outputToken = this.scope.mintToToken(solToWSol(orgOut.mint));\n  //   const outRoute: ComputeAmountOutLayout[] = [];\n\n  //   for (const itemPool of directPath) {\n  //     if (itemPool.version === 6) {\n  //       try {\n  //         const {\n  //           realAmountIn,\n  //           amountOut,\n  //           minAmountOut,\n  //           expirationTime,\n  //           currentPrice,\n  //           executionPrice,\n  //           priceImpact,\n  //           fee,\n  //           remainingAccounts,\n  //         } = await PoolUtils.computeAmountOutFormat({\n  //           poolInfo: itemPool as ClmmPoolInfo,\n  //           tickArrayCache: tickCache[itemPool.id.toString()],\n  //           amountIn,\n  //           tokenOut: outputToken,\n  //           slippage,\n  //           token2022Infos: mintInfos,\n  //           epochInfo,\n  //         });\n  //         outRoute.push({\n  //           amountIn: realAmountIn,\n  //           amountOut,\n  //           minAmountOut,\n  //           currentPrice,\n  //           executionPrice,\n  //           priceImpact,\n  //           fee: [fee],\n  //           remainingAccounts: [remainingAccounts],\n  //           routeType: \"amm\",\n  //           poolKey: [itemPool],\n  //           poolReady: (itemPool as ClmmPoolInfo).startTime < chainTime,\n  //           poolType: \"CLMM\",\n  //           feeConfig: _inFeeConfig,\n  //           expirationTime: minExpirationTime(realAmountIn.expirationTime, expirationTime),\n  //         });\n  //       } catch (e) {\n  //         //\n  //       }\n  //     } else {\n  //       try {\n  //         if (![1, 6, 7].includes(simulateCache[itemPool.id as string].status.toNumber())) continue;\n  //         // const { amountOut, minAmountOut, currentPrice, executionPrice, priceImpact, fee } =\n  //         //   this.scope.liquidity.computeAmountOut({\n  //         //     poolKeys: jsonInfo2PoolKeys(itemPool) as LiquidityPoolKeys,\n  //         //     poolInfo: simulateCache[itemPool.id as string],\n  //         //     amountIn,\n  //         //     outputToken,\n  //         //     slippage,\n  //         //   });\n  //         // outRoute.push({\n  //         //   amountIn: { amount: amountIn, fee: undefined, expirationTime: undefined },\n  //         //   amountOut: { amount: amountOut, fee: undefined, expirationTime: undefined },\n  //         //   minAmountOut: { amount: minAmountOut, fee: undefined, expirationTime: undefined },\n  //         //   currentPrice,\n  //         //   executionPrice,\n  //         //   priceImpact,\n  //         //   fee: [fee],\n  //         //   routeType: \"amm\",\n  //         //   poolKey: [itemPool],\n  //         //   remainingAccounts: [],\n  //         //   poolReady: simulateCache[itemPool.id as string].startTime.toNumber() < chainTime,\n  //         //   poolType: itemPool.version === 5 ? \"STABLE\" : undefined,\n  //         //   feeConfig: _inFeeConfig,\n  //         //   expirationTime: undefined,\n  //         // });\n  //       } catch (e) {\n  //         //\n  //       }\n  //     }\n  //   }\n  //   for (const [routeMint, info] of Object.entries(routePathDict)) {\n  //     for (const iFromPool of info.in) {\n  //       if (!simulateCache[iFromPool.id as string] && !tickCache[iFromPool.id.toString()]) continue;\n  //       if (iFromPool.version !== 6 && ![1, 6, 7].includes(simulateCache[iFromPool.id as string].status.toNumber()))\n  //         continue;\n  //       for (const iOutPool of info.out) {\n  //         if (!simulateCache[iOutPool.id as string] && !tickCache[iOutPool.id.toString()]) continue;\n  //         if (iOutPool.version !== 6 && ![1, 6, 7].includes(simulateCache[iOutPool.id as string].status.toNumber()))\n  //           continue;\n  //         try {\n  //           const {\n  //             amountOut,\n  //             minAmountOut,\n  //             executionPrice,\n  //             priceImpact,\n  //             fee,\n  //             remainingAccounts,\n  //             minMiddleAmountFee,\n  //             middleToken,\n  //             expirationTime,\n  //             realAmountIn,\n  //           } = await this.computeAmountOut({\n  //             middleMintInfo: {\n  //               mint: new PublicKey(routeMint),\n  //               decimals: info.mDecimals,\n  //             },\n  //             amountIn,\n  //             currencyOut: outputToken,\n  //             slippage,\n\n  //             fromPool: iFromPool,\n  //             toPool: iOutPool,\n  //             simulateCache,\n  //             tickCache,\n  //             mintInfos,\n  //           });\n\n  //           const infoAPoolOpen =\n  //             iFromPool.version === 6\n  //               ? (iFromPool as ClmmPoolInfo).startTime < chainTime\n  //               : simulateCache[iFromPool.id as string].startTime.toNumber() < chainTime;\n  //           const infoBPoolOpen =\n  //             iOutPool.version === 6\n  //               ? (iOutPool as ClmmPoolInfo).startTime < chainTime\n  //               : simulateCache[iOutPool.id as string].startTime.toNumber() < chainTime;\n\n  //           const poolTypeA = iFromPool.version === 6 ? \"CLMM\" : iFromPool.version === 5 ? \"STABLE\" : undefined;\n  //           const poolTypeB = iOutPool.version === 6 ? \"CLMM\" : iOutPool.version === 5 ? \"STABLE\" : undefined;\n  //           outRoute.push({\n  //             amountIn: realAmountIn,\n  //             amountOut,\n  //             minAmountOut,\n  //             currentPrice: undefined,\n  //             executionPrice,\n  //             priceImpact,\n  //             fee,\n  //             routeType: \"route\",\n  //             poolKey: [iFromPool, iOutPool],\n  //             remainingAccounts,\n  //             minMiddleAmountFee,\n  //             middleToken,\n  //             poolReady: infoAPoolOpen && infoBPoolOpen,\n  //             poolType: [poolTypeA, poolTypeB],\n  //             feeConfig: _inFeeConfig,\n  //             expirationTime,\n  //           });\n  //         } catch (e) {\n  //           //\n  //         }\n  //       }\n  //     }\n  //   }\n  //   outRoute.sort((a, b) => (a.amountOut.amount.raw.sub(b.amountOut.amount.raw).gt(BN_ZERO) ? -1 : 1));\n  //   const isReadyRoutes = outRoute.filter((i) => i.poolReady);\n\n  //   return {\n  //     routes: outRoute,\n  //     best: isReadyRoutes.length ? isReadyRoutes[0] : outRoute[0],\n  //   };\n  // }\n\n  // private async computeAmountOut({\n  //   middleMintInfo,\n  //   amountIn,\n  //   currencyOut,\n  //   slippage,\n\n  //   fromPool,\n  //   toPool,\n  //   simulateCache,\n  //   tickCache,\n  //   mintInfos,\n  // }: {\n  //   middleMintInfo: { mint: PublicKey; decimals: number };\n  //   amountIn: TokenAmount;\n  //   currencyOut: Token;\n  //   slippage: Percent;\n  //   fromPool: PoolType;\n  //   toPool: PoolType;\n  //   simulateCache: ReturnTypeFetchMultipleInfo;\n  //   tickCache: ReturnTypeFetchMultiplePoolTickArrays;\n  //   mintInfos: ReturnTypeFetchMultipleMintInfos;\n  // }): Promise<{\n  //   minMiddleAmountFee: TokenAmount | undefined;\n  //   middleToken: Token;\n  //   realAmountIn: TransferAmountFee;\n  //   amountOut: TransferAmountFee;\n  //   minAmountOut: TransferAmountFee;\n  //   executionPrice: Price | null;\n  //   priceImpact: Fraction;\n  //   fee: TokenAmount[];\n  //   remainingAccounts: [PublicKey[] | undefined, PublicKey[] | undefined];\n  //   expirationTime: number | undefined;\n  // }> {\n  //   const epochInfo = await this.scope.fetchEpochInfo();\n  //   const middleToken = new Token(middleMintInfo);\n\n  //   let firstPriceImpact: Percent;\n  //   let firstFee: TokenAmount;\n  //   let firstRemainingAccounts: PublicKey[] | undefined = undefined;\n  //   let minMiddleAmountOut: TransferAmountFee;\n  //   let firstExpirationTime: number | undefined = undefined;\n  //   let realAmountIn: TransferAmountFee = {\n  //     amount: amountIn,\n  //     fee: undefined,\n  //     expirationTime: undefined,\n  //   };\n\n  //   const _slippage = new Percent(0, 100);\n\n  //   if (fromPool.version === 6) {\n  //     const {\n  //       minAmountOut: _minMiddleAmountOut,\n  //       priceImpact: _firstPriceImpact,\n  //       fee: _firstFee,\n  //       remainingAccounts: _firstRemainingAccounts,\n  //       expirationTime: _expirationTime,\n  //       realAmountIn: _realAmountIn,\n  //     } = await PoolUtils.computeAmountOutFormat({\n  //       poolInfo: fromPool as ClmmPoolInfo,\n  //       tickArrayCache: tickCache[fromPool.id.toString()],\n  //       amountIn,\n  //       tokenOut: middleToken,\n  //       slippage: _slippage,\n  //       epochInfo,\n  //       token2022Infos: mintInfos,\n  //     });\n  //     minMiddleAmountOut = _minMiddleAmountOut;\n  //     firstPriceImpact = _firstPriceImpact;\n  //     firstFee = _firstFee;\n  //     firstRemainingAccounts = _firstRemainingAccounts;\n  //     firstExpirationTime = _expirationTime;\n  //     realAmountIn = _realAmountIn;\n  //   } else {\n  //     const {\n  //       minAmountOut: _minMiddleAmountOut,\n  //       priceImpact: _firstPriceImpact,\n  //       fee: _firstFee,\n  //     } = this.scope.liquidity.computeAmountOut({\n  //       poolKeys: jsonInfo2PoolKeys(fromPool) as LiquidityPoolKeys,\n  //       poolInfo: simulateCache[fromPool.id as string],\n  //       amountIn,\n  //       outputToken: middleToken,\n  //       slippage: _slippage,\n  //     });\n  //     minMiddleAmountOut = {\n  //       amount: _minMiddleAmountOut,\n  //       fee: undefined,\n  //       expirationTime: undefined,\n  //     };\n  //     firstPriceImpact = _firstPriceImpact;\n  //     firstFee = _firstFee;\n  //   }\n\n  //   let amountOut: TransferAmountFee;\n  //   let minAmountOut: TransferAmountFee;\n  //   let secondPriceImpact: Percent;\n  //   let secondFee: TokenAmount;\n  //   let secondRemainingAccounts: PublicKey[] | undefined = undefined;\n  //   let secondExpirationTime: number | undefined = undefined;\n  //   let realAmountRouteIn: TransferAmountFee = minMiddleAmountOut;\n\n  //   if (toPool.version === 6) {\n  //     const {\n  //       amountOut: _amountOut,\n  //       minAmountOut: _minAmountOut,\n  //       priceImpact: _secondPriceImpact,\n  //       fee: _secondFee,\n  //       remainingAccounts: _secondRemainingAccounts,\n  //       expirationTime: _expirationTime,\n  //       realAmountIn: _realAmountIn,\n  //     } = await PoolUtils.computeAmountOutFormat({\n  //       poolInfo: toPool as ClmmPoolInfo,\n  //       tickArrayCache: tickCache[toPool.id.toString()],\n  //       amountIn: new TokenAmount(\n  //         (minMiddleAmountOut.amount as TokenAmount).token,\n  //         minMiddleAmountOut.amount.raw.sub(\n  //           minMiddleAmountOut.fee === undefined ? BN_ZERO : minMiddleAmountOut.fee.raw,\n  //         ),\n  //       ),\n  //       tokenOut: currencyOut,\n  //       slippage,\n  //       epochInfo,\n  //       token2022Infos: mintInfos,\n  //     });\n  //     amountOut = _amountOut;\n  //     minAmountOut = _minAmountOut;\n  //     secondPriceImpact = _secondPriceImpact;\n  //     secondFee = _secondFee;\n  //     secondRemainingAccounts = _secondRemainingAccounts;\n  //     secondExpirationTime = _expirationTime;\n  //     realAmountRouteIn = _realAmountIn;\n  //   } else {\n  //     const {\n  //       amountOut: _amountOut,\n  //       minAmountOut: _minAmountOut,\n  //       priceImpact: _secondPriceImpact,\n  //       fee: _secondFee,\n  //     } = this.scope.liquidity.computeAmountOut({\n  //       poolKeys: jsonInfo2PoolKeys(toPool) as LiquidityPoolKeys,\n  //       poolInfo: simulateCache[toPool.id as string],\n  //       amountIn: new TokenAmount(\n  //         minMiddleAmountOut.amount.token,\n  //         minMiddleAmountOut.amount.raw.sub(\n  //           minMiddleAmountOut.fee === undefined ? BN_ZERO : minMiddleAmountOut.fee.raw,\n  //         ),\n  //       ),\n  //       outputToken: currencyOut,\n  //       slippage,\n  //     });\n  //     amountOut = {\n  //       amount: _amountOut,\n  //       fee: undefined,\n  //       expirationTime: undefined,\n  //     };\n  //     minAmountOut = {\n  //       amount: _minAmountOut,\n  //       fee: undefined,\n  //       expirationTime: undefined,\n  //     };\n  //     secondPriceImpact = _secondPriceImpact;\n  //     secondFee = _secondFee;\n  //   }\n\n  //   let executionPrice: Price | null = null;\n  //   const amountInRaw = amountIn.raw;\n  //   const amountOutRaw = amountOut.amount.raw;\n  //   const currencyIn = amountIn.token;\n  //   if (!amountInRaw.isZero() && !amountOutRaw.isZero()) {\n  //     executionPrice = new Price({\n  //       baseToken: currencyIn,\n  //       denominator: amountInRaw,\n  //       quoteToken: currencyOut,\n  //       numerator: amountOutRaw,\n  //     });\n  //   }\n\n  //   return {\n  //     minMiddleAmountFee:\n  //       minMiddleAmountOut.fee !== undefined\n  //         ? new TokenAmount(\n  //             middleToken,\n  //             (minMiddleAmountOut.fee?.raw ?? new BN(0)).add(realAmountRouteIn.fee?.raw ?? new BN(0)),\n  //           )\n  //         : undefined,\n  //     middleToken,\n  //     realAmountIn,\n  //     amountOut,\n  //     minAmountOut,\n  //     executionPrice,\n  //     priceImpact: firstPriceImpact.add(secondPriceImpact),\n  //     fee: [firstFee, secondFee],\n  //     remainingAccounts: [firstRemainingAccounts, secondRemainingAccounts],\n  //     expirationTime: minExpirationTime(firstExpirationTime, secondExpirationTime),\n  //   };\n  // }\n\n  private async getWSolAccounts(): Promise<TokenAccount[]> {\n    this.scope.checkOwner();\n    await this.scope.account.fetchWalletTokenAccounts();\n    const tokenAccounts = this.scope.account.tokenAccounts.filter((acc) => acc.mint.equals(WSOLMint));\n    tokenAccounts.sort((a, b) => {\n      if (a.isAssociated) return 1;\n      if (b.isAssociated) return -1;\n      return a.amount.lt(b.amount) ? -1 : 1;\n    });\n    return tokenAccounts;\n  }\n\n  public async unWrapWSol(props: {\n    amount: BigNumberish;\n    computeBudgetConfig?: ComputeBudgetConfig;\n    tokenProgram?: PublicKey;\n  }): Promise<MakeTransaction> {\n    const { amount, tokenProgram } = props;\n    const tokenAccounts = await this.getWSolAccounts();\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addCustomComputeBudget(props.computeBudgetConfig);\n    const ins = await createWSolAccountInstructions({\n      connection: this.scope.connection,\n      owner: this.scope.ownerPubKey,\n      payer: this.scope.ownerPubKey,\n      amount: 0,\n    });\n    txBuilder.addInstruction(ins);\n\n    const amountBN = parseBigNumberish(amount);\n    for (let i = 0; i < tokenAccounts.length; i++) {\n      if (amountBN.gte(tokenAccounts[i].amount)) {\n        txBuilder.addInstruction({\n          instructions: [\n            closeAccountInstruction({\n              tokenAccount: tokenAccounts[i].publicKey!,\n              payer: this.scope.ownerPubKey,\n              owner: this.scope.ownerPubKey,\n              programId: tokenProgram,\n            }),\n          ],\n        });\n        amountBN.sub(tokenAccounts[i].amount);\n      } else {\n        txBuilder.addInstruction({\n          instructions: [\n            closeAccountInstruction({\n              tokenAccount: tokenAccounts[i].publicKey!,\n              payer: this.scope.ownerPubKey,\n              owner: this.scope.ownerPubKey,\n              programId: tokenProgram,\n            }),\n          ],\n        });\n        makeTransferInstruction({\n          destination: ins.addresses.newAccount,\n          source: tokenAccounts[i].publicKey!,\n          amount: amountBN,\n          owner: this.scope.ownerPubKey,\n          tokenProgram,\n        });\n      }\n    }\n\n    return txBuilder.build();\n  }\n\n  public async wrapWSol(amount: BigNumberish, tokenProgram?: PublicKey): Promise<MakeTransaction> {\n    const tokenAccounts = await this.getWSolAccounts();\n\n    const txBuilder = this.createTxBuilder();\n    const ins = await createWSolAccountInstructions({\n      connection: this.scope.connection,\n      owner: this.scope.ownerPubKey,\n      payer: this.scope.ownerPubKey,\n      amount,\n      skipCloseAccount: true,\n    });\n    txBuilder.addInstruction(ins);\n\n    if (tokenAccounts.length) {\n      // already have wsol account\n      txBuilder.addInstruction({\n        instructions: [\n          makeTransferInstruction({\n            // destination: ins.signers![0].publicKey,\n            destination: tokenAccounts[0].publicKey!,\n            source: ins.addresses.newAccount,\n            amount,\n            owner: this.scope.ownerPubKey,\n            tokenProgram,\n          }),\n        ],\n        endInstructions: [\n          closeAccountInstruction({\n            tokenAccount: ins.addresses.newAccount,\n            payer: this.scope.ownerPubKey,\n            owner: this.scope.ownerPubKey,\n            programId: tokenProgram,\n          }),\n        ],\n      });\n    }\n    return txBuilder.build();\n  }\n\n  public async swap({\n    swapInfo: orgSwapInfo,\n    associatedOnly,\n    checkCreateATAOwner,\n    checkTransaction,\n    routeProgram = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\"),\n  }: {\n    swapInfo: ComputeAmountOutLayout;\n    associatedOnly: boolean;\n    checkCreateATAOwner: boolean;\n    checkTransaction: boolean;\n    routeProgram: PublicKey;\n  }): Promise<MakeMultiTransaction> {\n    const swapInfo = {\n      ...orgSwapInfo,\n      amountIn: this.scope.solToWsolTransferAmountFee(orgSwapInfo.amountIn),\n      amountOut: this.scope.solToWsolTransferAmountFee(orgSwapInfo.amountOut),\n      minAmountOut: this.scope.solToWsolTransferAmountFee(orgSwapInfo.minAmountOut),\n      middleMint: (orgSwapInfo as ComputeAmountOutRouteLayout).minMiddleAmountFee\n        ? solToWSol((orgSwapInfo as ComputeAmountOutRouteLayout).middleToken.mint)\n        : undefined,\n    };\n    const amountIn = swapInfo.amountIn;\n    const amountOut = swapInfo.amountOut;\n    const useSolBalance =\n      amountIn.amount.token.mint.equals(Token.WSOL.mint) || amountIn.amount.token.mint.equals(SOLMint);\n    const outSolBalance =\n      amountOut.amount.token.mint.equals(Token.WSOL.mint) || amountOut.amount.token.mint.equals(SOLMint);\n    const inputMint = amountIn.amount.token.mint;\n    const middleMint = swapInfo.middleMint!;\n    const outputMint = amountOut.amount.token.mint;\n    const txBuilder = this.createTxBuilder();\n\n    const { account: sourceToken, instructionParams: sourceInstructionParams } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: inputMint,\n        notUseTokenAccount: useSolBalance,\n        createInfo: useSolBalance\n          ? {\n              payer: this.scope.ownerPubKey,\n              amount: amountIn.amount.raw,\n            }\n          : undefined,\n        owner: this.scope.ownerPubKey,\n        skipCloseAccount: !useSolBalance,\n        associatedOnly: useSolBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n    sourceInstructionParams && txBuilder.addInstruction(sourceInstructionParams);\n    if (sourceToken === undefined) throw Error(\"input account check error\");\n\n    const { account: destinationToken, instructionParams: destinationInstructionParams } =\n      await this.scope.account.getOrCreateTokenAccount({\n        mint: outputMint,\n        skipCloseAccount: !outSolBalance,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        owner: this.scope.ownerPubKey,\n        associatedOnly,\n        checkCreateATAOwner,\n      });\n    destinationInstructionParams && txBuilder.addInstruction(destinationInstructionParams);\n\n    let routeToken: PublicKey | undefined = undefined;\n    if (swapInfo.routeType === \"route\") {\n      const res = await this.scope.account.getOrCreateTokenAccount({\n        mint: middleMint,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        owner: this.scope.ownerPubKey,\n        associatedOnly: false,\n        checkCreateATAOwner,\n      });\n      routeToken = res.account;\n      res.instructionParams && txBuilder.addInstruction(res.instructionParams);\n    }\n\n    const ins = await makeSwapInstruction({\n      routeProgram,\n      inputMint,\n      swapInfo,\n      ownerInfo: {\n        wallet: this.scope.ownerPubKey,\n        sourceToken,\n        routeToken,\n        destinationToken: destinationToken!,\n      },\n    });\n\n    const transferIns =\n      swapInfo.feeConfig !== undefined\n        ? [\n            createTransferInstruction(\n              sourceToken,\n              swapInfo.feeConfig.feeAccount,\n              this.scope.ownerPubKey,\n              swapInfo.feeConfig.feeAmount.toNumber(),\n            ),\n          ]\n        : [];\n    const transferInsType = swapInfo.feeConfig !== undefined ? [InstructionType.TransferAmount] : [];\n\n    const instructions: TransactionInstruction[] = [];\n    const instructionsTypes: string[] = [];\n    const config = await txBuilder.getComputeBudgetConfig();\n    if (config) {\n      const { instructions: _ins, instructionTypes: _insType } = addComputeBudget(config);\n      instructions.push(..._ins);\n      instructionsTypes.push(..._insType);\n    }\n\n    const allTxBuilder: TxBuilder[] = [];\n    const tempIns = [\n      ...instructions,\n      ...transferIns,\n      ...txBuilder.AllTxData.instructions,\n      ...ins.instructions,\n      ...txBuilder.AllTxData.endInstructions,\n    ];\n    const tempInsType = [\n      ...instructionsTypes,\n      ...transferInsType,\n      ...txBuilder.AllTxData.instructionTypes,\n      ...ins.instructionTypes,\n      ...txBuilder.AllTxData.endInstructionTypes,\n    ];\n    const tempSigner = [...txBuilder.AllTxData.signers, ...ins.signers];\n    if (checkTransaction) {\n      if (forecastTransactionSize(tempIns, [this.scope.ownerPubKey, ...tempSigner.map((i) => i.publicKey)])) {\n        allTxBuilder.push(\n          this.createTxBuilder().addInstruction({\n            instructions: tempIns,\n            signers: tempSigner,\n            instructionTypes: tempInsType,\n          }),\n        );\n      } else {\n        if (txBuilder.AllTxData.instructions.length > 0) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: txBuilder.AllTxData.instructions,\n              signers: txBuilder.AllTxData.signers,\n              instructionTypes: txBuilder.AllTxData.instructionTypes,\n            }),\n          );\n        }\n        if (forecastTransactionSize([...instructions, ...transferIns, ...ins.instructions], [this.scope.ownerPubKey])) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: [...instructions, ...transferIns, ...ins.instructions],\n              signers: ins.signers,\n              instructionTypes: [...instructionsTypes, ...transferInsType, ...ins.instructionTypes],\n            }),\n          );\n        } else if (forecastTransactionSize([...instructions, ...ins.instructions], [this.scope.ownerPubKey])) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: [...instructions, ...ins.instructions],\n              signers: ins.signers,\n              instructionTypes: ins.instructionTypes,\n            }),\n          );\n        } else if (forecastTransactionSize(ins.instructions, [this.scope.ownerPubKey])) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: [...ins.instructions],\n              signers: ins.signers,\n              instructionTypes: ins.instructionTypes,\n            }),\n          );\n        } else {\n          for (let index = 0; index < ins.instructions.length; index++) {\n            allTxBuilder.push(\n              this.createTxBuilder().addInstruction({\n                instructions: [...instructions, ins.instructions[index]],\n                signers: ins.signers,\n                instructionTypes: [...instructionsTypes, ins.instructionTypes[index]],\n              }),\n            );\n          }\n        }\n        if (txBuilder.AllTxData.endInstructions.length > 0) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: txBuilder.AllTxData.endInstructions,\n              instructionTypes: txBuilder.AllTxData.endInstructionTypes,\n            }),\n          );\n        }\n      }\n    } else {\n      if (swapInfo.routeType === \"amm\") {\n        allTxBuilder.push(\n          this.createTxBuilder().addInstruction({\n            instructions: tempIns,\n            signers: tempSigner,\n            instructionTypes: tempInsType,\n          }),\n        );\n      } else {\n        if (txBuilder.AllTxData.instructions.length > 0) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: txBuilder.AllTxData.instructions,\n              signers: txBuilder.AllTxData.signers,\n              instructionTypes: txBuilder.AllTxData.instructionTypes,\n            }),\n          );\n        }\n        allTxBuilder.push(\n          this.createTxBuilder().addInstruction({\n            instructions: ins.instructions,\n            signers: ins.signers,\n            instructionTypes: ins.instructionTypes,\n          }),\n        );\n        if (txBuilder.AllTxData.endInstructions.length > 0) {\n          allTxBuilder.push(\n            this.createTxBuilder().addInstruction({\n              instructions: txBuilder.AllTxData.endInstructions,\n              instructionTypes: txBuilder.AllTxData.endInstructionTypes,\n            }),\n          );\n        }\n      }\n    }\n    const firstBuilder = allTxBuilder.shift()!;\n    return firstBuilder.buildMultiTx({ extraPreBuildData: allTxBuilder.map((builder) => builder.build()) });\n  }\n}\n","import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from \"@solana/spl-token\";\nimport { PublicKey, TransactionInstruction, SystemProgram, AccountMeta } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { ClmmInstrument, ONE, MIN_SQRT_PRICE_X64, MAX_SQRT_PRICE_X64, getPdaExBitmapAccount } from \"../clmm\";\nimport { InstructionType, jsonInfo2PoolKeys, MEMO_PROGRAM_ID } from \"@/common\";\nimport { struct, u64, u8 } from \"@/marshmallow\";\nimport { makeAMMSwapInstruction } from \"../liquidity/instruction\";\n\nimport { ApiV3PoolInfoItem, ApiV3PoolInfoConcentratedItem, PoolKeys, ClmmKeys, AmmV4Keys, AmmV5Keys } from \"@/api/type\";\nimport { ComputeAmountOutLayout, ReturnTypeMakeSwapInstruction } from \"./type\";\n\nexport function route1Instruction(\n  programId: PublicKey,\n  poolInfoA: ApiV3PoolInfoItem,\n  poolKeyA: PoolKeys,\n  poolKeyB: PoolKeys,\n\n  userSourceToken: PublicKey,\n  userRouteToken: PublicKey,\n  // userDestinationToken: PublicKey,\n  userPdaAccount: PublicKey,\n  ownerWallet: PublicKey,\n\n  inputMint: PublicKey,\n\n  amountIn: BN,\n  amountOut: BN,\n\n  tickArrayA?: PublicKey[],\n  // tickArrayB?: PublicKey[],\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"instruction\"), u64(\"amountIn\"), u64(\"amountOut\")]);\n\n  const keys: { pubkey: PublicKey; isSigner: boolean; isWritable: boolean }[] = [\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: new PublicKey(poolKeyA.programId), isSigner: false, isWritable: false },\n    { pubkey: new PublicKey(poolKeyA.id), isSigner: false, isWritable: true },\n    { pubkey: new PublicKey(poolKeyB.id), isSigner: false, isWritable: true },\n\n    { pubkey: userSourceToken, isSigner: false, isWritable: true },\n    { pubkey: userRouteToken, isSigner: false, isWritable: true },\n    { pubkey: userPdaAccount, isSigner: false, isWritable: true },\n    { pubkey: ownerWallet, isSigner: true, isWritable: false },\n  ];\n\n  if (poolInfoA.type === \"Concentrated\") {\n    const poolKey = jsonInfo2PoolKeys(poolKeyA as ClmmKeys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        {\n          pubkey: poolKey.mintA.address.equals(inputMint) ? poolKey.vault.A : poolKey.vault.B,\n          isSigner: false,\n          isWritable: true,\n        },\n        {\n          pubkey: poolKey.mintA.address.equals(inputMint) ? poolKey.vault.B : poolKey.vault.A,\n          isSigner: false,\n          isWritable: true,\n        },\n        // { pubkey: poolKey.observationId, isSigner: false, isWritable: true }, // to do\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        ...tickArrayA!.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n      ],\n    );\n  } else if (poolInfoA.pooltype.includes(\"StablePool\")) {\n    const poolKey = jsonInfo2PoolKeys(poolKeyA as AmmV5Keys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n        { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      ],\n    );\n  } else {\n    const poolKey = jsonInfo2PoolKeys(poolKeyA as AmmV4Keys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n        ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n          ? [\n              { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n              { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n            ]\n          : [\n              { pubkey: poolKey.id, isSigner: false, isWritable: true },\n              { pubkey: poolKey.id, isSigner: false, isWritable: true },\n            ]),\n      ],\n    );\n  }\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      instruction: 4,\n      amountIn,\n      amountOut,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data,\n  });\n}\n\nexport function route2Instruction(\n  programId: PublicKey,\n  poolInfoB: ApiV3PoolInfoItem,\n  poolKeyA: PoolKeys,\n  poolKeyB: PoolKeys,\n\n  // userSourceToken: PublicKey,\n  userRouteToken: PublicKey,\n  userDestinationToken: PublicKey,\n  userPdaAccount: PublicKey,\n  ownerWallet: PublicKey,\n\n  routeMint: PublicKey,\n\n  // tickArrayA?: PublicKey[],\n  tickArrayB?: PublicKey[],\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"instruction\")]);\n\n  const keys: { pubkey: PublicKey; isSigner: boolean; isWritable: boolean }[] = [\n    { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: new PublicKey(String(poolKeyB.programId)), isSigner: false, isWritable: false },\n    { pubkey: new PublicKey(String(poolKeyB.id)), isSigner: false, isWritable: true },\n    { pubkey: new PublicKey(String(poolKeyA.id)), isSigner: false, isWritable: true },\n\n    { pubkey: userRouteToken, isSigner: false, isWritable: true },\n    { pubkey: userDestinationToken, isSigner: false, isWritable: true },\n    { pubkey: userPdaAccount, isSigner: false, isWritable: true },\n    { pubkey: ownerWallet, isSigner: true, isWritable: false },\n  ];\n\n  if (poolInfoB.type === \"Concentrated\") {\n    const poolKey = jsonInfo2PoolKeys(poolKeyB as ClmmKeys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        {\n          pubkey: poolKey.mintA.address.equals(routeMint) ? poolKey.vault.A : poolKey.vault.B,\n          isSigner: false,\n          isWritable: true,\n        },\n        {\n          pubkey: poolKey.mintA.address.equals(routeMint) ? poolKey.vault.B : poolKey.vault.A,\n          isSigner: false,\n          isWritable: true,\n        },\n        // { pubkey: poolKey.observationId, isSigner: false, isWritable: true }, // to do\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        ...tickArrayB!.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n      ],\n    );\n  } else if (poolInfoB.pooltype.includes(\"StablePool\")) {\n    const poolKey = jsonInfo2PoolKeys(poolKeyB as AmmV5Keys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n        { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n        { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      ],\n    );\n  } else {\n    const poolKey = jsonInfo2PoolKeys(poolKeyB as AmmV4Keys);\n    keys.push(\n      ...[\n        { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n        { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: false },\n        { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n        { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n        { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n        ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n          ? [\n              { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n              { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n            ]\n          : [\n              { pubkey: poolKey.id, isSigner: false, isWritable: true },\n              { pubkey: poolKey.id, isSigner: false, isWritable: true },\n            ]),\n      ],\n    );\n  }\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      instruction: 5,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data,\n  });\n}\n\nfunction makeInnerInsKey(\n  itemPool: ApiV3PoolInfoItem,\n  itemPoolKey: PoolKeys,\n  inMint: string,\n  userInAccount: PublicKey,\n  userOutAccount: PublicKey,\n  remainingAccount: PublicKey[] | undefined,\n): AccountMeta[] {\n  if (itemPool.pooltype.includes(\"StablePool\")) {\n    const poolKey = jsonInfo2PoolKeys(itemPoolKey as AmmV5Keys);\n\n    return [\n      { pubkey: poolKey.programId, isSigner: false, isWritable: false },\n      { pubkey: userInAccount, isSigner: false, isWritable: true },\n      { pubkey: userOutAccount, isSigner: false, isWritable: true },\n\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n      { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n      { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n      { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n      { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n    ];\n  } else if (itemPool.type === \"Concentrated\") {\n    const pool = itemPool as ApiV3PoolInfoConcentratedItem;\n    const poolKey = jsonInfo2PoolKeys(itemPoolKey as ClmmKeys);\n    const baseIn = pool.mintA.address === inMint;\n    return [\n      { pubkey: new PublicKey(String(itemPool.programId)), isSigner: false, isWritable: false },\n      { pubkey: userInAccount, isSigner: false, isWritable: true },\n      { pubkey: userOutAccount, isSigner: false, isWritable: true },\n      { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      { pubkey: baseIn ? poolKey.vault.A : poolKey.vault.B, isSigner: false, isWritable: true },\n      { pubkey: baseIn ? poolKey.vault.B : poolKey.vault.A, isSigner: false, isWritable: true },\n      // { pubkey: itemPool.observationId, isSigner: false, isWritable: true }, // to do\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      ...(poolKey.mintA.programId.equals(TOKEN_2022_PROGRAM_ID) || poolKey.mintB.programId.equals(TOKEN_2022_PROGRAM_ID)\n        ? [\n            { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n            { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n            { pubkey: baseIn ? poolKey.mintA.address : poolKey.mintB.address, isSigner: false, isWritable: false },\n            { pubkey: baseIn ? poolKey.mintB.address : poolKey.mintA.address, isSigner: false, isWritable: false },\n          ]\n        : []),\n      ...(remainingAccount ?? []).map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n      {\n        pubkey: getPdaExBitmapAccount(new PublicKey(String(itemPool.programId)), new PublicKey(itemPool.id)).publicKey,\n        isSigner: false,\n        isWritable: true,\n      },\n    ];\n  } else {\n    const poolKey = jsonInfo2PoolKeys(itemPoolKey as AmmV4Keys);\n\n    return [\n      { pubkey: poolKey.programId, isSigner: false, isWritable: false },\n      { pubkey: userInAccount, isSigner: false, isWritable: true },\n      { pubkey: userOutAccount, isSigner: false, isWritable: true },\n\n      { pubkey: poolKey.id, isSigner: false, isWritable: true },\n      { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n      { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n      { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: false },\n\n      { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n      { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n      { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n      { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n      ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n        ? [\n            { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n            { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n          ]\n        : [\n            { pubkey: poolKey.id, isSigner: false, isWritable: true },\n            { pubkey: poolKey.id, isSigner: false, isWritable: true },\n          ]),\n    ];\n  }\n}\n\nexport function routeInstruction(\n  programId: PublicKey,\n  wallet: PublicKey,\n\n  userSourceToken: PublicKey,\n  userRouteToken: PublicKey,\n  userDestinationToken: PublicKey,\n\n  inputMint: string,\n  routeMint: string,\n\n  poolInfoA: ApiV3PoolInfoItem,\n  poolInfoB: ApiV3PoolInfoItem,\n\n  poolKeyA: PoolKeys,\n  poolKeyB: PoolKeys,\n\n  amountIn: BN,\n  amountOut: BN,\n\n  remainingAccounts: (PublicKey[] | undefined)[],\n): TransactionInstruction {\n  const dataLayout = struct([u8(\"instruction\"), u64(\"amountIn\"), u64(\"amountOut\")]);\n\n  const keys: { pubkey: PublicKey; isSigner: boolean; isWritable: boolean }[] = [\n    { pubkey: wallet, isSigner: true, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n  ];\n\n  keys.push(...makeInnerInsKey(poolInfoA, poolKeyA, inputMint, userSourceToken, userRouteToken, remainingAccounts[0]));\n\n  keys.push(\n    ...makeInnerInsKey(poolInfoB, poolKeyB, routeMint, userRouteToken, userDestinationToken, remainingAccounts[1]),\n  );\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      instruction: 8,\n      amountIn,\n      amountOut,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data,\n  });\n}\n\ntype MakeSwapInstructionParam = {\n  ownerInfo: {\n    wallet: PublicKey;\n    // tokenAccountA: PublicKey\n    // tokenAccountB: PublicKey\n\n    sourceToken: PublicKey;\n    routeToken?: PublicKey;\n    destinationToken: PublicKey;\n  };\n\n  inputMint: PublicKey;\n  routeProgram: PublicKey;\n\n  swapInfo: ComputeAmountOutLayout;\n};\n\nexport async function makeSwapInstruction({\n  routeProgram,\n  ownerInfo,\n  inputMint,\n  swapInfo,\n}: MakeSwapInstructionParam): Promise<ReturnTypeMakeSwapInstruction> {\n  if (swapInfo.routeType === \"amm\") {\n    if (swapInfo.poolInfo[0].type === \"Concentrated\") {\n      const _poolKey = jsonInfo2PoolKeys(swapInfo.poolKey[0] as ClmmKeys);\n      const sqrtPriceLimitX64 = inputMint.equals(_poolKey.mintA.address)\n        ? MIN_SQRT_PRICE_X64.add(ONE)\n        : MAX_SQRT_PRICE_X64.sub(ONE);\n\n      return await ClmmInstrument.makeSwapBaseInInstructions({\n        poolInfo: _poolKey as any,\n        poolKeys: _poolKey as any,\n        ownerInfo: {\n          wallet: ownerInfo.wallet,\n          tokenAccountA: _poolKey.mintA.address.equals(inputMint) ? ownerInfo.sourceToken : ownerInfo.destinationToken,\n          tokenAccountB: _poolKey.mintA.address.equals(inputMint) ? ownerInfo.destinationToken : ownerInfo.sourceToken,\n        },\n        inputMint,\n        amountIn: swapInfo.amountIn.amount.raw,\n        amountOutMin: swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n        sqrtPriceLimitX64,\n        remainingAccounts: swapInfo.remainingAccounts[0],\n      });\n    } else {\n      const _poolKey = swapInfo.poolKey[0] as AmmV4Keys | AmmV5Keys;\n\n      return {\n        signers: [],\n        instructions: [\n          makeAMMSwapInstruction({\n            poolKeys: _poolKey,\n            version: swapInfo.poolInfo[0].pooltype.includes(\"StablePool\") ? 5 : 4,\n            userKeys: {\n              tokenAccountIn: ownerInfo.sourceToken,\n              tokenAccountOut: ownerInfo.destinationToken,\n              owner: ownerInfo.wallet,\n            },\n            amountIn: swapInfo.amountIn.amount.raw,\n            amountOut: swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n            fixedSide: \"in\",\n          }),\n        ],\n        lookupTableAddress: _poolKey.lookupTableAccount ? [_poolKey.lookupTableAccount] : [],\n        instructionTypes: [\n          swapInfo.poolInfo[0].pooltype.includes(\"StablePool\")\n            ? InstructionType.AmmV5SwapBaseIn\n            : InstructionType.AmmV4SwapBaseIn,\n        ],\n        address: {},\n      };\n    }\n  } else if (swapInfo.routeType === \"route\") {\n    const poolInfo1 = swapInfo.poolInfo[0];\n    const poolInfo2 = swapInfo.poolInfo[1];\n    const poolKey1 = swapInfo.poolKey[0];\n    const poolKey2 = swapInfo.poolKey[1];\n\n    if (ownerInfo.routeToken === undefined) throw Error(\"owner route token account check error\");\n\n    return {\n      signers: [],\n      instructions: [\n        routeInstruction(\n          routeProgram,\n          ownerInfo.wallet,\n          ownerInfo.sourceToken,\n          ownerInfo.routeToken,\n          ownerInfo.destinationToken,\n\n          inputMint.toString(),\n          swapInfo.minMiddleAmountFee!.token.mint.toString(),\n\n          poolInfo1,\n          poolInfo2,\n          poolKey1,\n          poolKey2,\n\n          swapInfo.amountIn.amount.raw,\n          swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n\n          swapInfo.remainingAccounts,\n        ),\n      ],\n      instructionTypes: [InstructionType.RouteSwap],\n      lookupTableAddress: [poolKey1.lookupTableAccount, poolKey2.lookupTableAccount].filter(\n        (a) => a !== undefined,\n      ) as string[],\n      address: {},\n    };\n  } else {\n    throw Error(\"route type error\");\n  }\n}\n","import { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Connection, PublicKey, Signer, Transaction, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport ModuleBase from \"../moduleBase\";\nimport { findProgramAddress, forecastTransactionSize, getMultipleAccountsInfo } from \"@/common\";\nimport { Token } from \"@/module\";\nimport { blob, publicKey, seq, struct, u64, u8 } from \"@/marshmallow\";\n\nexport interface SHOW_INFO {\n  programId: PublicKey;\n  poolId: PublicKey;\n  ammId: PublicKey;\n  ownerAccountId: PublicKey;\n  snapshotLpAmount: BN;\n\n  openTime: number;\n  endTime: number;\n\n  project: typeof Utils1216.VERSION_PROJECT[number];\n\n  canClaim: boolean;\n  canClaimErrorType: canClaimErrorType;\n\n  tokenInfo: {\n    mintAddress: PublicKey;\n    mintVault: PublicKey;\n    mintDecimals: number;\n    perLpLoss: BN;\n    debtAmount: BN;\n  }[];\n}\n\nexport type canClaimErrorType = \"outOfOperationalTime\" | \"alreadyClaimIt\" | undefined;\n\nexport default class Utils1216 extends ModuleBase {\n  static CLAIMED_NUM = 3;\n  static POOL_LAYOUT = struct([\n    blob(8),\n    u8(\"bump\"),\n    u8(\"status\"),\n    u64(\"openTime\"),\n    u64(\"endTime\"),\n    publicKey(\"ammId\"),\n\n    seq(\n      struct([\n        u8(\"mintDecimals\"),\n        publicKey(\"mintAddress\"),\n        publicKey(\"mintVault\"),\n        u64(\"perLpLoss\"),\n        u64(\"totalClaimedAmount\"),\n      ]),\n      Utils1216.CLAIMED_NUM,\n      \"tokenInfo\",\n    ),\n    seq(u64(), 10, \"padding\"),\n  ]);\n\n  static OWNER_LAYOUT = struct([\n    blob(8),\n    u8(\"bump\"),\n    u8(\"version\"),\n    publicKey(\"poolId\"),\n    publicKey(\"owner\"),\n    u64(\"lpAmount\"),\n\n    seq(\n      struct([publicKey(\"mintAddress\"), u64(\"debtAmount\"), u64(\"claimedAmount\")]),\n      Utils1216.CLAIMED_NUM,\n      \"tokenInfo\",\n    ),\n    seq(u64(), 4, \"padding\"),\n  ]);\n\n  static DEFAULT_POOL_ID = [\n    \"58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2\",\n    \"6UmmUiYoBjSrhakAobJw8BvkmJtDVxaeBtbt7rxWo1mg\",\n    \"AVs9TA4nWDzfPJE9gGVNJMVhcQy3V9PGazuz33BfG2RA\",\n    \"DVa7Qmb5ct9RCpaU7UTpSaf3GVMYz17vNVU67XpdCRut\",\n    \"7XawhbbxtsRcQA8KTkHT9f9nc6d69UwqCDh6U5EEbEmX\",\n    \"6a1CsrpeZubDjEJE9s1CMVheB6HWM5d7m1cj2jkhyXhj\",\n    \"EoNrn8iUhwgJySD1pHu8Qxm5gSQqLK3za4m8xzD2RuEb\",\n    \"AceAyRTWt4PyB2pHqf2qhDgNZDtKVNaxgL8Ru3V4aN1P\",\n    \"6tmFJbMk5yVHFcFy7X2K8RwHjKLr6KVFLYXpgpBNeAxB\",\n  ].map((i) => new PublicKey(i));\n\n  static SEED_CONFIG = {\n    pool: {\n      id: Buffer.from(\"pool_seed\", \"utf8\"),\n    },\n    owner: {\n      id: Buffer.from(\"user_claim_seed\", \"utf8\"),\n    },\n  };\n\n  static VERSION_PROJECT = [undefined, \"Francium\", \"Tulip\", \"Larix\"] as const;\n\n  // pda\n  static getPdaPoolId(\n    programId: PublicKey,\n    ammId: PublicKey,\n  ): {\n    publicKey: PublicKey;\n    nonce: number;\n  } {\n    return findProgramAddress([Utils1216.SEED_CONFIG.pool.id, ammId.toBuffer()], programId);\n  }\n\n  static getPdaOwnerId(\n    programId: PublicKey,\n    poolId: PublicKey,\n    owner: PublicKey,\n    version: number,\n  ): {\n    publicKey: PublicKey;\n    nonce: number;\n  } {\n    return findProgramAddress(\n      [\n        Utils1216.SEED_CONFIG.owner.id,\n        poolId.toBuffer(),\n        owner.toBuffer(),\n        // new BN(version).toBuffer()\n        Buffer.from(new BN(version).toArray()),\n      ],\n      programId,\n    );\n  }\n\n  static async getAllInfo({\n    connection,\n    programId,\n    poolIds,\n    wallet,\n    chainTime,\n  }: {\n    connection: Connection;\n    programId: PublicKey;\n    poolIds: PublicKey[];\n    wallet: PublicKey;\n    chainTime: number;\n  }): Promise<SHOW_INFO[]> {\n    if (poolIds.length === 0) return [];\n\n    const allPoolPda = poolIds.map((id) => Utils1216.getPdaPoolId(programId, id).publicKey);\n\n    const allOwnerPda: PublicKey[] = [];\n    for (let itemVersion = 0; itemVersion < Utils1216.VERSION_PROJECT.length; itemVersion++) {\n      allOwnerPda.push(\n        ...allPoolPda.map((id) => Utils1216.getPdaOwnerId(programId, id, wallet, itemVersion).publicKey),\n      );\n    }\n\n    const pdaInfo = await getMultipleAccountsInfo(connection, [...allPoolPda, ...allOwnerPda]);\n\n    const info: SHOW_INFO[] = [];\n    for (let index = 0; index < pdaInfo.length; index++) {\n      const version = Math.floor(index / poolIds.length);\n      const i = index % poolIds.length;\n\n      const itemPoolId = allPoolPda[i];\n      const itemOwnerId = allOwnerPda[index];\n      const itemPoolInfoS = pdaInfo[i];\n      const itemOwnerInfoS = pdaInfo[poolIds.length + index];\n      if (!(itemPoolInfoS && itemOwnerInfoS)) continue;\n      if (\n        itemPoolInfoS.data.length !== Utils1216.POOL_LAYOUT.span ||\n        itemOwnerInfoS.data.length !== Utils1216.OWNER_LAYOUT.span\n      )\n        continue;\n\n      const itemPoolInfo = Utils1216.POOL_LAYOUT.decode(itemPoolInfoS.data);\n      const itemOwnerInfo = Utils1216.OWNER_LAYOUT.decode(itemOwnerInfoS.data);\n\n      const openTime = itemPoolInfo.openTime.toNumber();\n      const endTime = itemPoolInfo.endTime.toNumber();\n\n      const hasCanClaimToken =\n        itemOwnerInfo.tokenInfo.map((i) => i.debtAmount.gt(new BN(0))).filter((i) => !i).length !== 3;\n      const inCanClaimTime = chainTime > openTime && chainTime < endTime && itemPoolInfo.status === 1;\n\n      const canClaim = hasCanClaimToken && inCanClaimTime;\n\n      info.push({\n        programId,\n        poolId: itemPoolId,\n        ammId: itemPoolInfo.ammId,\n        ownerAccountId: itemOwnerId,\n        snapshotLpAmount: itemOwnerInfo.lpAmount,\n\n        project: Utils1216.VERSION_PROJECT[version],\n\n        openTime,\n        endTime,\n\n        canClaim,\n        canClaimErrorType: !hasCanClaimToken ? \"alreadyClaimIt\" : !inCanClaimTime ? \"outOfOperationalTime\" : undefined,\n\n        tokenInfo: itemPoolInfo.tokenInfo.map((itemPoolToken, i) => ({\n          mintAddress: itemPoolToken.mintAddress,\n          mintVault: itemPoolToken.mintVault,\n          mintDecimals: itemPoolToken.mintDecimals,\n          perLpLoss: itemPoolToken.perLpLoss,\n          debtAmount: itemOwnerInfo.tokenInfo[i].debtAmount.add(itemOwnerInfo.tokenInfo[i].claimedAmount),\n        })),\n      });\n    }\n\n    return info;\n  }\n\n  public async makeClaimTransaction({\n    poolInfo,\n    ownerInfo,\n  }: {\n    connection: Connection;\n    poolInfo: SHOW_INFO;\n    ownerInfo: {\n      wallet?: PublicKey;\n      associatedOnly: boolean;\n    };\n  }): Promise<\n    {\n      transaction: Transaction;\n      signer: Signer[];\n    }[]\n  > {\n    if (!ownerInfo.wallet) this.scope.checkOwner();\n    const txBuilder = this.createTxBuilder();\n    const wallet = ownerInfo.wallet || this.scope.ownerPubKey;\n\n    const ownerVaultList: PublicKey[] = [];\n    for (const itemToken of poolInfo.tokenInfo) {\n      const { account, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n        mint: itemToken.mintAddress,\n        owner: this.scope.ownerPubKey,\n        notUseTokenAccount: itemToken.mintAddress.equals(Token.WSOL.mint),\n        createInfo: {\n          payer: wallet,\n          amount: 0,\n        },\n        skipCloseAccount: !itemToken.mintAddress.equals(Token.WSOL.mint),\n\n        associatedOnly: itemToken.mintAddress.equals(Token.WSOL.mint) ? false : ownerInfo.associatedOnly,\n      });\n      instructionParams && txBuilder.addInstruction(instructionParams);\n      ownerVaultList.push(account!);\n    }\n\n    txBuilder.addInstruction({\n      instructions: [\n        Utils1216.makeClaimInstruction({\n          programId: poolInfo.programId,\n          poolInfo,\n          ownerInfo: {\n            wallet,\n            ownerPda: poolInfo.ownerAccountId,\n            claimAddress: ownerVaultList,\n          },\n        }),\n      ],\n    });\n    const { transaction, signers } = txBuilder.build();\n\n    return [\n      {\n        transaction,\n        signer: signers,\n      },\n    ];\n  }\n\n  public async makeClaimAllTransaction({\n    poolInfos,\n    ownerInfo,\n  }: {\n    poolInfos: SHOW_INFO[];\n    ownerInfo: {\n      wallet?: PublicKey;\n      associatedOnly: boolean;\n    };\n  }): Promise<\n    {\n      transaction: Transaction;\n      signer: Signer[];\n    }[]\n  > {\n    const txBuilder = this.createTxBuilder();\n    const wallet = ownerInfo.wallet || this.scope.ownerPubKey;\n\n    const tempNewVault: { [mint: string]: PublicKey } = {};\n\n    for (const poolInfo of poolInfos) {\n      const ownerVaultList: PublicKey[] = [];\n      for (const itemToken of poolInfo.tokenInfo) {\n        const { account: tempVault, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n          mint: itemToken.mintAddress,\n          owner: this.scope.ownerPubKey,\n          notUseTokenAccount: itemToken.mintAddress.equals(Token.WSOL.mint),\n          createInfo: {\n            payer: wallet,\n            amount: 0,\n          },\n          skipCloseAccount: !itemToken.mintAddress.equals(Token.WSOL.mint),\n\n          associatedOnly: itemToken.mintAddress.equals(Token.WSOL.mint) ? false : ownerInfo.associatedOnly,\n        });\n        instructionParams && txBuilder.addInstruction(instructionParams);\n\n        if (tempVault) {\n          tempNewVault[itemToken.mintAddress.toString()] = tempVault;\n          ownerVaultList.push(tempVault);\n        }\n      }\n\n      txBuilder.addInstruction({\n        instructions: [\n          Utils1216.makeClaimInstruction({\n            programId: poolInfo.programId,\n            poolInfo,\n            ownerInfo: {\n              wallet,\n              ownerPda: poolInfo.ownerAccountId,\n              claimAddress: ownerVaultList,\n            },\n          }),\n        ],\n      });\n    }\n\n    const { transaction, signers } = txBuilder.build();\n    const instructions = txBuilder.allInstructions;\n\n    if (forecastTransactionSize(instructions, [wallet, ...signers.map((s) => s.publicKey)])) {\n      return [\n        {\n          transaction,\n          signer: signers,\n        },\n      ];\n    } else {\n      return [\n        {\n          transaction: new Transaction().add(...instructions.slice(0, txBuilder.AllTxData.instructions.length - 1)),\n          signer: signers,\n        },\n        {\n          transaction: new Transaction().add(...instructions.slice(txBuilder.AllTxData.instructions.length - 1)),\n          signer: [],\n        },\n        { transaction: new Transaction().add(...txBuilder.AllTxData.endInstructions), signer: [] },\n      ];\n    }\n  }\n\n  static makeClaimInstruction({\n    programId,\n    poolInfo,\n    ownerInfo,\n  }: {\n    programId: PublicKey;\n\n    poolInfo: SHOW_INFO;\n    ownerInfo: {\n      wallet: PublicKey;\n      ownerPda: PublicKey;\n      claimAddress: PublicKey[];\n    };\n  }): TransactionInstruction {\n    const dataLayout = struct([]);\n\n    const keys = [\n      { pubkey: ownerInfo.wallet, isSigner: true, isWritable: true },\n      { pubkey: poolInfo.poolId, isSigner: false, isWritable: true },\n      { pubkey: ownerInfo.ownerPda, isSigner: false, isWritable: true },\n\n      ...ownerInfo.claimAddress.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n      ...poolInfo.tokenInfo.map(({ mintVault }) => ({ pubkey: mintVault, isSigner: false, isWritable: true })),\n\n      { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    ];\n\n    const data = Buffer.alloc(dataLayout.span);\n    dataLayout.encode({}, data);\n    const aData = Buffer.from([...[10, 66, 208, 184, 161, 6, 191, 98], ...data]);\n\n    return new TransactionInstruction({\n      keys,\n      programId,\n      data: aData,\n    });\n  }\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport BN from \"bn.js\";\nimport ModuleBase from \"../moduleBase\";\nimport { TxVersion } from \"@/common/txTool/txType\";\nimport { MakeTxData, TxBuildData, TxV0BuildData, MakeMultiTxData } from \"@/common/txTool/txTool\";\nimport { generatePubKey } from \"../account/util\";\nimport { BN_ZERO } from \"@/common/bignumber\";\nimport { makeCreateMarketInstruction } from \"./instrument\";\n\ninterface ExtInfo {\n  address: {\n    marketId: PublicKey;\n    requestQueue: PublicKey;\n    eventQueue: PublicKey;\n    bids: PublicKey;\n    asks: PublicKey;\n    baseVault: PublicKey;\n    quoteVault: PublicKey;\n    baseMint: PublicKey;\n    quoteMin: PublicKey;\n  };\n}\n\nexport default class MarketV2 extends ModuleBase {\n  public async create<T extends TxVersion>({\n    baseInfo,\n    quoteInfo,\n    lotSize, // 1\n    tickSize, // 0.01\n    dexProgramId,\n    txVersion,\n  }: {\n    baseInfo: {\n      mint: PublicKey;\n      decimals: number;\n    };\n    quoteInfo: {\n      mint: PublicKey;\n      decimals: number;\n    };\n    lotSize: number;\n    tickSize: number;\n    dexProgramId: PublicKey;\n    eventQueue?: PublicKey;\n    requestQueue?: PublicKey;\n    txVersion?: T;\n  }): Promise<MakeMultiTxData<T, ExtInfo>> {\n    const wallet = this.scope.ownerPubKey;\n    const market = generatePubKey({ fromPublicKey: wallet, programId: dexProgramId });\n    const requestQueue = generatePubKey({ fromPublicKey: wallet, programId: dexProgramId });\n    const eventQueue = generatePubKey({ fromPublicKey: wallet, programId: dexProgramId });\n    const bids = generatePubKey({ fromPublicKey: wallet, programId: dexProgramId });\n    const asks = generatePubKey({ fromPublicKey: wallet, programId: dexProgramId });\n    const baseVault = generatePubKey({ fromPublicKey: wallet, programId: TOKEN_PROGRAM_ID });\n    const quoteVault = generatePubKey({ fromPublicKey: wallet, programId: TOKEN_PROGRAM_ID });\n    const feeRateBps = 0;\n    const quoteDustThreshold = new BN(100);\n    function getVaultOwnerAndNonce() {\n      const vaultSignerNonce = new BN(0);\n      // eslint-disable-next-line no-constant-condition\n      while (true) {\n        try {\n          const vaultOwner = PublicKey.createProgramAddressSync(\n            [market.publicKey.toBuffer(), vaultSignerNonce.toArrayLike(Buffer, \"le\", 8)],\n            dexProgramId,\n          );\n          return { vaultOwner, vaultSignerNonce };\n        } catch (e) {\n          vaultSignerNonce.iaddn(1);\n          if (vaultSignerNonce.gt(new BN(25555))) throw Error(\"find vault owner error\");\n        }\n      }\n    }\n    const { vaultOwner, vaultSignerNonce } = getVaultOwnerAndNonce();\n    const baseLotSize = new BN(Math.round(10 ** baseInfo.decimals * lotSize));\n    const quoteLotSize = new BN(Math.round(lotSize * 10 ** quoteInfo.decimals * tickSize));\n\n    if (baseLotSize.eq(BN_ZERO)) throw Error(\"lot size is too small\");\n    if (quoteLotSize.eq(BN_ZERO)) throw Error(\"tick size or lot size is too small\");\n    const allTxArr = await makeCreateMarketInstruction({\n      connection: this.scope.connection,\n      wallet: this.scope.ownerPubKey,\n      marketInfo: {\n        programId: dexProgramId,\n        id: market,\n        baseMint: baseInfo.mint,\n        quoteMint: quoteInfo.mint,\n        baseVault,\n        quoteVault,\n        vaultOwner,\n        requestQueue,\n        eventQueue,\n        bids,\n        asks,\n\n        feeRateBps,\n        quoteDustThreshold,\n        vaultSignerNonce,\n        baseLotSize,\n        quoteLotSize,\n      },\n    });\n    const txBuilder = this.createTxBuilder();\n    txBuilder.addInstruction({\n      instructions: allTxArr[0].transaction.instructions,\n      signers: allTxArr[0].signer,\n    });\n\n    const extraTxBuildData: any[] = [];\n\n    for await (const txData of allTxArr.slice(1, allTxArr.length)) {\n      const extraTxBuilder = this.createTxBuilder();\n      extraTxBuilder.addInstruction({\n        instructions: txData.transaction.instructions,\n        signers: txData.signer,\n        instructionTypes: txData.instructionTypes,\n      });\n      const build = await extraTxBuilder.versionBuild({ txVersion });\n      extraTxBuildData.push(build);\n    }\n\n    return txBuilder.versionMultiBuild<T, ExtInfo>({\n      extraPreBuildData: extraTxBuildData,\n      extInfo: {\n        address: {\n          marketId: market.publicKey,\n          requestQueue: requestQueue.publicKey,\n          eventQueue: eventQueue.publicKey,\n          bids: bids.publicKey,\n          asks: asks.publicKey,\n          baseVault: baseVault.publicKey,\n          quoteVault: quoteVault.publicKey,\n          baseMint: new PublicKey(baseInfo.mint),\n          quoteMin: new PublicKey(quoteInfo.mint),\n        },\n      },\n      txVersion,\n    }) as Promise<MakeMultiTxData<T, ExtInfo>>;\n  }\n}\n","import { TransactionInstruction, SYSVAR_RENT_PUBKEY } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { createInitializeAccountInstruction } from \"@solana/spl-token\";\nimport { Connection, Keypair, PublicKey, SystemProgram, Transaction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { MARKET_STATE_LAYOUT_V2 } from \"./layout\";\nimport { struct, u16, u32, u64, u8 } from \"@/marshmallow\";\nimport { InstructionType } from \"@/common/txTool/txType\";\n\ntype Transactions = {\n  transaction: Transaction;\n  signer?: Keypair[] | undefined;\n  instructionTypes?: string[];\n}[];\n\nexport function initializeMarket({\n  programId,\n  marketInfo,\n}: {\n  programId: PublicKey;\n  marketInfo: {\n    id: PublicKey;\n    requestQueue: PublicKey;\n    eventQueue: PublicKey;\n    bids: PublicKey;\n    asks: PublicKey;\n    baseVault: PublicKey;\n    quoteVault: PublicKey;\n    baseMint: PublicKey;\n    quoteMint: PublicKey;\n    authority?: PublicKey;\n    pruneAuthority?: PublicKey;\n\n    baseLotSize: BN;\n    quoteLotSize: BN;\n    feeRateBps: number;\n    vaultSignerNonce: BN;\n    quoteDustThreshold: BN;\n  };\n}): TransactionInstruction {\n  const dataLayout = struct([\n    u8(\"version\"),\n    u32(\"instruction\"),\n    u64(\"baseLotSize\"),\n    u64(\"quoteLotSize\"),\n    u16(\"feeRateBps\"),\n    u64(\"vaultSignerNonce\"),\n    u64(\"quoteDustThreshold\"),\n  ]);\n\n  const keys = [\n    { pubkey: marketInfo.id, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.requestQueue, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.eventQueue, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.bids, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.asks, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.baseVault, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.quoteVault, isSigner: false, isWritable: true },\n    { pubkey: marketInfo.baseMint, isSigner: false, isWritable: false },\n    { pubkey: marketInfo.quoteMint, isSigner: false, isWritable: false },\n    // Use a dummy address if using the new dex upgrade to save tx space.\n    {\n      pubkey: marketInfo.authority ? marketInfo.quoteMint : SYSVAR_RENT_PUBKEY,\n      isSigner: false,\n      isWritable: false,\n    },\n  ]\n    .concat(marketInfo.authority ? { pubkey: marketInfo.authority, isSigner: false, isWritable: false } : [])\n    .concat(\n      marketInfo.authority && marketInfo.pruneAuthority\n        ? { pubkey: marketInfo.pruneAuthority, isSigner: false, isWritable: false }\n        : [],\n    );\n\n  const data = Buffer.alloc(dataLayout.span);\n  dataLayout.encode(\n    {\n      version: 0,\n      instruction: 0,\n      baseLotSize: marketInfo.baseLotSize,\n      quoteLotSize: marketInfo.quoteLotSize,\n      feeRateBps: marketInfo.feeRateBps,\n      vaultSignerNonce: marketInfo.vaultSignerNonce,\n      quoteDustThreshold: marketInfo.quoteDustThreshold,\n    },\n    data,\n  );\n\n  return new TransactionInstruction({\n    keys,\n    programId,\n    data,\n  });\n}\n\nexport async function makeCreateMarketInstruction({\n  connection,\n  wallet,\n  marketInfo,\n}: {\n  connection: Connection;\n  wallet: PublicKey;\n  marketInfo: {\n    programId: PublicKey;\n    id: { publicKey: PublicKey; seed: string };\n    baseMint: PublicKey;\n    quoteMint: PublicKey;\n    baseVault: { publicKey: PublicKey; seed: string };\n    quoteVault: { publicKey: PublicKey; seed: string };\n    vaultOwner: PublicKey;\n\n    requestQueue: { publicKey: PublicKey; seed: string };\n    eventQueue: { publicKey: PublicKey; seed: string };\n    bids: { publicKey: PublicKey; seed: string };\n    asks: { publicKey: PublicKey; seed: string };\n\n    feeRateBps: number;\n    vaultSignerNonce: BN;\n    quoteDustThreshold: BN;\n\n    baseLotSize: BN;\n    quoteLotSize: BN;\n  };\n}): Promise<Transactions> {\n  const tx1 = new Transaction();\n  const accountLamports = await connection.getMinimumBalanceForRentExemption(165);\n  tx1.add(\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.baseVault.seed,\n      newAccountPubkey: marketInfo.baseVault.publicKey,\n      lamports: accountLamports,\n      space: 165,\n      programId: TOKEN_PROGRAM_ID,\n    }),\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.quoteVault.seed,\n      newAccountPubkey: marketInfo.quoteVault.publicKey,\n      lamports: accountLamports,\n      space: 165,\n      programId: TOKEN_PROGRAM_ID,\n    }),\n    createInitializeAccountInstruction(marketInfo.baseVault.publicKey, marketInfo.baseMint, marketInfo.vaultOwner),\n    createInitializeAccountInstruction(marketInfo.quoteVault.publicKey, marketInfo.quoteMint, marketInfo.vaultOwner),\n  );\n\n  const tx2 = new Transaction();\n  tx2.add(\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.id.seed,\n      newAccountPubkey: marketInfo.id.publicKey,\n      lamports: await connection.getMinimumBalanceForRentExemption(MARKET_STATE_LAYOUT_V2.span),\n      space: MARKET_STATE_LAYOUT_V2.span,\n      programId: marketInfo.programId,\n    }),\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.requestQueue.seed,\n      newAccountPubkey: marketInfo.requestQueue.publicKey,\n      lamports: await connection.getMinimumBalanceForRentExemption(5120 + 12),\n      space: 5120 + 12,\n      programId: marketInfo.programId,\n    }),\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.eventQueue.seed,\n      newAccountPubkey: marketInfo.eventQueue.publicKey,\n      lamports: await connection.getMinimumBalanceForRentExemption(262144 + 12),\n      space: 262144 + 12,\n      programId: marketInfo.programId,\n    }),\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.bids.seed,\n      newAccountPubkey: marketInfo.bids.publicKey,\n      lamports: await connection.getMinimumBalanceForRentExemption(65536 + 12),\n      space: 65536 + 12,\n      programId: marketInfo.programId,\n    }),\n    SystemProgram.createAccountWithSeed({\n      fromPubkey: wallet,\n      basePubkey: wallet,\n      seed: marketInfo.asks.seed,\n      newAccountPubkey: marketInfo.asks.publicKey,\n      lamports: await connection.getMinimumBalanceForRentExemption(65536 + 12),\n      space: 65536 + 12,\n      programId: marketInfo.programId,\n    }),\n    initializeMarket({\n      programId: marketInfo.programId,\n      marketInfo: {\n        id: marketInfo.id.publicKey,\n        requestQueue: marketInfo.requestQueue.publicKey,\n        eventQueue: marketInfo.eventQueue.publicKey,\n        bids: marketInfo.bids.publicKey,\n        asks: marketInfo.asks.publicKey,\n        baseVault: marketInfo.baseVault.publicKey,\n        quoteVault: marketInfo.quoteVault.publicKey,\n        baseMint: marketInfo.baseMint,\n        quoteMint: marketInfo.quoteMint,\n\n        baseLotSize: marketInfo.baseLotSize,\n        quoteLotSize: marketInfo.quoteLotSize,\n        feeRateBps: marketInfo.feeRateBps,\n        vaultSignerNonce: marketInfo.vaultSignerNonce,\n        quoteDustThreshold: marketInfo.quoteDustThreshold,\n      },\n    }),\n  );\n\n  return [\n    {\n      transaction: tx1,\n      signer: [],\n      instructionTypes: [\n        InstructionType.CreateAccount,\n        InstructionType.CreateAccount,\n        InstructionType.InitAccount,\n        InstructionType.InitAccount,\n      ],\n    },\n    {\n      transaction: tx2,\n      signer: [],\n      instructionTypes: [\n        InstructionType.CreateAccount,\n        InstructionType.CreateAccount,\n        InstructionType.CreateAccount,\n        InstructionType.CreateAccount,\n        InstructionType.CreateAccount,\n        InstructionType.InitMarket,\n      ],\n    },\n  ];\n}\n","import { blob, publicKey, struct, u64, WideBits } from \"@/marshmallow\";\n\nfunction accountFlagsLayout(property = \"accountFlags\"): WideBits<string> {\n  const ACCOUNT_FLAGS_LAYOUT = new WideBits(property);\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"initialized\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"market\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"openOrders\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"requestQueue\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"eventQueue\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"bids\");\n  ACCOUNT_FLAGS_LAYOUT.addBoolean(\"asks\");\n  return ACCOUNT_FLAGS_LAYOUT;\n}\n\nexport const MARKET_STATE_LAYOUT_V2 = struct([\n  blob(5),\n  accountFlagsLayout(\"accountFlags\"),\n  publicKey(\"ownAddress\"),\n  u64(\"vaultSignerNonce\"),\n  publicKey(\"baseMint\"),\n  publicKey(\"quoteMint\"),\n  publicKey(\"baseVault\"),\n  u64(\"baseDepositsTotal\"),\n  u64(\"baseFeesAccrued\"),\n  publicKey(\"quoteVault\"),\n  u64(\"quoteDepositsTotal\"),\n  u64(\"quoteFeesAccrued\"),\n  u64(\"quoteDustThreshold\"),\n  publicKey(\"requestQueue\"),\n  publicKey(\"eventQueue\"),\n  publicKey(\"bids\"),\n  publicKey(\"asks\"),\n  u64(\"baseLotSize\"),\n  u64(\"quoteLotSize\"),\n  u64(\"feeRateBps\"),\n  u64(\"referrerRebatesAccrued\"),\n  blob(7),\n]);\n","import { PublicKey } from \"@solana/web3.js\";\nimport ModuleBase from \"../moduleBase\";\nimport { makeClaimInstruction, makeClaimInstructionV4 } from \"./instruction\";\nimport { jsonInfo2PoolKeys } from \"@/common/utility\";\nimport { OwnerIdoInfo, IdoKeysData } from \"@/api/type\";\nimport { IDO_ALL_PROGRAM } from \"@/common/programId\";\nimport { WSOLMint } from \"@/common/pubKey\";\nimport { TxVersion } from \"@/common/txTool/txType\";\nimport { MakeTxData } from \"@/common/txTool/txTool\";\nimport BN from \"bn.js\";\nimport { userInfo } from \"os\";\n\nconst PROGRAM_TO_VERSION = {\n  [IDO_ALL_PROGRAM.IDO_PROGRAM_ID_V1.toString()]: 1,\n  [IDO_ALL_PROGRAM.IDO_PROGRAM_ID_V2.toString()]: 2,\n  [IDO_ALL_PROGRAM.IDO_PROGRAM_ID_V3.toString()]: 3,\n  [IDO_ALL_PROGRAM.IDO_PROGRAM_ID_V4.toString()]: 4,\n};\n\nexport default class MarketV2 extends ModuleBase {\n  public async claim<T extends TxVersion>({\n    ownerInfo,\n    idoKeys,\n    associatedOnly = true,\n    checkCreateATAOwner = false,\n    txVersion,\n  }: {\n    ownerInfo: OwnerIdoInfo[keyof OwnerIdoInfo] & { userIdoInfo: string };\n    idoKeys: IdoKeysData;\n    associatedOnly?: boolean;\n    checkCreateATAOwner?: boolean;\n    txVersion?: T;\n  }): Promise<MakeTxData> {\n    const txBuilder = this.createTxBuilder();\n    const version = PROGRAM_TO_VERSION[idoKeys.programId];\n\n    if (!version) this.logAndCreateError(\"invalid version\", version);\n    const poolConfigKey = jsonInfo2PoolKeys(idoKeys);\n\n    const [hasUnClaimedProject, hasUnClaimedBuy] = [!new BN(ownerInfo.coin).isZero(), !new BN(ownerInfo.pc).isZero()];\n\n    const userProjectUseSolBalance = poolConfigKey.projectInfo.mint.address.equals(WSOLMint);\n    const { account: userProjectTokenAccount, instructionParams: userProjectInstructionParams } =\n      await this.scope.account.getOrCreateTokenAccount({\n        tokenProgram: poolConfigKey.projectInfo.mint.programId,\n        mint: poolConfigKey.projectInfo.mint.address,\n        owner: this.scope.ownerPubKey,\n        createInfo: {\n          payer: this.scope.ownerPubKey,\n          amount: 0,\n        },\n        skipCloseAccount: !userProjectUseSolBalance,\n        notUseTokenAccount: userProjectUseSolBalance,\n        associatedOnly: userProjectUseSolBalance ? false : associatedOnly,\n        checkCreateATAOwner,\n      });\n\n    if (!userProjectTokenAccount && hasUnClaimedProject)\n      this.logAndCreateError(\"target token accounts not found\", \"mint\", idoKeys.projectInfo.mint.address);\n    hasUnClaimedProject && userProjectInstructionParams && txBuilder.addInstruction(userProjectInstructionParams);\n\n    const buyMintUseSolBalance = poolConfigKey.buyInfo.mint.address.equals(WSOLMint);\n    const { account: userBuyTokenAccount, instructionParams } = await this.scope.account.getOrCreateTokenAccount({\n      tokenProgram: poolConfigKey.buyInfo.mint.programId,\n      mint: poolConfigKey.buyInfo.mint.address,\n      owner: this.scope.ownerPubKey,\n      createInfo: {\n        payer: this.scope.ownerPubKey,\n        amount: 0,\n      },\n      skipCloseAccount: !buyMintUseSolBalance,\n      notUseTokenAccount: buyMintUseSolBalance,\n      associatedOnly: buyMintUseSolBalance ? false : associatedOnly,\n      checkCreateATAOwner,\n    });\n    if (!userProjectTokenAccount && hasUnClaimedBuy)\n      this.logAndCreateError(\"target token accounts not found\", \"mint\", idoKeys.projectInfo.mint.address);\n    hasUnClaimedBuy && instructionParams && txBuilder.addInstruction(instructionParams);\n\n    if (!userProjectTokenAccount || !userBuyTokenAccount)\n      this.logAndCreateError(\n        \"target token accounts not found\",\n        \"mint\",\n        idoKeys.projectInfo.mint.address,\n        idoKeys.buyInfo.mint.address,\n      );\n\n    if (version === 3) {\n      return txBuilder\n        .addInstruction({\n          instructions: [\n            ...(hasUnClaimedProject\n              ? [\n                  makeClaimInstruction<\"3\">(\n                    { programId: poolConfigKey.programId },\n                    {\n                      idoId: poolConfigKey.id,\n                      authority: poolConfigKey.authority,\n                      poolTokenAccount: poolConfigKey.projectInfo.vault,\n                      userTokenAccount: userProjectTokenAccount!,\n                      userIdoInfo: new PublicKey(ownerInfo.userIdoInfo),\n                      userOwner: this.scope.ownerPubKey,\n                    },\n                  ),\n                ]\n              : []),\n            ...(hasUnClaimedBuy\n              ? [\n                  makeClaimInstruction<\"3\">(\n                    { programId: new PublicKey(idoKeys.programId) },\n                    {\n                      idoId: poolConfigKey.id,\n                      authority: poolConfigKey.authority,\n                      poolTokenAccount: poolConfigKey.buyInfo.vault,\n                      userTokenAccount: userBuyTokenAccount!,\n                      userIdoInfo: new PublicKey(ownerInfo.userIdoInfo),\n                      userOwner: this.scope.ownerPubKey,\n                    },\n                  ),\n                ]\n              : []),\n          ],\n        })\n        .versionBuild({ txVersion }) as Promise<MakeTxData>;\n    }\n    if (version < 3) {\n      if (!hasUnClaimedProject && !hasUnClaimedBuy) this.logAndCreateError(\"no claimable rewards\");\n      return txBuilder\n        .addInstruction({\n          instructions: [\n            makeClaimInstruction<\"\">(\n              { programId: poolConfigKey.programId },\n              {\n                idoId: poolConfigKey.id,\n                authority: poolConfigKey.authority,\n                poolQuoteTokenAccount: poolConfigKey.buyInfo.vault,\n                poolBaseTokenAccount: poolConfigKey.projectInfo.vault,\n                userQuoteTokenAccount: userBuyTokenAccount!,\n                userBaseTokenAccount: userProjectTokenAccount!,\n                userIdoInfo: new PublicKey(ownerInfo.userIdoInfo),\n                userOwner: this.scope.ownerPubKey,\n              },\n            ),\n          ],\n        })\n        .versionBuild({ txVersion }) as Promise<MakeTxData>;\n    }\n\n    const keys = {\n      poolConfig: {\n        id: poolConfigKey.id,\n        programId: poolConfigKey.programId,\n        authority: poolConfigKey.authority,\n        baseVault: poolConfigKey.projectInfo.vault,\n        quoteVault: poolConfigKey.buyInfo.vault,\n        baseToken: idoKeys.projectInfo.mint,\n        quoteToken: idoKeys.buyInfo.mint,\n      },\n      userKeys: {\n        baseTokenAccount: userProjectTokenAccount!,\n        quoteTokenAccount: userBuyTokenAccount!,\n        ledgerAccount: new PublicKey(ownerInfo.userIdoInfo),\n        owner: this.scope.ownerPubKey,\n      },\n    };\n\n    return txBuilder\n      .addInstruction({\n        instructions: [\n          ...(hasUnClaimedProject ? [makeClaimInstructionV4({ ...keys, side: \"base\" })] : []),\n          ...(hasUnClaimedBuy ? [makeClaimInstructionV4({ ...keys, side: \"quote\" })] : []),\n        ],\n      })\n      .versionBuild({ txVersion }) as Promise<MakeTxData>;\n  }\n}\n","import { PublicKey, TransactionInstruction, SYSVAR_CLOCK_PUBKEY } from \"@solana/web3.js\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { RENT_PROGRAM_ID, CLOCK_PROGRAM_ID } from \"@/common/pubKey\";\nimport {\n  PurchaseInstructionKeys,\n  ClaimInstructionKeysV3,\n  ClaimInstructionKeys,\n  IdoClaimInstructionParams,\n} from \"./type\";\nimport { purchaseLayout, claimLayout } from \"./layout\";\n\nexport function makePurchaseInstruction({\n  programId,\n  amount,\n  instructionKeys,\n}: {\n  programId: PublicKey;\n  amount: string | number;\n  instructionKeys: PurchaseInstructionKeys;\n}): TransactionInstruction {\n  const keys = [\n    // system\n    { pubkey: new PublicKey(\"11111111111111111111111111111111\"), isSigner: false, isWritable: false },\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: RENT_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: CLOCK_PROGRAM_ID, isSigner: false, isWritable: false },\n    // pubkeys\n    ...Object.entries(instructionKeys).map(([name, pubkey]) => ({\n      pubkey,\n      isSigner: name === \"userOwner\",\n      isWritable: ![\"authority\", \"userOwner\", \"userIdoCheck\", \"userStakeInfo\"].includes(name),\n    })),\n  ];\n\n  const data = Buffer.alloc(purchaseLayout.span);\n  purchaseLayout.encode({ instruction: 1, amount: Number(amount) }, data);\n\n  return new TransactionInstruction({ keys, programId, data });\n}\n\nexport function makeClaimInstruction<Version extends \"\" | \"3\" = \"\">(\n  { programId }: { programId: PublicKey },\n  instructionKeys: Version extends \"3\" ? ClaimInstructionKeysV3 : ClaimInstructionKeys,\n): TransactionInstruction {\n  const keys = [\n    { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n    { pubkey: CLOCK_PROGRAM_ID, isSigner: false, isWritable: false },\n    ...Object.entries(instructionKeys).map(([name, pubkey]) => ({\n      pubkey,\n      isSigner: name === \"userOwner\",\n      isWritable: ![\"authority\", \"userOwner\"].includes(name),\n    })),\n  ];\n\n  const data = Buffer.alloc(claimLayout.span);\n  claimLayout.encode({ instruction: 2 }, data);\n\n  return new TransactionInstruction({ keys, programId, data });\n}\n\nexport function makeClaimInstructionV4(params: IdoClaimInstructionParams): TransactionInstruction {\n  const { poolConfig, userKeys, side } = params;\n\n  const tokenAccount = side === \"base\" ? userKeys.baseTokenAccount : userKeys.quoteTokenAccount;\n  const vault = side === \"base\" ? poolConfig.baseVault : poolConfig.quoteVault;\n  const data = Buffer.alloc(claimLayout.span);\n  claimLayout.encode(\n    {\n      instruction: 2,\n    },\n    data,\n  );\n\n  const keys = [\n    {\n      pubkey: TOKEN_PROGRAM_ID,\n      isWritable: false,\n      isSigner: false,\n    },\n    {\n      pubkey: SYSVAR_CLOCK_PUBKEY,\n      isWritable: false,\n      isSigner: false,\n    },\n    // ido\n    {\n      pubkey: poolConfig.id,\n      isWritable: true,\n      isSigner: false,\n    },\n    {\n      pubkey: poolConfig.authority,\n      isWritable: false,\n      isSigner: false,\n    },\n    {\n      pubkey: vault,\n      isWritable: true,\n      isSigner: false,\n    },\n    // user\n    {\n      pubkey: tokenAccount,\n      isWritable: true,\n      isSigner: false,\n    },\n    {\n      pubkey: userKeys.ledgerAccount,\n      isWritable: true,\n      isSigner: false,\n    },\n    {\n      pubkey: userKeys.owner,\n      isWritable: false,\n      isSigner: true,\n    },\n  ];\n\n  return new TransactionInstruction({\n    programId: poolConfig.programId,\n    keys,\n    data,\n  });\n}\n","import { nu64, struct, u8 } from \"@/marshmallow\";\n\nexport const purchaseLayout = struct([u8(\"instruction\"), nu64(\"amount\")]);\nexport const claimLayout = struct([u8(\"instruction\")]);\n","import { MintLayout, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nimport { Price, Token, TokenAmount, Fraction } from \"@/module\";\nimport { PublicKeyish, validateAndParsePublicKey, SOLMint } from \"@/common/pubKey\";\nimport { BigNumberish, parseNumberInfo, toBN } from \"@/common/bignumber\";\nimport { JupTokenType } from \"@/api/type\";\nimport ModuleBase, { ModuleBaseProps } from \"../moduleBase\";\nimport { LoadParams } from \"../type\";\n\nimport { TokenInfo } from \"./type\";\nimport { SOL_INFO } from \"./constant\";\nimport BN from \"bn.js\";\n\nexport interface MintToTokenAmount {\n  token?: Token;\n  mint: PublicKeyish;\n  amount: BigNumberish;\n  decimalDone?: boolean;\n}\n\nexport default class TokenModule extends ModuleBase {\n  private _tokenList: TokenInfo[] = [];\n  private _tokenMap: Map<string, TokenInfo> = new Map();\n  private _blackTokenMap: Map<string, TokenInfo> = new Map();\n  private _tokenPrice: Map<string, Price> = new Map();\n  private _tokenPriceOrg: Map<string, number> = new Map();\n  private _tokenPriceFetched = { prevCount: 0, fetched: 0 };\n  private _mintGroup: { official: Set<string>; jup: Set<string>; extra: Set<string> } = {\n    official: new Set(),\n    jup: new Set(),\n    extra: new Set(),\n  };\n  private _extraTokenList: TokenInfo[] = [];\n\n  constructor(params: ModuleBaseProps) {\n    super(params);\n  }\n\n  public async load(params?: LoadParams & { fetchTokenPrice?: boolean; type?: JupTokenType }): Promise<void> {\n    this.checkDisabled();\n    const { forceUpdate = false, type = JupTokenType.Strict } = params || {};\n    const { mintList, blacklist } = await this.scope.fetchV3TokenList(forceUpdate);\n    const jup = await this.scope.fetchJupTokenList(type, forceUpdate);\n    // reset all data\n    this._tokenList = [];\n    this._tokenMap = new Map();\n    this._blackTokenMap = new Map();\n    this._mintGroup = { official: new Set(), jup: new Set(), extra: new Set() };\n\n    this._tokenMap.set(SOL_INFO.address, SOL_INFO);\n    this._mintGroup.official.add(SOL_INFO.address);\n    blacklist.forEach((token) => {\n      this._blackTokenMap.set(token.address, { ...token, priority: -1 });\n    });\n\n    mintList.forEach((token) => {\n      if (this._blackTokenMap.has(token.address)) return;\n      this._tokenMap.set(token.address, {\n        ...token,\n        type: \"raydium\",\n        priority: 2,\n        programId:\n          token.programId ??\n          (token.tags.includes(\"token-2022\") ? TOKEN_2022_PROGRAM_ID.toBase58() : TOKEN_PROGRAM_ID.toBase58()),\n      });\n      this._mintGroup.official.add(token.address);\n    });\n\n    jup.forEach((token) => {\n      if (this._blackTokenMap.has(token.address) || this._tokenMap.has(token.address)) return;\n      this._tokenMap.set(token.address, {\n        ...token,\n        type: \"jupiter\",\n        priority: 1,\n        programId:\n          token.programId ??\n          (token.tags.includes(\"token-2022\") ? TOKEN_2022_PROGRAM_ID.toBase58() : TOKEN_PROGRAM_ID.toBase58()),\n      });\n      this._mintGroup.jup.add(token.address);\n    });\n\n    this._extraTokenList.forEach((token) => {\n      if (this._blackTokenMap.has(token.address) || this._tokenMap.has(token.address)) return;\n      this._tokenMap.set(token.address, {\n        ...token,\n        type: \"extra\",\n        priority: 1,\n        programId:\n          token.programId || token.tags.includes(\"token-2022\")\n            ? TOKEN_2022_PROGRAM_ID.toBase58()\n            : TOKEN_PROGRAM_ID.toBase58(),\n      });\n      this._mintGroup.extra.add(token.address);\n    });\n\n    this._tokenList = Array.from(this._tokenMap).map((data) => data[1]);\n    // if (fetchTokenPrice) await this.fetchTokenPrices(forceUpdate);\n  }\n\n  get tokenList(): TokenInfo[] {\n    return this._tokenList;\n  }\n  get tokenMap(): Map<string, TokenInfo> {\n    return this._tokenMap;\n  }\n  get blackTokenMap(): Map<string, TokenInfo> {\n    return this._blackTokenMap;\n  }\n  get mintGroup(): { official: Set<string>; jup: Set<string> } {\n    return this._mintGroup;\n  }\n\n  /** === util functions === */\n\n  public async getChainTokenInfo(mint: PublicKeyish): Promise<{ token: Token; tokenInfo: TokenInfo }> {\n    const _mint = validateAndParsePublicKey({ publicKey: mint });\n    const mintStr = _mint.toBase58();\n    const mintSymbol = _mint.toString().substring(0, 6);\n    const isSol = _mint.equals(SOLMint);\n\n    if (isSol) {\n      return {\n        token: new Token({\n          decimals: SOL_INFO.decimals,\n          name: SOL_INFO.name,\n          symbol: SOL_INFO.symbol,\n          skipMint: true,\n          mint: \"\",\n        }),\n        tokenInfo: SOL_INFO,\n      };\n    }\n\n    const tokenInfo = await this.scope.api.getTokenInfo(_mint);\n    if (tokenInfo) {\n      this._mintGroup.extra.add(mintStr);\n      const fullInfo = { ...tokenInfo, priority: 2 };\n      this._tokenMap.set(mintStr, fullInfo);\n      return {\n        token: new Token({\n          mint: _mint,\n          decimals: tokenInfo.decimals,\n          symbol: tokenInfo.symbol || mintSymbol,\n          name: tokenInfo.name || mintSymbol,\n          isToken2022: tokenInfo.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n        }),\n        tokenInfo: fullInfo,\n      };\n    }\n\n    const info = await this.scope.connection.getAccountInfo(_mint);\n    if (!info) this.logAndCreateError(\"On chain token not found, mint:\", _mint.toBase58());\n\n    const data = MintLayout.decode(info!.data);\n\n    const fullInfo = {\n      chainId: 101,\n      address: mintStr,\n      programId: info!.owner.toBase58(),\n      logoURI: \"\",\n      symbol: mintSymbol,\n      name: mintSymbol,\n      decimals: data.decimals,\n      tags: [],\n      extensions: {},\n      priority: 0,\n    };\n\n    if (!this._tokenMap.has(mintStr)) {\n      this._mintGroup.extra.add(mintStr);\n      this._tokenMap.set(mintStr, fullInfo);\n    }\n\n    return {\n      token: new Token({\n        mint: _mint,\n        decimals: data.decimals,\n        symbol: mintSymbol,\n        name: mintSymbol,\n        isToken2022: info!.owner.equals(TOKEN_2022_PROGRAM_ID),\n      }),\n      tokenInfo: fullInfo,\n    };\n  }\n\n  public mintToToken(mint: PublicKeyish): Token {\n    const _mint = validateAndParsePublicKey({ publicKey: mint });\n    const tokenInfo = this._tokenMap.get(_mint.toBase58());\n    if (!tokenInfo)\n      this.logAndCreateError(\"token not found, mint:\", _mint.toBase58(), \", use getChainTokenInfo to get info instead\");\n    const { decimals, name, symbol } = tokenInfo!;\n    const isSol = _mint.equals(SOLMint);\n    return new Token({\n      decimals,\n      name,\n      symbol,\n      skipMint: isSol,\n      mint: isSol ? \"\" : mint,\n      isToken2022: tokenInfo!.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n    });\n  }\n\n  public mintToTokenAmount({ mint, amount, decimalDone, token }: MintToTokenAmount): TokenAmount {\n    const _token = token || this.mintToToken(mint);\n\n    if (decimalDone) {\n      const numberDetails = parseNumberInfo(amount);\n      const amountBigNumber = toBN(new Fraction(numberDetails.numerator, numberDetails.denominator));\n      return new TokenAmount(_token, amountBigNumber);\n    }\n    return new TokenAmount(_token, this.decimalAmount({ mint, amount, decimalDone }));\n  }\n\n  public decimalAmount({ mint, amount, token }: MintToTokenAmount): BN {\n    const numberDetails = parseNumberInfo(amount);\n    const _token = token || this.mintToToken(mint);\n    return toBN(new Fraction(numberDetails.numerator, numberDetails.denominator).mul(new BN(10 ** _token.decimals)));\n  }\n\n  public uiAmount({ mint, amount, token }: MintToTokenAmount): string {\n    const numberDetails = parseNumberInfo(amount);\n    const _token = token || this.mintToToken(mint);\n    if (!_token) return \"\";\n    return new Fraction(numberDetails.numerator, numberDetails.denominator)\n      .div(new BN(10 ** _token.decimals))\n      .toSignificant(_token.decimals);\n  }\n}\n"],"mappings":"omBAEA,gCCFA,sBCAA,wCACA,sBACA,iCACA,GAAM,OAAO,EAAG,EAUT,YAAa,CAGlB,YAAY,EAA+C,CACzD,KAAK,SAAW,EAAO,WAAa,OAAY,EAAO,SAAW,EAClE,KAAK,KAAO,EAAO,IACrB,IAEI,OAAM,EAAoB,CAC5B,KAAK,SAAW,CAClB,IACI,OAAe,CACjB,MAAO,IAAM,EAAE,IAAI,EAAE,OAAO,yBAAyB,CACvD,IACI,aAAqB,CACvB,MAAO,MAAK,IACd,CAEQ,WAAW,EAA0B,CAC3C,MAAO,IAAS,KAAK,QACvB,CAEO,SAAS,EAAe,CAC7B,MAAK,MAAK,WAAW,CAAc,EACnC,SAAQ,MAAM,KAAK,KAAM,KAAK,KAAM,mBAAoB,GAAG,CAAK,EACzD,MAFsC,IAG/C,CAEO,gBAAgB,EAAe,CAEpC,GAAM,GAAM,EAAM,IAAI,AAAC,GAAS,MAAO,IAAQ,SAAW,KAAK,UAAU,CAAG,EAAI,CAAI,EAAE,KAAK,IAAI,EAC/F,KAAM,IAAI,OAAM,CAAG,CACrB,CAEO,WAAW,EAAe,CAC/B,MAAK,MAAK,WAAW,CAAgB,EACrC,SAAQ,KAAK,KAAK,KAAM,KAAK,KAAM,qBAAsB,GAAG,CAAK,EAC1D,MAFwC,IAGjD,CAEO,QAAQ,EAAe,CAC5B,MAAK,MAAK,WAAW,CAAa,EAClC,SAAQ,KAAK,KAAK,KAAM,KAAK,KAAM,kBAAmB,GAAG,CAAK,EACvD,MAFqC,IAG9C,CAEO,SAAS,EAAe,CAC7B,MAAK,MAAK,WAAW,CAAc,EACnC,SA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