@cobaltx/sdk-v2
Version:
An SDK for building applications on top of CobaltX.
1 lines • 513 kB
Source Map (JSON)
{"version":3,"sources":["../../../../src/cobaltx/clmm/utils/tick.ts","../../../../../../node_modules/decimal.js/decimal.mjs","../../../../src/cobaltx/clmm/utils/constants.ts","../../../../src/cobaltx/clmm/utils/math.ts","../../../../src/common/transfer.ts","../../../../src/common/accountInfo.ts","../../../../src/common/logger.ts","../../../../src/common/bignumber.ts","../../../../src/module/amount.ts","../../../../src/module/formatter.ts","../../../../src/module/fraction.ts","../../../../src/common/constant.ts","../../../../src/cobaltx/token/constant.ts","../../../../src/config.ts","../../../../src/module/token.ts","../../../../src/common/pubKey.ts","../../../../src/module/percent.ts","../../../../src/module/price.ts","../../../../src/common/utility.ts","../../../../src/common/lodash.ts","../../../../src/common/pda.ts","../../../../src/common/txTool/txUtils.ts","../../../../src/common/programId.ts","../../../../src/common/txTool/lookupTable.ts","../../../../src/common/txTool/txTool.ts","../../../../src/cobaltx/clmm/utils/util.ts","../../../../src/cobaltx/clmm/utils/pda.ts","../../../../src/cobaltx/clmm/utils/pool.ts","../../../../src/marshmallow/index.ts","../../../../src/marshmallow/buffer-layout.ts","../../../../src/cobaltx/clmm/utils/tickQuery.ts","../../../../src/cobaltx/clmm/utils/tickarrayBitmap.ts","../../../../src/cobaltx/clmm/layout.ts","../../../../src/cobaltx/clmm/utils/position.ts"],"sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"../../../api/type\";\nimport { ClmmPoolInfo, TickArrayBitmapExtensionType } from \"../type\";\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { SqrtPriceMath, TickMath } from \"./math\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { TickQuery } from \"./tickQuery\";\n\nexport const TICK_ARRAY_SIZE = 60;\nexport const TICK_ARRAY_BITMAP_SIZE = 512;\n\nexport interface ReturnTypeGetTickPrice {\n tick: number;\n price: Decimal;\n tickSqrtPriceX64: BN;\n}\n\nexport interface ReturnTypeGetPriceAndTick {\n tick: number;\n price: Decimal;\n}\n\nexport type Tick = {\n tick: number;\n liquidityNet: BN;\n liquidityGross: BN;\n feeGrowthOutsideX64A: BN;\n feeGrowthOutsideX64B: BN;\n rewardGrowthsOutsideX64: BN[];\n};\n\nexport type TickArray = {\n address: PublicKey;\n poolId: PublicKey;\n startTickIndex: number;\n ticks: Tick[];\n initializedTickCount: number;\n};\n\nexport type TickState = {\n tick: number;\n liquidityNet: BN;\n liquidityGross: BN;\n feeGrowthOutsideX64A: BN;\n feeGrowthOutsideX64B: BN;\n tickCumulativeOutside: BN;\n secondsPerLiquidityOutsideX64: BN;\n secondsOutside: number;\n rewardGrowthsOutside: BN[];\n};\n\nexport type TickArrayState = {\n ammPool: PublicKey;\n startTickIndex: number;\n ticks: TickState[];\n initializedTickCount: number;\n};\n\nexport class TickUtils {\n public static getTickArrayAddressByTick(\n programId: PublicKey,\n poolId: PublicKey,\n tickIndex: number,\n tickSpacing: number,\n ): PublicKey {\n const startIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(programId, poolId, startIndex);\n return tickArrayAddress;\n }\n\n public static getTickOffsetInArray(tickIndex: number, tickSpacing: number): number {\n if (tickIndex % tickSpacing != 0) {\n throw new Error(\"tickIndex % tickSpacing not equal 0\");\n }\n const startTickIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n const offsetInArray = Math.floor((tickIndex - startTickIndex) / tickSpacing);\n if (offsetInArray < 0 || offsetInArray >= TICK_ARRAY_SIZE) {\n throw new Error(\"tick offset in array overflow\");\n }\n return offsetInArray;\n }\n\n public static getTickArrayBitIndex(tickIndex: number, tickSpacing: number): number {\n const ticksInArray = TickQuery.tickCount(tickSpacing);\n\n let startIndex: number = tickIndex / ticksInArray;\n if (tickIndex < 0 && tickIndex % ticksInArray != 0) {\n startIndex = Math.ceil(startIndex) - 1;\n } else {\n startIndex = Math.floor(startIndex);\n }\n return startIndex;\n }\n\n public static getTickArrayStartIndexByTick(tickIndex: number, tickSpacing: number): number {\n return this.getTickArrayBitIndex(tickIndex, tickSpacing) * TickQuery.tickCount(tickSpacing);\n }\n\n public static getTickArrayOffsetInBitmapByTick(tick: number, tickSpacing: number): number {\n const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n const compressed = Math.floor(tick / multiplier) + 512;\n return Math.abs(compressed);\n }\n\n public static checkTickArrayIsInitialized(\n bitmap: BN,\n tick: number,\n tickSpacing: number,\n ): {\n isInitialized: boolean;\n startIndex: number;\n } {\n const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n const compressed = Math.floor(tick / multiplier) + 512;\n const bitPos = Math.abs(compressed);\n return {\n isInitialized: bitmap.testn(bitPos),\n startIndex: (bitPos - 512) * multiplier,\n };\n }\n\n public static getNextTickArrayStartIndex(\n lastTickArrayStartIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n ): number {\n return zeroForOne\n ? lastTickArrayStartIndex - tickSpacing * TICK_ARRAY_SIZE\n : lastTickArrayStartIndex + tickSpacing * TICK_ARRAY_SIZE;\n }\n\n public static mergeTickArrayBitmap(bns: BN[]): BN {\n let b = new BN(0);\n for (let i = 0; i < bns.length; i++) {\n b = b.add(bns[i].shln(64 * i));\n }\n return b;\n }\n\n public static getInitializedTickArrayInRange(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: TickArrayBitmapExtensionType,\n tickSpacing: number,\n tickArrayStartIndex: number,\n expectedCount: number,\n ): number[] {\n const tickArrayOffset = Math.floor(tickArrayStartIndex / (tickSpacing * TICK_ARRAY_SIZE));\n return [\n // find right of currenct offset\n ...TickUtils.searchLowBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n tickArrayOffset - 1,\n expectedCount,\n tickSpacing,\n ),\n\n // find left of current offset\n ...TickUtils.searchHightBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n tickArrayOffset,\n expectedCount,\n tickSpacing,\n ),\n ];\n }\n\n public static getAllInitializedTickArrayStartIndex(\n tickArrayBitmap: BN[],\n exTickArrayBitmap: TickArrayBitmapExtensionType,\n tickSpacing: number,\n ): number[] {\n // find from offset 0 to 1024\n return TickUtils.searchHightBitFromStart(\n tickArrayBitmap,\n exTickArrayBitmap,\n 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","/*!\r\n * decimal.js v10.5.0\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2025 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|bigint|Decimal}\r\n * max {number|string|bigint|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 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 // See https://github.com/MikeMcl/decimal.js/pull/217\r\n x = new Ctor(1).minus(x).div(x.plus(1)).sqrt().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 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|bigint|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|bigint|Decimal}\r\n *\r\nP.max = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, -1);\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|bigint|Decimal}\r\n *\r\nP.min = function () {\r\n Array.prototype.push.call(arguments, this);\r\n return maxOrMin(this.constructor, arguments, 1);\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|bigint|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|bigint|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|bigint|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` (`n` is -1) and `min` (`n` is 1).\r\n */\r\nfunction maxOrMin(Ctor, args, n) {\r\n var k, 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\r\n // NaN?\r\n if (!y.s) {\r\n x = y;\r\n break;\r\n }\r\n\r\n k = x.cmp(y);\r\n\r\n if (k === n || k === 0 && x.s === n) {\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 // TODO BigInt str: no need to check for decimal point, exponential form or leading zeros.\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|bigint|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|bigint|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|bigint|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|bigint|Decimal}\r\n * y {number|string|bigint|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|bigint|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|bigint|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|bigint|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|bigint|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|bigint|Decimal} The y-coordinate.\r\n * x {number|string|bigint|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|bigint|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|bigint|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|bigint|Decimal}\r\n * min {number|string|bigint|Decimal}\r\n * max {number|string|bigint|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|bigint|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|bigint|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|bigint|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 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\r\n // Infinity or NaN?\r\n 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\r\n if (t === 'string') {\r\n if ((i = v.charCodeAt(0)) === 45) { // minus sign\r\n v = v.slice(1);\r\n x.s = -1;\r\n } else {\r\n if (i === 43) v = v.slice(1); // plus sign\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 if (t === 'bigint') {\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 return parseDecimal(x, v.toString());\r\n }\r\n\r\n throw Error(invalidArgument + 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|bigint|Decimal}\r\n * y {number|string|bigint|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|bigint|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|bigint|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|bigint|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|bigint|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|bigint|Decimal} The argument of the logarithm.\r\n * y {number|string|bigint|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|bigint|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|bigint|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|bigint|Decimal}\r\n *\r\n */\r\nfunction max() {\r\n return maxOrMin(this, arguments, -1);\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|bigint|Decimal}\r\n *\r\n */\r\nfunction min() {\r\n return maxOrMin(this, arguments, 1);\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|bigint|Decimal}\r\n * y {number|string|bigint|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|bigint|Decimal}\r\n * y {number|string|bigint|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|bigint|Decimal} The base.\r\n * y {number|string|bigint|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|bigint|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|bigint|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|bigint|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|bigint|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|bigint|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|bigint|Decimal}\r\n * y {number|string|bigint|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|bigint|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|bigint|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|bigint|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|bigint|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 BN from \"bn.js\";\n\nexport const ZERO = new BN(0);\nexport const ONE = new BN(1);\nexport const NEGATIVE_ONE = new BN(-1);\n\nexport const Q64 = new BN(1).shln(64);\nexport const Q128 = new BN(1).shln(128);\n\nexport const MaxU64 = Q64.sub(ONE);\n\nexport const U64Resolution = 64;\n\nexport const MaxUint128 = Q128.subn(1);\n\nexport const MIN_TICK = -443636;\nexport const MAX_TICK = -MIN_TICK;\n\nexport const MIN_SQRT_PRICE_X64: BN = new BN(\"4295048016\");\nexport const MAX_SQRT_PRICE_X64: BN = new BN(\"79226673521066979257578248091\");\n\nexport const MIN_SQRT_PRICE_X64_ADD_ONE: BN = new BN(\"4295048017\");\nexport const MAX_SQRT_PRICE_X64_SUB_ONE: BN = new BN(\"79226673521066979257578248090\");\n\n// export const MIN_TICK_ARRAY_START_INDEX = -307200;\n// export const MAX_TICK_ARRAY_START_INDEX = 306600;\n\nexport const BIT_PRECISION = 16;\nexport const LOG_B_2_X32 = \"59543866431248\";\nexport const LOG_B_P_ERR_MARGIN_LOWER_X64 = \"184467440737095516\";\nexport const LOG_B_P_ERR_MARGIN_UPPER_X64 = \"15793534762490258745\";\n\nexport const FEE_RATE_DENOMINATOR = new BN(10).pow(new BN(6));\n\nexport enum Fee {\n rate_500 = 500, // 500 / 10e6 = 0.0005\n rate_3000 = 3000, // 3000/ 10e6 = 0.003\n rate_10000 = 10000, // 10000 /10e6 = 0.01\n}\nexport const TICK_SPACINGS: { [amount in Fee]: number } = {\n [Fee.rate_500]: 10,\n [Fee.rate_3000]: 60,\n [Fee.rate_10000]: 200,\n};\n\nexport const mockCreatePoolInfo = {\n version: 6,\n liquidity: ZERO,\n tickCurrent: 0,\n feeGrowthGlobalX64A: ZERO,\n feeGrowthGlobalX64B: ZERO,\n protocolFeesTokenA: ZERO,\n protocolFeesTokenB: ZERO,\n swapInAmountTokenA: ZERO,\n swapOutAmountTokenB: ZERO,\n swapInAmountTokenB: ZERO,\n swapOutAmountTokenA: ZERO,\n tickArrayBitmap: [],\n\n rewardInfos: [],\n\n day: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n week: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n month: {\n volume: 0,\n volumeFee: 0,\n feeA: 0,\n feeB: 0,\n feeApr: 0,\n rewardApr: { A: 0, B: 0, C: 0 },\n apr: 0,\n priceMax: 0,\n priceMin: 0,\n },\n tvl: 0,\n};\n\nexport const mockV3CreatePoolInfo = {\n tvl: 0,\n volumeQuote: 0,\n mintAmountA: 0,\n mintAmountB: 0,\n rewardDefaultInfos: [],\n farmUpcomingCount: 0,\n farmOngoingCount: 0,\n farmFinishedCount: 0,\n\n day: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n week: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n month: {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [0],\n },\n pooltype: [],\n};\n\nexport const U64_IGNORE_RANGE = new BN(\"18446744073700000000\");\n","import { EpochInfo, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\n\nimport { ApiV3PoolInfoConcentratedItem } from \"../../../api/type\";\nimport { getTransferAmountFeeV2, minExpirationTime } from \"../../../common/transfer\";\nimport { ReturnTypeGetLiquidityAmountOut, TickArrayBitmapExtensionType } from \"../type\";\nimport {\n BIT_PRECISION,\n Fee,\n FEE_RATE_DENOMINATOR,\n LOG_B_2_X32,\n LOG_B_P_ERR_MARGIN_LOWER_X64,\n LOG_B_P_ERR_MARGIN_UPPER_X64,\n MAX_SQRT_PRICE_X64,\n MAX_TICK,\n MaxU64,\n MaxUint128,\n MIN_SQRT_PRICE_X64,\n MIN_TICK,\n NEGATIVE_ONE,\n ONE,\n Q128,\n Q64,\n U64Resolution,\n ZERO,\n} from \"./constants\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { PoolUtils } from \"./pool\";\nimport { Tick, TickArray, TickUtils } from \"./tick\";\nimport { TickQuery } from \"./tickQuery\";\n\nexport class MathUtil {\n public static mulDivRoundingUp(a: BN, b: BN, denominator: BN): BN {\n const numerator = a.mul(b);\n let result = numerator.div(denominator);\n if (!numerator.mod(denominator).eq(ZERO)) {\n result = result.add(ONE);\n }\n return result;\n }\n\n public static mulDivFloor(a: BN, b: BN, denominator: BN): BN {\n if (denominator.eq(ZERO)) {\n throw new Error(\"division by 0\");\n }\n return a.mul(b).div(denominator);\n }\n\n public static mulDivCeil(a: BN, b: BN, denominator: BN): BN {\n if (denominator.eq(ZERO)) {\n throw new Error(\"division by 0\");\n }\n const numerator = a.mul(b).add(denominator.sub(ONE));\n return numerator.div(denominator);\n }\n\n public static x64ToDecimal(num: BN, decimalPlaces?: number): Decimal {\n return new Decimal(num.toString()).div(Decimal.pow(2, 64)).toDecimalPlaces(decimalPlaces);\n }\n\n public static decimalToX64(num: Decimal): BN {\n return new BN(num.mul(Decimal.pow(2, 64)).floor().toFixed());\n }\n\n public static wrappingSubU128(n0: BN, n1: BN): BN {\n return n0.add(Q128).sub(n1).mod(Q128);\n }\n}\n\n// sqrt price math\nfunction mulRightShift(val: BN, mulBy: BN): BN {\n return signedRightShift(val.mul(mulBy), 64, 256);\n}\n\nfunction signedLeftShift(n0: BN, shiftBy: number, bitWidth: number): BN {\n const twosN0 = n0.toTwos(bitWidth).shln(shiftBy);\n twosN0.imaskn(bitWidth + 1);\n return twosN0.fromTwos(bitWidth);\n}\n\nfunction signedRightShift(n0: BN, shiftBy: number, bitWidth: number): BN {\n const twoN0 = n0.toTwos(bitWidth).shrn(shiftBy);\n twoN0.imaskn(bitWidth - shiftBy + 1);\n return twoN0.fromTwos(bitWidth - shiftBy);\n}\n\nexport class SqrtPriceMath {\n public static sqrtPriceX64ToPrice(sqrtPriceX64: BN, decimalsA: number, decimalsB: number): Decimal {\n return MathUtil.x64ToDecimal(sqrtPriceX64)\n .pow(2)\n .mul(Decimal.pow(10, decimalsA - decimalsB));\n }\n\n public static priceToSqrtPriceX64(price: Decimal, decimalsA: number, decimalsB: number): BN {\n return MathUtil.decimalToX64(price.mul(Decimal.pow(10, decimalsB - decimalsA)).sqrt());\n }\n\n public static getNextSqrtPriceX64FromInput(sqrtPriceX64: BN, liquidity: BN, amountIn: BN, zeroForOne: boolean): BN {\n if (!sqrtPriceX64.gt(ZERO)) {\n throw new Error(\"sqrtPriceX64 must greater than 0\");\n }\n if (!liquidity.gt(ZERO)) {\n throw new Error(\"liquidity must greater than 0\");\n }\n\n return zeroForOne\n ? this.getNextSqrtPriceFromTokenAmountARoundingUp(sqrtPriceX64, liquidity, amountIn, true)\n : this.getNextSqrtPriceFromTokenAmountBRoundingDown(sqrtPriceX64, liquidity, amountIn, true);\n }\n\n public static getNextSqrtPriceX64FromOutput(sqrtPriceX64: BN, liquidity: BN, amountOut: BN, zeroForOne: boolean): BN {\n if (!sqrtPriceX64.gt(ZERO)) {\n throw new Error(\"sqrtPriceX64 must greater than 0\");\n }\n if (!liquidity.gt(ZERO)) {\n throw new Error(\"liquidity must greater than 0\");\n }\n\n return zeroForOne\n ? this.getNextSqrtPriceFromTokenAmountBRoundingDown(sqrtPriceX64, liquidity, amountOut, false)\n : this.getNextSqrtPriceFromTokenAmountARoundingUp(sqrtPriceX64, liquidity, amountOut, false);\n }\n\n private static getNextSqrtPriceFromTokenAmountARoundingUp(\n sqrtPriceX64: BN,\n liquidity: BN,\n amount: BN,\n add: boolean,\n ): BN {\n if (amount.eq(ZERO)) return sqrtPriceX64;\n const liquidityLeftShift = liquidity.shln(U64Resolution);\n\n if (add) {\n const numerator1 = liquidityLeftShift;\n const denominator = liquidityLeftShift.add(amount.mul(sqrtPriceX64));\n if (denominator.gte(numerator1)) {\n return MathUtil.mulDivCeil(numerator1, sqrtPriceX64, denominator);\n }\n return MathUtil.mulDivRoundingUp(numerator1, ONE, numerator1.div(sqrtPriceX64).add(amount));\n } else {\n const amountMulSqrtPrice = amount.mul(sqrtPriceX64);\n if (!liquidityLeftShift.gt(amountMulSqrtPrice)) {\n throw new Error(\"getNextSqrtPriceFromTokenAmountARoundingUp,liquidityLeftShift must gt amountMulSqrtPrice\");\n }\n const denominator = liquidityLeftShift.sub(amountMulSqrtPrice);\n return MathUtil.mulDivCeil(liquidityLeftShift, sqrtPriceX64, denominator);\n }\n }\n\n private static getNextSqrtPriceFromTokenAmountBRoundingDown(\n sqrtPriceX64: BN,\n liquidity: BN,\n amount: BN,\n add: boolean,\n ): BN {\n const deltaY = amount.shln(U64Resolution);\n if (add) {\n return sqrtPriceX64.add(deltaY.div(liquidity));\n } else {\n const amountDivLiquidity = MathUtil.mulDivRoundingUp(deltaY, ONE, liquidity);\n if (!sqrtPriceX64.gt(amountDivLiquidity)) {\n throw new Error(\"getNextSqrtPriceFromTokenAmountBRoundingDown sqrtPriceX64 must gt amountDivLiquidity\");\n }\n return sqrtPriceX64.sub(amountDivLiquidity);\n }\n }\n\n public static getSqrtPriceX64FromTick(tick: number): BN {\n if (!Number.isInteger(tick)) {\n throw new Error(\"tick must be integer\");\n }\n if (tick < MIN_TICK || tick > MAX_TICK) {\n throw new Error(\"tick must be in MIN_TICK and MAX_TICK\");\n }\n const tickAbs: number = tick < 0 ? tick * -1 : tick;\n\n let ratio: BN = (tickAbs & 0x1) != 0 ? new BN(\"18445821805675395072\") : new BN(\"18446744073709551616\");\n if ((tickAbs & 0x2) != 0) ratio = mulRightShift(ratio, new BN(\"18444899583751176192\"));\n if ((tickAbs & 0x4) != 0) ratio = mulRightShift(ratio, new BN(\"18443055278223355904\"));\n if ((tickAbs & 0x8) != 0) ratio = mulRightShift(ratio, new BN(\"18439367220385607680\"));\n if ((tickAbs & 0x10) != 0) ratio = mulRightShift(ratio, new BN(\"18431993317065453568\"));\n if ((tickAbs & 0x20) != 0) ratio = mulRightShift(ratio, new BN(\"18417254355718170624\"));\n if ((tickAbs & 0x40) != 0) ratio = mulRightShift(ratio, new BN(\"18387811781193609216\"));\n if ((tickAbs & 0x80) != 0) ratio = mulRightShift(ratio, new BN(\"18329067761203558400\"));\n if ((tickAbs & 0x100) != 0) ratio = mulRightShift(ratio, new BN(\"18212142134806163456\"));\n if ((tickAbs & 0x200) != 0) ratio = mulRightShift(ratio, new BN(\"17980523815641700352\"));\n if ((tickAbs & 0x400) != 0) ratio = mulRightShift(ratio, new BN(\"17526086738831433728\"));\n if ((tickAbs & 0x800) != 0) ratio = mulRightShift(ratio, new BN(\"16651378430235570176\"));\n if ((tickAbs & 0x1000) != 0) ratio = mulRightShift(ratio, new BN(\"15030750278694412288\"));\n if ((tickAbs & 0x2000) != 0) ratio = mulRightShift(ratio, new BN(\"12247334978884435968\"));\n if ((tickAbs & 0x4000) != 0) ratio = mulRightShift(ratio, new BN(\"8131365268886854656\"));\n if ((tickAbs & 0x8000) != 0) ratio = mulRightShift(ratio, new BN(\"3584323654725218816\"));\n if ((tickAbs & 0x10000) != 0) ratio = mulRightShift(ratio, new BN(\"696457651848324352\"));\n if ((tickAbs & 0x20000) != 0) ratio = mulRightShift(ratio, new BN(\"26294789957507116\"));\n if ((tickAbs & 0x40000) != 0) ratio = mulRightShift(ratio, new BN(\"37481735321082\"));\n\n if (tick > 0) ratio = MaxUint128.div(ratio);\n return ratio;\n }\n\n public static getTickFromPrice(price: Decimal, decimalsA: number, decimalsB: number): number {\n return SqrtPriceMath.getTickFromSqrtPriceX64(SqrtPriceMath.priceToSqrtPriceX64(price, decimalsA, decimalsB));\n }\n\n public static getTickFromSqrtPriceX64(sqrtPriceX64: BN): number {\n if (sqrtPriceX64.gt(MAX_SQRT_PRICE_X64) || sqrtPriceX64.lt(MIN_SQRT_PRICE_X64)) {\n throw new Error(\"Provided sqrtPrice is not within the supported sqrtPrice range.\");\n }\n\n const msb = sqrtPriceX64.bitLength() - 1;\n const adjustedMsb = new BN(msb - 64);\n const log2pIntegerX32 = signedLeftShift(adjustedMsb, 32, 128);\n\n let bit = new BN(\"8000000000000000\", \"hex\");\n let precision = 0;\n let log2pFractionX64 = new BN(0);\n\n let r = msb >= 64 ? sqrtPriceX64.shrn(msb - 63) : sqrtPriceX64.shln(63 - msb);\n\n while (bit.gt(new BN(0)) && precision < BIT_PRECISION) {\n r = r.mul(r);\n const rMoreThanTwo = r.shrn(127);\n r = r.shrn(63 + rMoreThanTwo.toNumber());\n log2pFractionX64 = log2pFractionX64.add(bit.mul(rMoreThanTwo));\n bit = bit.shrn(1);\n precision += 1;\n }\n\n const log2pFractionX32 = log2pFractionX64.shrn(32);\n\n const log2pX32 = log2pIntegerX32.add(log2pFractionX32);\n const logbpX64 = log2pX32.mul(new BN(LOG_B_2_X32));\n\n const tickLow = signedRightShift(logbpX64.sub(new BN(LOG_B_P_ERR_MARGIN_LOWER_X64)), 64, 128).toNumber();\n const tickHigh = signedRightShift(logbpX64.add(new BN(LOG_B_P_ERR_MARGIN_UPPER_X64)), 64, 128).toNumber();\n\n if (tickLow == tickHigh) {\n return tickLow;\n } else {\n const derivedTickHighSqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tickHigh);\n return derivedTickHighSqrtPriceX64.lte(sqrtPriceX64) ? tickHigh : tickLow;\n }\n }\n}\n\n// tick math\nexport class TickMath {\n public static getTickWithPriceAndTickspacing(\n price: Decimal,\n tickSpacing: number,\n mintDecimalsA: number,\n mintDecimalsB: number,\n ): number {\n const tick = SqrtPriceMath.getTickFromSqrtPriceX64(\n SqrtPriceMath.priceToSqrtPriceX64(price, mintDecimalsA, mintDecimalsB),\n );\n let result = tick / tickSpacing;\n if (result < 0) {\n result = Math.floor(result);\n } else {\n result = Math.ceil(result);\n }\n return result * tickSpacing;\n }\n\n public static roundPriceWithTickspacing(\n price: Decimal,\n tickSpacing: number,\n mintDecimalsA: number,\n mintDecimalsB: number,\n ): Decimal {\n const tick = TickMath.getTickWithPriceAndTickspacing(price, tickSpacing, mintDecimalsA, mintDecimalsB);\n const sqrtPriceX64 = SqrtPriceMath.getSqrtPriceX64FromTick(tick);\n return SqrtPriceMath.sqrtPriceX64ToPrice(sqrtPriceX64, mintDecimalsA, mintDecimalsB);\n }\n}\n\nexport class LiquidityMath {\n public static addDelta(x: BN, y: BN): BN {\n return x.add(y);\n }\n\n public static getTokenAmountAFromLiquidity(\n sqrtPriceX64A: BN,\n sqrtPriceX64B: BN,\n liquidity: BN,\n roundUp: boolean,\n ): BN {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n\n if (!sqrtPriceX64A.gt(ZERO)) {\n throw new Error(\"sqrtPriceX64A must greater than 0\");\n }\n\n const numerator1 = liquidity.ushln(U64Resolution);\n const numerator2 = sqrtPriceX64B.sub(sqrtPriceX64A);\n\n return roundUp\n ? MathUtil.mulDivRoundingUp(MathUtil.mulDivCeil(numerator1, numerator2, sqrtPriceX64B), ONE, sqrtPriceX64A)\n : MathUtil.mulDivFloor(numerator1, numerator2, sqrtPriceX64B).div(sqrtPriceX64A);\n }\n\n public static getTokenAmountBFromLiquidity(\n sqrtPriceX64A: BN,\n sqrtPriceX64B: BN,\n liquidity: BN,\n roundUp: boolean,\n ): BN {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n if (!sqrtPriceX64A.gt(ZERO)) {\n throw new Error(\"sqrtPriceX64A must greater than 0\");\n }\n\n return roundUp\n ? MathUtil.mulDivCeil(liquidity, sqrtPriceX64B.sub(sqrtPriceX64A), Q64)\n : MathUtil.mulDivFloor(liquidity, sqrtPriceX64B.sub(sqrtPriceX64A), Q64);\n }\n\n public static getLiquidityFromTokenAmountA(sqrtPriceX64A: BN, sqrtPriceX64B: BN, amountA: BN, roundUp: boolean): BN {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n\n const numerator = amountA.mul(sqrtPriceX64A).mul(sqrtPriceX64B);\n const denominator = sqrtPriceX64B.sub(sqrtPriceX64A);\n const result = numerator.div(denominator);\n\n if (roundUp) {\n return MathUtil.mulDivRoundingUp(result, ONE, MaxU64);\n } else {\n return result.shrn(U64Resolution);\n }\n }\n\n public static getLiquidityFromTokenAmountB(sqrtPriceX64A: BN, sqrtPriceX64B: BN, amountB: BN): BN {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n return MathUtil.mulDivFloor(amountB, MaxU64, sqrtPriceX64B.sub(sqrtPriceX64A));\n }\n\n public static getLiquidityFromTokenAmounts(\n sqrtPriceCurrentX64: BN,\n sqrtPriceX64A: BN,\n sqrtPriceX64B: BN,\n amountA: BN,\n amountB: BN,\n ): BN {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n\n if (sqrtPriceCurrentX64.lte(sqrtPriceX64A)) {\n return LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceX64A, sqrtPriceX64B, amountA, false);\n } else if (sqrtPriceCurrentX64.lt(sqrtPriceX64B)) {\n const liquidity0 = LiquidityMath.getLiquidityFromTokenAmountA(sqrtPriceCurrentX64, sqrtPriceX64B, amountA, false);\n const liquidity1 = LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceCurrentX64, amountB);\n return liquidity0.lt(liquidity1) ? liquidity0 : liquidity1;\n } else {\n return LiquidityMath.getLiquidityFromTokenAmountB(sqrtPriceX64A, sqrtPriceX64B, amountB);\n }\n }\n\n public static getAmountsFromLiquidity(\n sqrtPriceCurrentX64: BN,\n sqrtPriceX64A: BN,\n sqrtPriceX64B: BN,\n liquidity: BN,\n roundUp: boolean,\n ): { amountA: BN; amountB: BN } {\n if (sqrtPriceX64A.gt(sqrtPriceX64B)) {\n [sqrtPriceX64A, sqrtPriceX64B] = [sqrtPriceX64B, sqrtPriceX64A];\n }\n\n if (sqrtPriceCurrentX64.lte(sqrtPriceX64A)) {\n return {\n amountA: LiquidityMath.getTokenAmountAFromLiquidity(sqrtPriceX64A, sqrtPriceX64B, liquidity, roundUp),\n amountB: new BN(0),\n };\n } else if (sqrtPriceCurrentX64.lt(sqrtPriceX64B)) {\n const amountA = LiquidityMath.getTokenAmountAFromLiquidity(\n sqrtPriceCurrentX64,\n sqrtPriceX64B,\n liquidity,\n roundUp,\n );\n const amountB = LiquidityMath.getTokenAmountBFromLiquidity(\n sqrtPriceX64A,\n sqrtPriceCurrentX64,\n liquidity,\n roundUp,\n );\n return { amountA, amountB };\n } else {\n return {\n amountA: new BN(0),\n amountB: LiquidityMath.getTokenAmountBFromLiquidity(sqrtPriceX64A, sqrtPriceX64B, liquidity, roundUp),\n };\n }\n }\n\n public static getAmountsFromLiquidityWithSlippage(\n sqrtPriceCurrentX64: BN,\n sqrtPriceX64A: BN,\n sqrtPriceX64B: BN,\n liquidity: BN,\n amountMax: boolean,\n roundUp: boolean,\n amountSlippage: number,\n ): { amountSlippageA: BN; amountSlippageB: BN } {\n const { amountA, amountB } = LiquidityMath.getAmountsFromLiquidity(\n sqrtPriceCurrentX64,\n sqrtPriceX64A,\n sqrtPriceX64B,\n liquidity,\n roundUp,\n );\n const coefficient = amountMax ? 1 + amountSlippage : 1 - amountSlippage;\n\n const amount0Slippage = new BN(new Decimal(amountA.toString()).mul(coefficient).toFixed(0));\n const amount1Slippage = new BN(new Decimal(amountB.toString()).mul(coefficient).toFixed(0));\n return {\n amountSlippageA: amount0Slippage,\n amountSlippageB: amount1Slippage,\n };\n }\n\n public static getAmountsOutFromLiquidity({\n poolInfo,\n tickLower,\n tickUpper,\n liquidity,\n slippage,\n add,\n epochInfo,\n amountAddFee,\n }: {\n poolInfo: ApiV3PoolInfoConcentratedItem;\n tickLower: number;\n tickUpper: number;\n liquidity: BN;\n slippage: number;\n add: boolean;\n\n epochInfo: EpochInfo;\n amountAddFee: boolean;\n }): ReturnTypeGetLiquidityAmountOut {\n const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n new Decimal(poolInfo.price),\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(tickLower);\n const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(tickUpper);\n\n const coefficientRe = add ? 1 + slippage : 1 - slippage;\n\n const amounts = LiquidityMath.getAmountsFromLiquidity(sqrtPriceX64, sqrtPriceX64A, sqrtPriceX64B, liquidity, add);\n\n const [amountA, amountB] = [\n getTransferAmountFeeV2(amounts.amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, amountAddFee),\n getTransferAmountFeeV2(amounts.amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, amountAddFee),\n ];\n const [amountSlippageA, amountSlippageB] = [\n getTransferAmountFeeV2(\n new BN(new Decimal(amounts.amountA.toString()).mul(coefficientRe).toFixed(0)),\n poolInfo.mintA.extensions?.feeConfig,\n epochInfo,\n amountAddFee,\n ),\n getTransferAmountFeeV2(\n new BN(new Decimal(amounts.amountB.toString()).mul(coefficientRe).toFixed(0)),\n poolInfo.mintB.extensions?.feeConfig,\n epochInfo,\n amountAddFee,\n ),\n ];\n\n return {\n liquidity,\n amountA,\n amountB,\n amountSlippageA,\n amountSlippageB,\n expirationTime: minExpirationTime(amountA.expirationTime, amountB.expirationTime),\n };\n }\n}\n\n// swap math\n\ntype SwapStep = {\n sqrtPriceX64Next: BN;\n amountIn: BN;\n amountOut: BN;\n feeAmount: BN;\n};\n\nexport interface StepComputations {\n sqrtPriceStartX64: BN;\n tickNext: number;\n initialized: boolean;\n sqrtPriceNextX64: BN;\n amountIn: BN;\n amountOut: BN;\n feeAmount: BN;\n}\n\nexport abstract class SwapMath {\n public static swapCompute(\n programId: PublicKey,\n poolId: PublicKey,\n tickArrayCache: { [key: string]: TickArray },\n tickArrayBitmap: BN[],\n tickarrayBitmapExtension: TickArrayBitmapExtensionType,\n zeroForOne: boolean,\n fee: number,\n liquidity: BN,\n currentTick: number,\n tickSpacing: number,\n currentSqrtPriceX64: BN,\n amountSpecified: BN,\n lastSavedTickArrayStartIndex: number,\n sqrtPriceLimitX64?: BN,\n catchLiquidityInsufficient = false,\n ): {\n allTrade: boolean;\n amountSpecifiedRemaining: BN;\n amountCalculated: BN;\n feeAmount: BN;\n sqrtPriceX64: BN;\n liquidity: BN;\n tickCurrent: number;\n accounts: PublicKey[];\n } {\n if (amountSpecified.eq(ZERO)) {\n throw new Error(\"amountSpecified must not be 0\");\n }\n if (!sqrtPriceLimitX64) sqrtPriceLimitX64 = zeroForOne ? MIN_SQRT_PRICE_X64.add(ONE) : MAX_SQRT_PRICE_X64.sub(ONE);\n\n if (zeroForOne) {\n if (sqrtPriceLimitX64.lt(MIN_SQRT_PRICE_X64)) {\n throw new Error(\"sqrtPriceX64 must greater than MIN_SQRT_PRICE_X64\");\n }\n\n if (sqrtPriceLimitX64.gte(currentSqrtPriceX64)) {\n throw new Error(\"sqrtPriceX64 must smaller than current\");\n }\n } else {\n if (sqrtPriceLimitX64.gt(MAX_SQRT_PRICE_X64)) {\n throw new Error(\"sqrtPriceX64 must smaller than MAX_SQRT_PRICE_X64\");\n }\n\n if (sqrtPriceLimitX64.lte(currentSqrtPriceX64)) {\n throw new Error(\"sqrtPriceX64 must greater than current\");\n }\n }\n const baseInput = amountSpecified.gt(ZERO);\n\n const state = {\n amountSpecifiedRemaining: amountSpecified,\n amountCalculated: ZERO,\n sqrtPriceX64: currentSqrtPriceX64,\n tick:\n currentTick > lastSavedTickArrayStartIndex\n ? Math.min(lastSavedTickArrayStartIndex + TickQuery.tickCount(tickSpacing) - 1, currentTick)\n : lastSavedTickArrayStartIndex,\n accounts: [] as PublicKey[],\n liquidity,\n feeAmount: new BN(0),\n };\n let tickAarrayStartIndex = lastSavedTickArrayStartIndex;\n let tickArrayCurrent = tickArrayCache[lastSavedTickArrayStartIndex];\n let loopCount = 0;\n let t = !zeroForOne && tickArrayCurrent.startTickIndex === state.tick;\n while (\n !state.amountSpecifiedRemaining.eq(ZERO) &&\n !state.sqrtPriceX64.eq(sqrtPriceLimitX64)\n // state.tick < MAX_TICK &&\n // state.tick > MIN_TICK\n ) {\n if (loopCount > 10) {\n // throw Error('liquidity limit')\n }\n const step: Partial<StepComputations> = {};\n step.sqrtPriceStartX64 = state.sqrtPriceX64;\n\n const tickState: Tick | null = TickUtils.nextInitTick(tickArrayCurrent, state.tick, tickSpacing, zeroForOne, t);\n\n let nextInitTick: Tick | null = tickState ? tickState : null; // TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne)\n let tickArrayAddress: null | PublicKey = null;\n\n if (!nextInitTick?.liquidityGross.gtn(0)) {\n const nextInitTickArrayIndex = PoolUtils.nextInitializedTickArrayStartIndex(\n {\n tickCurrent: state.tick,\n tickSpacing,\n tickArrayBitmap,\n exBitmapInfo: tickarrayBitmapExtension,\n },\n tickAarrayStartIndex,\n zeroForOne,\n );\n if (!nextInitTickArrayIndex.isExist) {\n if (catchLiquidityInsufficient) {\n return {\n allTrade: false,\n amountSpecifiedRemaining: state.amountSpecifiedRemaining,\n amountCalculated: state.amountCalculated,\n feeAmount: state.feeAmount,\n sqrtPriceX64: state.sqrtPriceX64,\n liquidity: state.liquidity,\n tickCurrent: state.tick,\n accounts: state.accounts,\n };\n }\n throw Error(\"swapCompute LiquidityInsufficient\");\n }\n tickAarrayStartIndex = nextInitTickArrayIndex.nextStartIndex;\n\n const { publicKey: expectedNextTickArrayAddress } = getPdaTickArrayAddress(\n programId,\n poolId,\n tickAarrayStartIndex,\n );\n tickArrayAddress = expectedNextTickArrayAddress;\n tickArrayCurrent = tickArrayCache[tickAarrayStartIndex];\n\n try {\n nextInitTick = TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne);\n } catch (e) {\n throw Error(\"not found next tick info\");\n }\n }\n\n step.tickNext = nextInitTick.tick;\n step.initialized = nextInitTick.liquidityGross.gtn(0);\n if (lastSavedTickArrayStartIndex !== tickAarrayStartIndex && tickArrayAddress) {\n state.accounts.push(tickArrayAddress);\n lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n }\n if (step.tickNext < MIN_TICK) {\n step.tickNext = MIN_TICK;\n } else if (step.tickNext > MAX_TICK) {\n step.tickNext = MAX_TICK;\n }\n\n step.sqrtPriceNextX64 = SqrtPriceMath.getSqrtPriceX64FromTick(step.tickNext);\n let targetPrice: BN;\n if (\n (zeroForOne && step.sqrtPriceNextX64.lt(sqrtPriceLimitX64)) ||\n (!zeroForOne && step.sqrtPriceNextX64.gt(sqrtPriceLimitX64))\n ) {\n targetPrice = sqrtPriceLimitX64;\n } else {\n targetPrice = step.sqrtPriceNextX64;\n }\n [state.sqrtPriceX64, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.swapStepCompute(\n state.sqrtPriceX64,\n targetPrice,\n state.liquidity,\n state.amountSpecifiedRemaining,\n fee,\n );\n\n state.feeAmount = state.feeAmount.add(step.feeAmount);\n\n if (baseInput) {\n state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.sub(step.amountIn.add(step.feeAmount));\n state.amountCalculated = state.amountCalculated.sub(step.amountOut);\n } else {\n state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.add(step.amountOut);\n state.amountCalculated = state.amountCalculated.add(step.amountIn.add(step.feeAmount));\n }\n if (state.sqrtPriceX64.eq(step.sqrtPriceNextX64)) {\n if (step.initialized) {\n let liquidityNet = nextInitTick.liquidityNet;\n if (zeroForOne) liquidityNet = liquidityNet.mul(NEGATIVE_ONE);\n state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n }\n\n t = step.tickNext != state.tick && !zeroForOne && tickArrayCurrent.startTickIndex === step.tickNext;\n state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext; //\n } else if (state.sqrtPriceX64 != step.sqrtPriceStartX64) {\n const _T = SqrtPriceMath.getTickFromSqrtPriceX64(state.sqrtPriceX64);\n t = _T != state.tick && !zeroForOne && tickArrayCurrent.startTickIndex === _T;\n state.tick = _T;\n }\n ++loopCount;\n }\n\n try {\n const { nextStartIndex: tickAarrayStartIndex, isExist } = TickQuery.nextInitializedTickArray(\n state.tick,\n tickSpacing,\n zeroForOne,\n tickArrayBitmap,\n tickarrayBitmapExtension,\n );\n if (isExist && lastSavedTickArrayStartIndex !== tickAarrayStartIndex) {\n state.accounts.push(getPdaTickArrayAddress(programId, poolId, tickAarrayStartIndex).publicKey);\n lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n }\n } catch (e) {\n /* empty */\n }\n\n return {\n allTrade: true,\n amountSpecifiedRemaining: ZERO,\n amountCalculated: state.amountCalculated,\n feeAmount: state.feeAmount,\n sqrtPriceX64: state.sqrtPriceX64,\n liquidity: state.liquidity,\n tickCurrent: state.tick,\n accounts: state.accounts,\n };\n }\n // public static swapCompute(\n // programId: PublicKey,\n // poolId: PublicKey,\n // tickArrayCache: { [key: string]: TickArray },\n // tickArrayBitmap: BN[],\n // tickarrayBitmapExtension: TickArrayBitmapExtensionType,\n // zeroForOne: boolean,\n // fee: number,\n // liquidity: BN,\n // currentTick: number,\n // tickSpacing: number,\n // currentSqrtPriceX64: BN,\n // amountSpecified: BN,\n // lastSavedTickArrayStartIndex: number,\n // sqrtPriceLimitX64?: BN,\n // ): {\n // amountCalculated: BN;\n // feeAmount: BN;\n // sqrtPriceX64: BN;\n // liquidity: BN;\n // tickCurrent: number;\n // accounts: PublicKey[];\n // } {\n // if (amountSpecified.eq(ZERO)) {\n // throw new Error(\"amountSpecified must not be 0\");\n // }\n // if (!sqrtPriceLimitX64) sqrtPriceLimitX64 = zeroForOne ? MIN_SQRT_PRICE_X64.add(ONE) : MAX_SQRT_PRICE_X64.sub(ONE);\n\n // if (zeroForOne) {\n // if (sqrtPriceLimitX64.lt(MIN_SQRT_PRICE_X64)) {\n // throw new Error(\"sqrtPriceX64 must greater than MIN_SQRT_PRICE_X64\");\n // }\n\n // if (sqrtPriceLimitX64.gte(currentSqrtPriceX64)) {\n // throw new Error(\"sqrtPriceX64 must smaller than current\");\n // }\n // } else {\n // if (sqrtPriceLimitX64.gt(MAX_SQRT_PRICE_X64)) {\n // throw new Error(\"sqrtPriceX64 must smaller than MAX_SQRT_PRICE_X64\");\n // }\n\n // if (sqrtPriceLimitX64.lte(currentSqrtPriceX64)) {\n // throw new Error(\"sqrtPriceX64 must greater than current\");\n // }\n // }\n // const baseInput = amountSpecified.gt(ZERO);\n\n // const state = {\n // amountSpecifiedRemaining: amountSpecified,\n // amountCalculated: ZERO,\n // sqrtPriceX64: currentSqrtPriceX64,\n // tick:\n // currentTick > lastSavedTickArrayStartIndex\n // ? Math.min(lastSavedTickArrayStartIndex + TickQuery.tickCount(tickSpacing) - 1, currentTick)\n // : lastSavedTickArrayStartIndex,\n // accounts: [] as PublicKey[],\n // liquidity,\n // feeAmount: new BN(0),\n // };\n // let tickAarrayStartIndex = lastSavedTickArrayStartIndex;\n // let tickArrayCurrent = tickArrayCache[lastSavedTickArrayStartIndex];\n // let loopCount = 0;\n // while (\n // !state.amountSpecifiedRemaining.eq(ZERO) &&\n // !state.sqrtPriceX64.eq(sqrtPriceLimitX64)\n // // state.tick < MAX_TICK &&\n // // state.tick > MIN_TICK\n // ) {\n // if (loopCount > 10) {\n // throw Error(\"liquidity limit\");\n // }\n // const step: Partial<StepComputations> = {};\n // step.sqrtPriceStartX64 = state.sqrtPriceX64;\n\n // const tickState: Tick | null = TickUtils.nextInitTick(tickArrayCurrent, state.tick, tickSpacing, zeroForOne);\n\n // let nextInitTick: Tick | null = tickState ? tickState : null; // TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne)\n // let tickArrayAddress: PublicKey | null = null;\n\n // if (!nextInitTick?.liquidityGross.gtn(0)) {\n // const nextInitTickArrayIndex = PoolUtils.nextInitializedTickArrayStartIndex(\n // {\n // tickCurrent: state.tick,\n // tickSpacing,\n // tickArrayBitmap,\n // exBitmapInfo: tickarrayBitmapExtension,\n // },\n // tickAarrayStartIndex,\n // zeroForOne,\n // );\n // if (!nextInitTickArrayIndex.isExist) {\n // throw Error(\"swapCompute LiquidityInsufficient\");\n // }\n // tickAarrayStartIndex = nextInitTickArrayIndex.nextStartIndex;\n\n // const { publicKey: expectedNextTickArrayAddress } = getPdaTickArrayAddress(\n // programId,\n // poolId,\n // tickAarrayStartIndex,\n // );\n // tickArrayAddress = expectedNextTickArrayAddress;\n // tickArrayCurrent = tickArrayCache[tickAarrayStartIndex];\n\n // nextInitTick = TickUtils.firstInitializedTick(tickArrayCurrent, zeroForOne);\n // }\n\n // step.tickNext = nextInitTick.tick;\n // step.initialized = nextInitTick.liquidityGross.gtn(0);\n // if (lastSavedTickArrayStartIndex !== tickAarrayStartIndex && tickArrayAddress) {\n // state.accounts.push(tickArrayAddress);\n // lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n // }\n // if (step.tickNext < MIN_TICK) {\n // step.tickNext = MIN_TICK;\n // } else if (step.tickNext > MAX_TICK) {\n // step.tickNext = MAX_TICK;\n // }\n\n // step.sqrtPriceNextX64 = SqrtPriceMath.getSqrtPriceX64FromTick(step.tickNext);\n // let targetPrice: BN;\n // if (\n // (zeroForOne && step.sqrtPriceNextX64.lt(sqrtPriceLimitX64)) ||\n // (!zeroForOne && step.sqrtPriceNextX64.gt(sqrtPriceLimitX64))\n // ) {\n // targetPrice = sqrtPriceLimitX64;\n // } else {\n // targetPrice = step.sqrtPriceNextX64;\n // }\n // [state.sqrtPriceX64, step.amountIn, step.amountOut, step.feeAmount] = SwapMath.swapStepCompute(\n // state.sqrtPriceX64,\n // targetPrice,\n // state.liquidity,\n // state.amountSpecifiedRemaining,\n // fee,\n // );\n\n // state.feeAmount = state.feeAmount.add(step.feeAmount);\n\n // if (baseInput) {\n // state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.sub(step.amountIn.add(step.feeAmount));\n // state.amountCalculated = state.amountCalculated.sub(step.amountOut);\n // } else {\n // state.amountSpecifiedRemaining = state.amountSpecifiedRemaining.add(step.amountOut);\n // state.amountCalculated = state.amountCalculated.add(step.amountIn.add(step.feeAmount));\n // }\n // if (state.sqrtPriceX64.eq(step.sqrtPriceNextX64)) {\n // if (step.initialized) {\n // let liquidityNet = nextInitTick.liquidityNet;\n // if (zeroForOne) liquidityNet = liquidityNet.mul(NEGATIVE_ONE);\n // state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);\n // }\n // state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n // } else if (state.sqrtPriceX64 != step.sqrtPriceStartX64) {\n // state.tick = SqrtPriceMath.getTickFromSqrtPriceX64(state.sqrtPriceX64);\n // }\n // ++loopCount;\n // }\n\n // // try {\n // // console.log('state.tick', state.tick)\n // // const { nextStartIndex: tickAarrayStartIndex } = TickQuery.nextInitializedTickArray(\n // // state.tick,\n // // tickSpacing,\n // // zeroForOne,\n // // tickArrayBitmap,\n // // tickarrayBitmapExtension,\n // // );\n // // if (\n // // lastSavedTickArrayStartIndex !== tickAarrayStartIndex\n // // ) {\n // // state.accounts.push(getPdaTickArrayAddress(\n // // programId,\n // // poolId,\n // // tickAarrayStartIndex,\n // // ).publicKey)\n // // lastSavedTickArrayStartIndex = tickAarrayStartIndex;\n // // }\n // // } catch (e) { /* empty */ }\n\n // return {\n // amountCalculated: state.amountCalculated,\n // feeAmount: state.feeAmount,\n // sqrtPriceX64: state.sqrtPriceX64,\n // liquidity: state.liquidity,\n // tickCurrent: state.tick,\n // accounts: state.accounts,\n // };\n // }\n\n private static swapStepCompute(\n sqrtPriceX64Current: BN,\n sqrtPriceX64Target: BN,\n liquidity: BN,\n amountRemaining: BN,\n feeRate: Fee,\n ): [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 { TransferFee, TransferFeeConfig } from \"@solana/spl-token\";\nimport { EpochInfo } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { TransferFeeDataBaseType } from \"../api/type\";\nimport { GetTransferAmountFee } from \"../cobaltx/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","import { MINT_SIZE, TOKEN_PROGRAM_ID, getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\nimport { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../cobaltx/type\";\nimport { chunkArray, getMintAddresses, solToWSol } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { NetworkName } from \"@/config\";\n\ninterface MultipleAccountsJsonRpcResponse {\n jsonrpc: string;\n id: string;\n error?: {\n code: number;\n message: string;\n };\n result: {\n context: { slot: number };\n value: { data: Array<string>; executable: boolean; lamports: number; owner: string; rentEpoch: number }[];\n };\n}\n\nexport interface GetMultipleAccountsInfoConfig {\n batchRequest?: boolean;\n commitment?: Commitment;\n chunkCount?: number;\n}\n\nconst logger = createLogger(\"CobaltX_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n connection: Connection,\n publicKeys: PublicKey[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n const {\n batchRequest,\n commitment = \"confirmed\",\n chunkCount = 100,\n } = {\n batchRequest: false,\n ...config,\n };\n\n const chunkedKeys = chunkArray(publicKeys, chunkCount);\n let results: (AccountInfo<Buffer> | null)[][] = new Array(chunkedKeys.length).fill([]);\n\n if (batchRequest) {\n const batch = chunkedKeys.map((keys) => {\n const args = connection._buildArgs([keys.map((key) => key.toBase58())], commitment, \"base64\");\n return {\n methodName: \"getMultipleAccounts\",\n args,\n };\n });\n\n const _batch = chunkArray(batch, 10);\n\n const unsafeResponse: MultipleAccountsJsonRpcResponse[] = await (\n await Promise.all(_batch.map(async (i) => await (connection as any)._rpcBatchRequest(i)))\n ).flat();\n results = unsafeResponse.map((unsafeRes: MultipleAccountsJsonRpcResponse) => {\n if (unsafeRes.error)\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${unsafeRes.error.message}`);\n\n return unsafeRes.result.value.map((accountInfo) => {\n if (accountInfo) {\n const { data, executable, lamports, owner, rentEpoch } = accountInfo;\n\n if (data.length !== 2 && data[1] !== \"base64\") logger.logWithError(`info must be base64 encoded, RPC_ERROR`);\n\n return {\n data: Buffer.from(data[0], \"base64\"),\n executable,\n lamports,\n owner: new PublicKey(owner),\n rentEpoch,\n };\n }\n return null;\n });\n });\n } else {\n try {\n results = (await Promise.all(\n chunkedKeys.map((keys) => connection.getMultipleAccountsInfo(keys, commitment)),\n )) as (AccountInfo<Buffer> | null)[][];\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${error.message}`);\n }\n }\n }\n\n return results.flat();\n}\n\nexport async function getMultipleAccountsInfoWithCustomFlags<T extends { pubkey: PublicKey }>(\n connection: Connection,\n publicKeysWithCustomFlag: T[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<({ accountInfo: AccountInfo<Buffer> | null } & T)[]> {\n const multipleAccountsInfo = await getMultipleAccountsInfo(\n connection,\n publicKeysWithCustomFlag.map((o) => o.pubkey),\n config,\n );\n\n return publicKeysWithCustomFlag.map((o, idx) => ({ ...o, accountInfo: multipleAccountsInfo[idx] }));\n}\n\nexport enum AccountType {\n Uninitialized,\n Mint,\n Account,\n}\nexport const ACCOUNT_TYPE_SIZE = 1;\n\nexport async function fetchMultipleMintInfos({\n connection,\n mints,\n network,\n config,\n}: {\n connection: Connection;\n mints: PublicKey[];\n network: NetworkName;\n config?: { batchRequest?: boolean };\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n if (mints.length === 0) return {};\n const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n mints.map((i) => ({ pubkey: solToWSol(i, network) })),\n config,\n );\n\n const mintK: ReturnTypeFetchMultipleMintInfos = {};\n for (const i of mintInfos) {\n if (!i.accountInfo || i.accountInfo.data.length < MINT_SIZE) {\n console.log(\"invalid mint account\", i.pubkey.toBase58());\n continue;\n }\n const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n mintK[i.pubkey.toString()] = {\n ...t,\n programId: i.accountInfo?.owner || TOKEN_PROGRAM_ID,\n feeConfig: getTransferFeeConfig(t) ?? undefined,\n };\n }\n mintK[PublicKey.default.toBase58()] = mintK[getMintAddresses(network).WSOLMint.toBase58()];\n\n return mintK;\n}\n","import { get, set } from \"lodash\";\n\nexport type ModuleName = \"Common.Api\";\n\nexport enum LogLevel {\n Error,\n Warning,\n Info,\n Debug,\n}\nexport class Logger {\n private logLevel: LogLevel;\n private name: string;\n constructor(params: { name: string; logLevel?: LogLevel }) {\n this.logLevel = params.logLevel !== undefined ? params.logLevel : LogLevel.Error;\n this.name = params.name;\n }\n\n set level(logLevel: LogLevel) {\n this.logLevel = logLevel;\n }\n get time(): string {\n return Date.now().toString();\n }\n get moduleName(): string {\n return this.name;\n }\n\n private isLogLevel(level: LogLevel): boolean {\n return level <= this.logLevel;\n }\n\n public error(...props): Logger {\n if (!this.isLogLevel(LogLevel.Error)) return this;\n console.error(this.time, this.name, \"sdk logger error\", ...props);\n return this;\n }\n\n public logWithError(...props): Logger {\n // this.error(...props)\n const msg = props.map((arg) => (typeof arg === \"object\" ? JSON.stringify(arg) : arg)).join(\", \");\n throw new Error(msg);\n }\n\n public warning(...props): Logger {\n if (!this.isLogLevel(LogLevel.Warning)) return this;\n console.warn(this.time, this.name, \"sdk logger warning\", ...props);\n return this;\n }\n\n public info(...props): Logger {\n if (!this.isLogLevel(LogLevel.Info)) return this;\n console.info(this.time, this.name, \"sdk logger info\", ...props);\n return this;\n }\n\n public debug(...props): Logger {\n if (!this.isLogLevel(LogLevel.Debug)) return this;\n console.debug(this.time, this.name, \"sdk logger debug\", ...props);\n return this;\n }\n}\n\nconst moduleLoggers: { [key in ModuleName]?: Logger } = {};\nconst moduleLevels: { [key in ModuleName]?: LogLevel } = {};\n\nexport function createLogger(moduleName: string): Logger {\n let logger = get(moduleLoggers, moduleName);\n if (!logger) {\n // default level is error\n const logLevel = get(moduleLevels, moduleName);\n\n logger = new Logger({ name: moduleName, logLevel });\n set(moduleLoggers, moduleName, logger);\n }\n\n return logger;\n}\n\nexport function setLoggerLevel(moduleName: string, level: LogLevel): void {\n set(moduleLevels, moduleName, level);\n\n const logger = get(moduleLoggers, moduleName);\n if (logger) logger.level = level;\n}\n","import BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { SplToken, TokenJson } from \"../cobaltx/token/type\";\nimport { ReplaceType } from \"../cobaltx/type\";\nimport { CurrencyAmount, TokenAmount } from \"../module/amount\";\nimport { Currency } from \"../module/currency\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { Price } from \"../module/price\";\nimport { Token } from \"../module/token\";\nimport { parseBigNumberish } from \"./constant\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\n\nexport const BN_ZERO = new BN(0);\nexport const BN_ONE = new BN(1);\nexport const BN_TWO = new BN(2);\nexport const BN_THREE = new BN(3);\nexport const BN_FIVE = new BN(5);\nexport const BN_TEN = new BN(10);\nexport const BN_100 = new BN(100);\nexport const BN_1000 = new BN(1000);\nexport const BN_10000 = new BN(10000);\nexport type BigNumberish = BN | string | number | bigint;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\nexport function tenExponential(shift: BigNumberish): BN {\n return BN_TEN.pow(parseBigNumberish(shift));\n}\n\n/**\n *\n * @example\n * getIntInfo(0.34) => { numerator: '34', denominator: '100'}\n * getIntInfo('0.34') //=> { numerator: '34', denominator: '100'}\n */\nexport function parseNumberInfo(n: Numberish | undefined): {\n denominator: string;\n numerator: string;\n sign?: string;\n int?: string;\n dec?: string;\n} {\n if (n === undefined) return { denominator: \"1\", numerator: \"0\" };\n if (n instanceof BN) {\n return { numerator: n.toString(), denominator: \"1\" };\n }\n\n if (n instanceof Fraction) {\n return { denominator: n.denominator.toString(), numerator: n.numerator.toString() };\n }\n\n const s = String(n);\n const [, sign = \"\", int = \"\", dec = \"\"] = s.replace(\",\", \"\").match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n const denominator = \"1\" + \"0\".repeat(dec.length);\n const numerator = sign + (int === \"0\" ? \"\" : int) + dec || \"0\";\n return { denominator, numerator, sign, int, dec };\n}\n\n// round up\nexport function divCeil(a: BN, b: BN): BN {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const dm = a.divmod(b);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n // Round up\n return dm.div.isNeg() ? dm.div.isubn(1) : dm.div.iaddn(1);\n}\n\nexport function shakeFractionDecimal(n: Fraction): string {\n const [, sign = \"\", int = \"\"] = n.toFixed(2).match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n return `${sign}${int}`;\n}\n\nexport function toBN(n: Numberish, decimal: BigNumberish = 0): BN {\n if (n instanceof BN) return n;\n return new BN(shakeFractionDecimal(toFraction(n).mul(BN_TEN.pow(new BN(String(decimal))))));\n}\n\nexport function toFraction(value: Numberish): Fraction {\n // to complete math format(may have decimal), not int\n if (value instanceof Percent) return new Fraction(value.numerator, value.denominator);\n\n if (value instanceof Price) return value.adjusted;\n\n // to complete math format(may have decimal), not BN\n if (value instanceof TokenAmount)\n try {\n return toFraction(value.toExact());\n } catch {\n return new Fraction(BN_ZERO);\n }\n\n // do not ideal with other fraction value\n if (value instanceof Fraction) return value;\n\n // wrap to Fraction\n const n = String(value);\n const details = parseNumberInfo(n);\n return new Fraction(details.numerator, details.denominator);\n}\n\n/**\n * @example\n * toPercent(3.14) // => Percent { 314.00% }\n * toPercent(3.14, { alreadyDecimaled: true }) // => Percent {3.14%}\n */\nexport function toPercent(\n n: Numberish,\n options?: { /* usually used for backend data */ alreadyDecimaled?: boolean },\n): Percent {\n const { numerator, denominator } = parseNumberInfo(n);\n return new Percent(new BN(numerator), new BN(denominator).mul(options?.alreadyDecimaled ? new BN(100) : new BN(1)));\n}\n\nexport function toTokenPrice(params: {\n token: TokenJson | Token | SplToken;\n numberPrice: Numberish;\n decimalDone?: boolean;\n}): Price {\n const { token, numberPrice, decimalDone } = params;\n const usdCurrency = new Token({ mint: \"\", decimals: 6, symbol: \"usd\", name: \"usd\", skipMint: true });\n const { numerator, denominator } = parseNumberInfo(numberPrice);\n const parsedNumerator = decimalDone ? new BN(numerator).mul(BN_TEN.pow(new BN(token.decimals))) : numerator;\n const parsedDenominator = new BN(denominator).mul(BN_TEN.pow(new BN(usdCurrency.decimals)));\n\n return new Price({\n baseToken: usdCurrency,\n denominator: parsedDenominator.toString(),\n quoteToken: new Token({ ...token, skipMint: true, mint: \"\" }),\n numerator: parsedNumerator.toString(),\n });\n}\n\nexport function toUsdCurrency(amount: Numberish): CurrencyAmount {\n const usdCurrency = new Currency({ decimals: 6, symbol: \"usd\", name: \"usd\" });\n const amountBigNumber = toBN(mul(amount, 10 ** usdCurrency.decimals)!);\n return new CurrencyAmount(usdCurrency, amountBigNumber);\n}\n\nexport function toTotalPrice(amount: Numberish | undefined, price: Price | undefined): CurrencyAmount {\n if (!price || !amount) return toUsdCurrency(0);\n return toUsdCurrency(mul(amount, price)!);\n}\n\nexport function decimalToFraction(n: Decimal | undefined): Fraction | undefined {\n if (n == null) return undefined;\n const { numerator, denominator } = parseNumberInfo(n.toString());\n return new Fraction(numerator, denominator);\n}\n\nexport function isDecimal(val: unknown): boolean {\n return val instanceof Decimal;\n}\n\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n // @ts-expect-error no need type for inner code\n return isDecimal(info)\n ? decimalToFraction(info as any)\n : Array.isArray(info)\n ? info.map((k) => recursivelyDecimalToFraction(k))\n : notInnerObject(info)\n ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)]))\n : info;\n}\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\n\nimport { BigNumberish, BN_TEN } from \"../common/bignumber\";\nimport { createLogger, Logger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common\";\nimport { Currency } from \"./currency\";\nimport toFormat, { WrappedBig } from \"./formatter\";\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\nimport { NetworkName } from \"@/config\";\n\nconst logger = createLogger(\"CobaltX_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 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 Big, { BigConstructor, BigSource, RoundingMode } from \"big.js\";\nimport Decimal, { Config, Numeric } from \"decimal.js-light\";\nimport _toFarmat from \"toformat\";\n\ntype TakeStatic<T> = { [P in keyof T]: T[P] };\ninterface FormatOptions {\n decimalSeparator?: string;\n groupSeparator?: string;\n groupSize?: number;\n fractionGroupSeparator?: string;\n fractionGroupSize?: number;\n}\ninterface WrappedBigConstructor extends TakeStatic<BigConstructor> {\n new (value: BigSource): WrappedBig;\n (value: BigSource): WrappedBig;\n (): WrappedBigConstructor;\n\n format: FormatOptions;\n}\nexport interface WrappedBig extends Big {\n add(n: BigSource): WrappedBig;\n abs(): WrappedBig;\n div(n: BigSource): WrappedBig;\n minus(n: BigSource): WrappedBig;\n mod(n: BigSource): WrappedBig;\n mul(n: BigSource): WrappedBig;\n plus(n: BigSource): WrappedBig;\n pow(exp: number): WrappedBig;\n round(dp?: number, rm?: RoundingMode): WrappedBig;\n sqrt(): WrappedBig;\n sub(n: BigSource): WrappedBig;\n times(n: BigSource): WrappedBig;\n toFormat(): string;\n toFormat(options: FormatOptions): string;\n toFormat(fractionLength: number): string;\n toFormat(fractionLength: number, options: FormatOptions): string;\n toFormat(fractionLength: number, missionUnknown: number): string;\n toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\ntype DecimalConstructor = typeof Decimal;\ninterface WrappedDecimalConstructor extends TakeStatic<DecimalConstructor> {\n new (value: Numeric): WrappedDecimal;\n clone(config?: Config): WrappedDecimalConstructor;\n config(config: Config): WrappedDecimal;\n set(config: Config): WrappedDecimal;\n format: FormatOptions;\n}\nexport interface WrappedDecimal extends Decimal {\n absoluteValue(): WrappedDecimal;\n abs(): WrappedDecimal;\n dividedBy(y: Numeric): WrappedDecimal;\n div(y: Numeric): WrappedDecimal;\n dividedToIntegerBy(y: Numeric): WrappedDecimal;\n idiv(y: Numeric): WrappedDecimal;\n logarithm(base?: Numeric): WrappedDecimal;\n log(base?: Numeric): WrappedDecimal;\n minus(y: Numeric): WrappedDecimal;\n sub(y: Numeric): WrappedDecimal;\n modulo(y: Numeric): WrappedDecimal;\n mod(y: Numeric): WrappedDecimal;\n naturalExponetial(): WrappedDecimal;\n exp(): WrappedDecimal;\n naturalLogarithm(): WrappedDecimal;\n ln(): WrappedDecimal;\n negated(): WrappedDecimal;\n neg(): WrappedDecimal;\n plus(y: Numeric): WrappedDecimal;\n add(y: Numeric): WrappedDecimal;\n squareRoot(): WrappedDecimal;\n sqrt(): WrappedDecimal;\n times(y: Numeric): WrappedDecimal;\n mul(y: Numeric): WrappedDecimal;\n toWrappedDecimalPlaces(dp?: number, rm?: number): WrappedDecimal;\n todp(dp?: number, rm?: number): WrappedDecimal;\n toInteger(): WrappedDecimal;\n toint(): WrappedDecimal;\n toPower(y: Numeric): WrappedDecimal;\n pow(y: Numeric): WrappedDecimal;\n toSignificantDigits(sd?: number, rm?: number): WrappedDecimal;\n tosd(sd?: number, rm?: number): WrappedDecimal;\n toFormat(options: FormatOptions): string;\n toFormat(fractionLength: number): string;\n toFormat(fractionLength: number, options: FormatOptions): string;\n toFormat(fractionLength: number, missionUnknown: number): string;\n toFormat(fractionLength: number, missionUnknown: number, options: FormatOptions): string;\n}\n\nconst toFormat: {\n (fn: BigConstructor): WrappedBigConstructor;\n (fn: DecimalConstructor): WrappedDecimalConstructor;\n} = _toFarmat;\nexport default toFormat;\n","import _Big from \"big.js\";\nimport BN from \"bn.js\";\nimport _Decimal from \"decimal.js-light\";\n\nimport { BigNumberish } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { parseBigNumberish, Rounding } from \"../common/constant\";\nimport toFormat, { WrappedBig } from \"./formatter\";\n\nconst logger = createLogger(\"module/fraction\");\n\nconst Big = toFormat(_Big);\ntype Big = WrappedBig;\n\nconst Decimal = toFormat(_Decimal);\n\nconst toSignificantRounding = {\n [Rounding.ROUND_DOWN]: Decimal.ROUND_DOWN,\n [Rounding.ROUND_HALF_UP]: Decimal.ROUND_HALF_UP,\n [Rounding.ROUND_UP]: Decimal.ROUND_UP,\n};\n\nconst toFixedRounding = {\n [Rounding.ROUND_DOWN]: _Big.roundDown,\n [Rounding.ROUND_HALF_UP]: _Big.roundHalfUp,\n [Rounding.ROUND_UP]: _Big.roundUp,\n};\n\nexport class Fraction {\n public readonly numerator: BN;\n public readonly denominator: BN;\n\n public constructor(numerator: BigNumberish, denominator: BigNumberish = new BN(1)) {\n this.numerator = parseBigNumberish(numerator);\n this.denominator = parseBigNumberish(denominator);\n }\n\n public get quotient(): BN {\n return this.numerator.div(this.denominator);\n }\n\n public invert(): Fraction {\n return new Fraction(this.denominator, this.numerator);\n }\n\n public add(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n if (this.denominator.eq(otherParsed.denominator)) {\n return new Fraction(this.numerator.add(otherParsed.numerator), this.denominator);\n }\n\n return new Fraction(\n this.numerator.mul(otherParsed.denominator).add(otherParsed.numerator.mul(this.denominator)),\n this.denominator.mul(otherParsed.denominator),\n );\n }\n\n public sub(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n if (this.denominator.eq(otherParsed.denominator)) {\n return new Fraction(this.numerator.sub(otherParsed.numerator), this.denominator);\n }\n\n return new Fraction(\n this.numerator.mul(otherParsed.denominator).sub(otherParsed.numerator.mul(this.denominator)),\n this.denominator.mul(otherParsed.denominator),\n );\n }\n\n public mul(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n return new Fraction(this.numerator.mul(otherParsed.numerator), this.denominator.mul(otherParsed.denominator));\n }\n\n public div(other: Fraction | BigNumberish): Fraction {\n const otherParsed = other instanceof Fraction ? other : new Fraction(parseBigNumberish(other));\n\n return new Fraction(this.numerator.mul(otherParsed.denominator), this.denominator.mul(otherParsed.numerator));\n }\n\n public toSignificant(\n significantDigits: number,\n format: object = { groupSeparator: \"\" },\n rounding: Rounding = Rounding.ROUND_HALF_UP,\n ): string {\n if (!Number.isInteger(significantDigits)) logger.logWithError(`${significantDigits} is not an integer.`);\n if (significantDigits <= 0) logger.logWithError(`${significantDigits} is not positive.`);\n\n Decimal.set({ precision: significantDigits + 1, rounding: toSignificantRounding[rounding] });\n const quotient = new Decimal(this.numerator.toString())\n .div(this.denominator.toString())\n .toSignificantDigits(significantDigits);\n return quotient.toFormat(quotient.decimalPlaces(), format);\n }\n\n public toFixed(\n decimalPlaces: number,\n format: object = { groupSeparator: \"\" },\n rounding: Rounding = Rounding.ROUND_HALF_UP,\n ): string {\n if (!Number.isInteger(decimalPlaces)) logger.logWithError(`${decimalPlaces} is not an integer.`);\n if (decimalPlaces < 0) logger.logWithError(`${decimalPlaces} is negative.`);\n\n Big.DP = decimalPlaces;\n Big.RM = toFixedRounding[rounding] || 1;\n return new Big(this.numerator.toString()).div(this.denominator.toString()).toFormat(decimalPlaces, format);\n }\n\n public isZero(): boolean {\n return this.numerator.isZero();\n }\n}\n","import BN from \"bn.js\";\nimport { BigNumberish } from \"./bignumber\";\nimport { createLogger } from \"./logger\";\n\nexport enum Rounding {\n ROUND_DOWN,\n ROUND_HALF_UP,\n ROUND_UP,\n}\n\nconst MAX_SAFE = 0x1fffffffffffff;\n\nexport function parseBigNumberish(value: BigNumberish): BN {\n const logger = createLogger(\"CobaltX_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","import { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { PublicKey } from \"@solana/web3.js\";\nimport { TokenInfo } from \"./type\";\nimport { NetworkName } from \"@/config\";\nimport { getNetworkConfig } from \"@/config\";\n\nexport function getSolInfo(network: NetworkName): TokenInfo {\n const config = getNetworkConfig(network);\n return {\n chainId: 101,\n address: PublicKey.default.toBase58(),\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: config.NATIVE_TOKEN_SYMBOL,\n name: config.FULL_TOKEN_NAME,\n logoURI: config.GITHUB_LOGO_URL,\n tags: [],\n priority: 2,\n type: \"cobaltx\",\n extensions: {\n coingeckoId: \"solana\",\n },\n };\n}\n\nexport function getTokenWSol(network: NetworkName): TokenInfo {\n const config = getNetworkConfig(network);\n return {\n chainId: 101,\n address: config.WSOL_MINT_ADDRESS,\n programId: TOKEN_PROGRAM_ID.toBase58(),\n decimals: 9,\n symbol: config.WRAPPED_TOKEN_SYMBOL || \"\",\n name: config.FULL_TOKEN_NAME,\n logoURI: config.GITHUB_LOGO_URL,\n tags: [],\n priority: 2,\n type: \"cobaltx\",\n extensions: {\n coingeckoId: \"solana\",\n },\n};\n}\n","import { PublicKey } from \"@solana/web3.js\";\r\n\r\nexport enum NetworkName {\r\n sooneth = \"sooneth\",\r\n // sooneth_testnet = \"sooneth_testnet\",\r\n svmbnb = \"svmbnb\",\r\n svmbnb_testnet = \"svmbnb_testnet\",\r\n svmbase_testnet = \"svmbase_testnet\",\r\n soonbase_mainnet = \"soonbase_mainnet\",\r\n}\r\n\r\nexport interface NetworkConfig {\r\n SWAP_HOST: string;\r\n NATIVE_TOKEN_SYMBOL: string;\r\n BASE_HOST: string;\r\n OWNER_BASE_HOST: string;\r\n SERVICE_BASE_HOST: string;\r\n MONITOR_BASE_HOST: string;\r\n SERVICE_1_BASE_HOST: string;\r\n ANALYTICS_BASE_HOST: string;\r\n GITHUB_TOKEN_LIST_URL: string;\r\n WSOL_MINT_ADDRESS: string;\r\n GITHUB_LOGO_URL: string;\r\n LOOKUP_TABLE_CACHE: string; \r\n CLMM_PROGRAMM_ID: string;\r\n FULL_TOKEN_NAME: string;\r\n USDC_MINT_ADDRESS: string;\r\n USDT_MINT_ADDRESS: string;\r\n ETH_MINT_ADDRESS: string;\r\n BONK_MINT_ADDRESS?: string | undefined;\r\n SOL_MINT_ADDRESS?: string | undefined;\r\n WRAPPED_TOKEN_SYMBOL: string;\r\n WSOL_DECIMALS: number;\r\n INPUT_MINT_ADDRESS: string;\r\n OUTPUT_MINT_ADDRESS: string;\r\n POPULAR_TOKENS: {\r\n SOL?: string,\r\n ETH?: string,\r\n USDC?: string,\r\n USDT?: string,\r\n\r\n };\r\n}\r\n\r\nexport const NETWORK_CONFIG: Record<NetworkName, NetworkConfig> = {\r\n [NetworkName.sooneth]: {\r\n NATIVE_TOKEN_SYMBOL: \"ETH\",\r\n SWAP_HOST: \"https://trade-api.cobaltx.io\",\r\n BASE_HOST: \"https://api.cobaltx.io\",\r\n OWNER_BASE_HOST: \"https://api.cobaltx.io\",\r\n SERVICE_BASE_HOST: \"https://api.cobaltx.io\",\r\n MONITOR_BASE_HOST: \"https://api.cobaltx.io\",\r\n SERVICE_1_BASE_HOST: \"https://api.cobaltx.io\",\r\n ANALYTICS_BASE_HOST: \"https://api.cobaltx.io\",\r\n GITHUB_TOKEN_LIST_URL: \"https://raw.githubusercontent.com/cobaltx-io/tokens/main/tokens.json\",\r\n WSOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n GITHUB_LOGO_URL:\r\n \"https://raw.githubusercontent.com/cobaltx-io/tokens/main/logo/So11111111111111111111111111111111111111112.png\",\r\n LOOKUP_TABLE_CACHE: \"6fa5xTGwoYJPMLMXaQ4tQFKMoYvXuvsJFLigMJ9a5QeB\",\r\n CLMM_PROGRAMM_ID: \"2TnjBuwqyBB9to5jURagDT7jLmBPefGRiKL2yh1zPZ4V\",\r\n BONK_MINT_ADDRESS: \"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd\",\r\n SOL_MINT_ADDRESS: \"ERFzpDteGNo8LTDKW1WwVGrkRMmA2y9WZHXNHxMA6BSV\",\r\n USDC_MINT_ADDRESS: \"ExYxyorY2x3h8gLcuypnHFQV3F36rmMkQVn7HHV8mUy9\",\r\n USDT_MINT_ADDRESS: \"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9\",\r\n FULL_TOKEN_NAME: \"Wrapped Ethereum\",\r\n ETH_MINT_ADDRESS: \"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd\",\r\n WRAPPED_TOKEN_SYMBOL: \"WETH\",\r\n INPUT_MINT_ADDRESS: PublicKey.default.toString(),\r\n OUTPUT_MINT_ADDRESS: \"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9\",\r\n POPULAR_TOKENS: {\r\n SOL: PublicKey.default.toString(),\r\n ETH: \"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd\",\r\n USDC: \"ExYxyorY2x3h8gLcuypnHFQV3F36rmMkQVn7HHV8KjtA\",\r\n USDT: \"742wcXVzkhNuEePAot7L3GvPseh93pvYFPgyHLX8mUy9\",\r\n },\r\n WSOL_DECIMALS: 9,\r\n },\r\n [NetworkName.svmbnb]: {\r\n NATIVE_TOKEN_SYMBOL: \"BNB\",\r\n SWAP_HOST: \"https://trade-api.svmbnb.cobaltx.io\",\r\n BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n OWNER_BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n SERVICE_BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n MONITOR_BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n SERVICE_1_BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n ANALYTICS_BASE_HOST: \"https://api.svmbnb.cobaltx.io\",\r\n GITHUB_TOKEN_LIST_URL: \"https://raw.githubusercontent.com/cobaltx-io/svmbnb-tokens/main/tokens.json\",\r\n WSOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n GITHUB_LOGO_URL:\r\n \"https://raw.githubusercontent.com/cobaltx-io/svmbnb-tokens/main/logo/So11111111111111111111111111111111111111112.svg\",\r\n LOOKUP_TABLE_CACHE: \"GSR5XQGWhpzV9TTduBJR6qPNjYsepMQSGkpaqfrbrW9w\",\r\n CLMM_PROGRAMM_ID: \"6f1b3xyVZbnWMHXBjgW1KPwxmPAgXcRdrvKNn4Nmf1Cn\",\r\n ETH_MINT_ADDRESS: \"H3xpFH1yN5E1zFdAoBrC9Y7m7RfJUeQNLvkHi8kNf9Qu\",\r\n USDC_MINT_ADDRESS: \"5odzAHDpDETYhupMkc6kjiYen3K2nrf8oPmvqmsoNW4L\",\r\n USDT_MINT_ADDRESS: \"s8cRDxnp3VxjB6khRnGDdxv6QbCUPyY9Vn1bgSQQsnG\",\r\n SOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n FULL_TOKEN_NAME: \"Wrapped BNB\",\r\n WRAPPED_TOKEN_SYMBOL: \"WBNB\",\r\n INPUT_MINT_ADDRESS: PublicKey.default.toBase58(),\r\n OUTPUT_MINT_ADDRESS: \"ABoT7umUXnx8RtJTeRqKB6myebVjP2wdJGQuV23jVVH3\",\r\n POPULAR_TOKENS: {\r\n SOL: PublicKey.default.toString(),\r\n ETH: \"H3xpFH1yN5E1zFdAoBrC9Y7m7RfJUeQNLvkHi8kNf9Qu\",\r\n USDC: \"5odzAHDpDETYhupMkc6kjiYen3K2nrf8oPmvqmsoNW4L\",\r\n USDT: \"s8cRDxnp3VxjB6khRnGDdxv6QbCUPyY9Vn1bgSQQsnG\",\r\n },\r\n WSOL_DECIMALS: 9,\r\n },\r\n [NetworkName.svmbnb_testnet]: {\r\n NATIVE_TOKEN_SYMBOL: \"BNB\",\r\n SWAP_HOST: \"https://trade-api.svmbnb.cobaltx.io\",\r\n BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n OWNER_BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n SERVICE_BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n MONITOR_BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n SERVICE_1_BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n ANALYTICS_BASE_HOST: \"https://api.testnet.svmbnb.cobaltx.io\",\r\n GITHUB_TOKEN_LIST_URL: \"https://raw.githubusercontent.com/cobaltx-io/svmbnb-testnet-tokens/main/tokens.json\",\r\n WSOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n GITHUB_LOGO_URL:\r\n \"https://raw.githubusercontent.com/cobaltx-io/svmbnb-testnet-tokens/main/logo/So11111111111111111111111111111111111111112.svg\",\r\n LOOKUP_TABLE_CACHE: \"D79gSiTNV9pyLPJyscW5yZYwdPVDrtKsamL3ZfQi6JiM\",\r\n CLMM_PROGRAMM_ID: \"FgycD57kcCZsjpoTAi2u67GTPxm59bPEhycL2Lw1icm1\",\r\n ETH_MINT_ADDRESS: \"5aLr3sV4UNVcMB6CiA3PZTWbgVBRNyMdEp1s5LNfhR95\",\r\n USDC_MINT_ADDRESS: \"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw\",\r\n USDT_MINT_ADDRESS: \"Ex86C4gmdjvPRNrfyvsyejbjkP6RstNaBC5g3itZw2iv\",\r\n FULL_TOKEN_NAME: \"Wrapped BNB\",\r\n WRAPPED_TOKEN_SYMBOL: \"WBNB\",\r\n INPUT_MINT_ADDRESS: \"bnb\",\r\n OUTPUT_MINT_ADDRESS: \"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw\",\r\n POPULAR_TOKENS: {\r\n SOL: PublicKey.default.toString(),\r\n ETH: \"5aLr3sV4UNVcMB6CiA3PZTWbgVBRNyMdEp1s5LNfhR95\",\r\n USDC: \"jrhUNRxEDpFmGV3sqaWyveS7bVtRQgtHsfBTCdjfMBw\",\r\n USDT: \"Ex86C4gmdjvPRNrfyvsyejbjkP6RstNaBC5g3itZw2iv\",\r\n },\r\n WSOL_DECIMALS: 9,\r\n },\r\n [NetworkName.svmbase_testnet]: {\r\n NATIVE_TOKEN_SYMBOL: \"ETH\",\r\n SWAP_HOST: \"https://trade-api.testnet.svmbase.cobaltx.io\",\r\n BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n OWNER_BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n SERVICE_BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n MONITOR_BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n SERVICE_1_BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n ANALYTICS_BASE_HOST: \"https://api.testnet.svmbase.cobaltx.io\",\r\n GITHUB_TOKEN_LIST_URL: \"https://raw.githubusercontent.com/cobaltx-io/svmbase-testnet-tokens/main/tokens.json\",\r\n WSOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n GITHUB_LOGO_URL:\r\n \"https://raw.githubusercontent.com/cobaltx-io/svmbase-testnet-tokens/main/logo/So11111111111111111111111111111111111111112.png\",\r\n LOOKUP_TABLE_CACHE: \"AyPMvNmUUY2jwZ75NxhkLYPraQGNk5DssVfP4TnMcPJF\",\r\n CLMM_PROGRAMM_ID: \"DnZnBqJKiGSYHUHYvkXAbQmkMbwrjfgo4orR7jWyMsik\",\r\n ETH_MINT_ADDRESS: \"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd\",\r\n USDC_MINT_ADDRESS: \"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK\",\r\n USDT_MINT_ADDRESS: \"4fyX7hSmPetQC2wRS3YVAhWeFzif7WStarKwTvCXrBtD\",\r\n FULL_TOKEN_NAME: \"Wrapped Ethereum\",\r\n WRAPPED_TOKEN_SYMBOL: \"WETH\",\r\n INPUT_MINT_ADDRESS: PublicKey.default.toString(),\r\n OUTPUT_MINT_ADDRESS: \"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK\",\r\n POPULAR_TOKENS: {\r\n SOL: PublicKey.default.toString(),\r\n ETH: \"So11111111111111111111111111111111111111112\",\r\n USDC: \"63tPXWPnYeZ9hA3dJsAY5RcQ8YbwEz8uZ5nKu3uFD1aK\",\r\n USDT: \"4fyX7hSmPetQC2wRS3YVAhWeFzif7WStarKwTvCXrBtD\",\r\n },\r\n WSOL_DECIMALS: 9,\r\n },\r\n [NetworkName.soonbase_mainnet]: {\r\n NATIVE_TOKEN_SYMBOL: \"ETH\",\r\n SWAP_HOST: \"https://trade-api.soonbase.cobaltx.io\",\r\n BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n OWNER_BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n SERVICE_BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n MONITOR_BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n SERVICE_1_BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n ANALYTICS_BASE_HOST: \"https://api.soonbase.cobaltx.io\",\r\n GITHUB_TOKEN_LIST_URL: \"https://raw.githubusercontent.com/cobaltx-io/soonbase-tokens/main/tokens.json\",\r\n WSOL_MINT_ADDRESS: \"So11111111111111111111111111111111111111112\",\r\n GITHUB_LOGO_URL:\r\n \"https://raw.githubusercontent.com/cobaltx-io/soonbase-tokens/main/logo/So11111111111111111111111111111111111111112.png\",\r\n LOOKUP_TABLE_CACHE: \"FGRusuLycV6nhSPQc9VX55YjT6DCzJFc59mvTTarSTjK\",\r\n CLMM_PROGRAMM_ID: \"6f1b3xyVZbnWMHXBjgW1KPwxmPAgXcRdrvKNn4Nmf1Cn\",\r\n ETH_MINT_ADDRESS: \"71kRXzJMvSeArtXYNEWa8KAjpRJosdMQ7Dpgy5Jt5zfd\",\r\n USDC_MINT_ADDRESS: \"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo\",\r\n USDT_MINT_ADDRESS: \"J87bysZjwfS3n6KR21cwbdPZVJWNSFcXpWF5kiChAwQH\",\r\n FULL_TOKEN_NAME: \"Wrapped Ethereum\",\r\n WRAPPED_TOKEN_SYMBOL: \"WETH\",\r\n INPUT_MINT_ADDRESS: PublicKey.default.toString(),\r\n OUTPUT_MINT_ADDRESS: \"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo\",\r\n POPULAR_TOKENS: {\r\n SOL: PublicKey.default.toString(),\r\n ETH: \"FkvCG5DcuYCQ1BnPH4ZzTkCdk3VzutgyDAFBec4qAjhh\",\r\n USDC: \"BoYN2f2gLQS4jpvMSV9dAZwfzKJiKGk4NPck5BjXfujo\",\r\n USDT: \"J87bysZjwfS3n6KR21cwbdPZVJWNSFcXpWF5kiChAwQH\",\r\n },\r\n WSOL_DECIMALS: 9,\r\n },\r\n};\r\n\r\nexport const getNetworkConfig = (network: NetworkName): NetworkConfig => {\r\n return NETWORK_CONFIG[network];\r\n};\r\n\r\n\r\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { getNetworkConfig, NetworkName } from \"@/config\";\nimport { getTokenWSol } from \"../cobaltx/token/constant\";\nimport { PublicKeyish, SOLMint, validateAndParsePublicKey } from \"../common/pubKey\";\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 network?: NetworkName;\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 public readonly network?: NetworkName;\n public readonly mint: PublicKey;\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, network }: TokenProps) {\n if (mint === SOLMint.toBase58() || (mint instanceof PublicKey && SOLMint.equals(mint))&& network) {\n this.decimals = getTokenWSol(network as NetworkName).decimals;\n this.symbol = getTokenWSol(network as NetworkName).symbol;\n this.name = getTokenWSol(network as NetworkName).name;\n this.mint = new PublicKey(getTokenWSol(network as NetworkName).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 static getWSol(network: NetworkName): Token {\n return new Token({\n ...getTokenWSol(network),\n mint: getTokenWSol(network).address,\n });\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 { getNetworkConfig, NetworkName } from \"@/config\";\nimport { 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 network,\n}: {\n publicKey: PublicKeyish;\n transformSol?: boolean;\n network?: NetworkName;\n}): PublicKey {\n const publicKey = tryParsePublicKey(orgPubKey.toString());\n\n if (transformSol && network) {\n const { WSOLMint } = getMintAddresses(network);\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 } else if (publicKey instanceof PublicKey) {\n return publicKey;\n }\n\n if (typeof publicKey === \"string\") {\n if (publicKey === PublicKey.default.toBase58()) return PublicKey.default;\n try {\n const key = new PublicKey(publicKey);\n return key;\n } catch {\n throw new Error(\"invalid public key\");\n }\n }\n\n throw new Error(\"invalid public key\");\n}\n\nexport function tryParsePublicKey(v: string): PublicKey | string {\n try {\n return new PublicKey(v);\n } catch (e) {\n return v;\n }\n}\n\nexport const MEMO_PROGRAM_ID = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const MEMO_PROGRAM_ID2 = new PublicKey(\"MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr\");\nexport const RENT_PROGRAM_ID = new PublicKey(\"SysvarRent111111111111111111111111111111111\");\nexport const CLOCK_PROGRAM_ID = new PublicKey(\"SysvarC1ock11111111111111111111111111111111\");\nexport const METADATA_PROGRAM_ID = new PublicKey(\"metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s\");\nexport const INSTRUCTION_PROGRAM_ID = new PublicKey(\"Sysvar1nstructions1111111111111111111111111\");\nexport const SYSTEM_PROGRAM_ID = SystemProgram.programId;\nexport const SOLMint = PublicKey.default;\n\nexport function getMintAddresses(network: NetworkName) {\n const config = getNetworkConfig(network);\n return {\n USDCMint: new PublicKey(config.USDC_MINT_ADDRESS),\n USDTMint: new PublicKey(config.USDT_MINT_ADDRESS),\n WSOLMint: new PublicKey(config.WSOL_MINT_ADDRESS),\n ETHMint: new PublicKey(config.ETH_MINT_ADDRESS),\n BONK_Mint: config.BONK_MINT_ADDRESS ? new PublicKey(config.BONK_MINT_ADDRESS) : PublicKey.default,\n SOL_Mint: config.SOL_MINT_ADDRESS ? new PublicKey(config.SOL_MINT_ADDRESS) : PublicKey.default,\n INPUT_MINT: new PublicKey(config.INPUT_MINT_ADDRESS),\n OUTPUT_MINT: new PublicKey(config.OUTPUT_MINT_ADDRESS),\n };\n}\n\n\nexport function solToWSol(mint: PublicKeyish, network: NetworkName): PublicKey {\n return validateAndParsePublicKey({ publicKey: mint, transformSol: true, network });\n}\n","import BN from \"bn.js\";\nimport { Rounding } from \"../common\";\nimport { Fraction } from \"./fraction\";\n\nexport const _100_PERCENT = new Fraction(new BN(100));\n\nexport class Percent extends Fraction {\n public toSignificant(significantDigits = 5, format?: object, rounding?: Rounding): string {\n return this.mul(_100_PERCENT).toSignificant(significantDigits, format, rounding);\n }\n\n public toFixed(decimalPlaces = 2, format?: object, rounding?: Rounding): string {\n return this.mul(_100_PERCENT).toFixed(decimalPlaces, format, rounding);\n }\n}\n","import { Rounding } from \"../common\";\nimport { BigNumberish, tenExponential } from \"../common/bignumber\";\nimport { createLogger } from \"../common/logger\";\n\nimport { Fraction } from \"./fraction\";\nimport { Token } from \"./token\";\n\nconst logger = createLogger(\"CobaltX_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 { PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { ReplaceType } from \"../cobaltx/type\";\nimport { Fraction, Percent, Price, Token, TokenAmount } from \"../module\";\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","/**\n * https://youmightnotneed.com/lodash/\n */\n\nexport function chunkArray<T>(arr: T[], chunkSize = 1, cache: T[][] = []): T[][] {\n const tmp = [...arr];\n if (chunkSize <= 0) return cache;\n while (tmp.length) cache.push(tmp.splice(0, chunkSize));\n return cache;\n}\n\nexport function intersection<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => arr.includes(item)));\n}\n\nexport function xor<T>(arr: T[], ...args: T[][]): T[] {\n return arr.filter((item) => args.every((arr) => !arr.includes(item)));\n}\n\nexport function uniq<T>(arr: T[]): T[] {\n return [...new Set(arr)];\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { findProgramAddress } from \"./txTool/txUtils\";\n\nexport function getATAAddress(\n owner: PublicKey,\n mint: PublicKey,\n programId?: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress(\n [owner.toBuffer(), (programId ?? TOKEN_PROGRAM_ID).toBuffer(), mint.toBuffer()],\n new PublicKey(\"ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL\"),\n );\n}\n","import {\n Commitment,\n ComputeBudgetProgram,\n Connection,\n EpochInfo,\n Keypair,\n PublicKey,\n SimulatedTransactionResponse,\n Transaction,\n TransactionInstruction,\n TransactionMessage,\n VersionedTransaction,\n} from \"@solana/web3.js\";\n\nimport { createLogger } from \"../logger\";\nimport { CacheLTA } from \"./lookupTable\";\nimport { InstructionType } from \"./txType\";\n\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport { ComputeBudgetConfig } from \"../../cobaltx/type\";\n\nconst logger = createLogger(\"CobaltX_txUtil\");\n\nexport const MAX_BASE64_SIZE = 1644;\n\nexport function addComputeBudget(config: ComputeBudgetConfig): {\n instructions: TransactionInstruction[];\n instructionTypes: string[];\n} {\n const ins: TransactionInstruction[] = [];\n const insTypes: string[] = [];\n if (config.microLamports) {\n ins.push(ComputeBudgetProgram.setComputeUnitPrice({ microLamports: config.microLamports }));\n insTypes.push(InstructionType.SetComputeUnitPrice);\n }\n if (config.units) {\n ins.push(ComputeBudgetProgram.setComputeUnitLimit({ units: config.units }));\n insTypes.push(InstructionType.SetComputeUnitLimit);\n }\n\n return {\n instructions: ins,\n instructionTypes: insTypes,\n };\n}\n\nexport async function getRecentBlockHash(connection: Connection, propsCommitment?: Commitment): Promise<string> {\n const commitment = propsCommitment ?? \"confirmed\";\n return (await connection.getLatestBlockhash?.({ commitment }))?.blockhash;\n}\n\nexport async function confirmTransaction(connection: Connection, txId: string): Promise<string> {\n connection.getSignatureStatuses([txId]);\n return new Promise((resolve, reject) => {\n const id = setTimeout(reject, 60 * 1000);\n connection.onSignature(\n txId,\n (signatureResult) => {\n clearTimeout(id);\n if (!signatureResult.err) {\n resolve(\"\");\n return;\n }\n reject(signatureResult.err.toString());\n },\n \"confirmed\",\n );\n });\n}\n\n/**\n * Forecast transaction size\n */\nexport function forecastTransactionSize(instructions: TransactionInstruction[], signers: PublicKey[]): boolean {\n if (instructions.length < 1) logger.logWithError(`no instructions provided: ${instructions.toString()}`);\n if (signers.length < 1) logger.logWithError(`no signers provided:, ${signers.toString()}`);\n\n const transaction = new Transaction();\n transaction.recentBlockhash = \"11111111111111111111111111111111\";\n transaction.feePayer = signers[0];\n transaction.add(...instructions);\n\n try {\n return Buffer.from(transaction.serialize({ verifySignatures: false })).toString(\"base64\").length < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Simulates multiple instruction\n */\n/**\n * Simulates multiple instruction\n */\nexport async function simulateMultipleInstruction(\n connection: Connection,\n instructions: TransactionInstruction[],\n keyword: string,\n batchRequest = true,\n): Promise<string[]> {\n const feePayer = new PublicKey(\"CobaltXSimuLateTransaction11111111111111111\");\n\n const transactions: Transaction[] = [];\n\n let transaction = new Transaction();\n transaction.feePayer = feePayer;\n\n for (const instruction of instructions) {\n if (!forecastTransactionSize([...transaction.instructions, instruction], [feePayer])) {\n transactions.push(transaction);\n transaction = new Transaction();\n transaction.feePayer = feePayer;\n }\n transaction.add(instruction);\n }\n if (transaction.instructions.length > 0) {\n transactions.push(transaction);\n }\n\n let results: SimulatedTransactionResponse[] = [];\n\n try {\n results = await simulateTransaction(connection, transactions, batchRequest);\n if (results.find((i) => i.err !== null)) throw Error(\"rpc simulateTransaction error\");\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to simulate for instructions\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n\n const logs: string[] = [];\n for (const result of results) {\n logger.debug(\"simulate result:\", result);\n\n if (result.logs) {\n const filteredLog = result.logs.filter((log) => log && log.includes(keyword));\n logger.debug(\"filteredLog:\", logs);\n if (!filteredLog.length) logger.logWithError(\"simulate log not match keyword\", \"keyword\", keyword);\n logs.push(...filteredLog);\n }\n }\n\n return logs;\n}\n\nexport function parseSimulateLogToJson(log: string, keyword: string): any {\n const results = log.match(/{[\"\\w:,]+}/g);\n if (!results || results.length !== 1) {\n return logger.logWithError(`simulate log fail to match json, keyword: ${keyword}`);\n }\n\n return results[0];\n}\n\nexport function parseSimulateValue(log: string, key: string): any {\n const reg = new RegExp(`\"${key}\":(\\\\d+)`, \"g\");\n\n const results = reg.exec(log);\n if (!results || results.length !== 2) {\n return logger.logWithError(`simulate log fail to match key\", key: ${key}`);\n }\n\n return results[1];\n}\n\nexport interface ProgramAddress {\n publicKey: PublicKey;\n nonce: number;\n}\nexport function findProgramAddress(\n seeds: Array<Buffer | Uint8Array>,\n programId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n const [publicKey, nonce] = PublicKey.findProgramAddressSync(seeds, programId);\n return { publicKey, nonce };\n}\n\nexport async function simulateTransaction(\n connection: Connection,\n transactions: Transaction[],\n batchRequest?: boolean,\n): Promise<any[]> {\n let results: any[] = [];\n if (batchRequest) {\n const getLatestBlockhash = await connection.getLatestBlockhash();\n\n const encodedTransactions: string[] = [];\n for (const transaction of transactions) {\n transaction.recentBlockhash = getLatestBlockhash.blockhash;\n transaction.lastValidBlockHeight = getLatestBlockhash.lastValidBlockHeight;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const message = transaction._compile();\n const signData = message.serialize();\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const wireTransaction = transaction._serialize(signData);\n const encodedTransaction = wireTransaction.toString(\"base64\");\n\n encodedTransactions.push(encodedTransaction);\n }\n\n const batch = encodedTransactions.map((keys) => {\n const args = connection._buildArgs([keys], undefined, \"base64\");\n return {\n methodName: \"simulateTransaction\",\n args,\n };\n });\n\n const reqData: { methodName: string; args: any[] }[][] = [];\n const itemReqIndex = 20;\n for (let i = 0; i < Math.ceil(batch.length / itemReqIndex); i++) {\n reqData.push(batch.slice(i * itemReqIndex, (i + 1) * itemReqIndex));\n }\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n results = await (\n await Promise.all(\n reqData.map(async (i) => (await (connection as any)._rpcBatchRequest(i)).map((ii) => ii.result.value)),\n )\n ).flat();\n } else {\n try {\n results = await Promise.all(\n transactions.map(async (transaction) => await (await connection.simulateTransaction(transaction)).value),\n );\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(\"failed to get info for multiple accounts\", \"RPC_ERROR\", {\n message: error.message,\n });\n }\n }\n }\n\n return results;\n}\n\nexport function checkLegacyTxSize({\n instructions,\n payer,\n signers,\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n signers: PublicKey[];\n}): boolean {\n return forecastTransactionSize(instructions, [payer, ...signers]);\n}\n\nexport function checkV0TxSize({\n instructions,\n payer,\n lookupTableAddressAccount,\n recentBlockhash = Keypair.generate().publicKey.toString(),\n}: {\n instructions: TransactionInstruction[];\n payer: PublicKey;\n lookupTableAddressAccount?: CacheLTA;\n recentBlockhash?: string;\n}): boolean {\n const transactionMessage = new TransactionMessage({\n payerKey: payer,\n recentBlockhash,\n instructions,\n });\n\n const messageV0 = transactionMessage.compileToV0Message(Object.values(lookupTableAddressAccount ?? {}));\n try {\n const buildLength = Buffer.from(new VersionedTransaction(messageV0).serialize()).toString(\"base64\").length;\n return buildLength < MAX_BASE64_SIZE;\n } catch (error) {\n return false;\n }\n}\n\nlet epochInfoCache: { time: number; data?: EpochInfo } = {\n time: 0,\n data: undefined,\n};\n\nexport async function getEpochInfo(connection: Connection): Promise<EpochInfo> {\n if (!epochInfoCache.data || (Date.now() - epochInfoCache.time) / 1000 > 30) {\n const data = await connection.getEpochInfo();\n epochInfoCache = {\n time: Date.now(),\n data,\n };\n return data;\n } else {\n return epochInfoCache.data;\n }\n}\n\nexport const toBuffer = (arr: Buffer | Uint8Array | Array<number>): Buffer => {\n if (Buffer.isBuffer(arr)) {\n return arr;\n } else if (arr instanceof Uint8Array) {\n return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);\n } else {\n return Buffer.from(arr);\n }\n};\n\nexport const txToBase64 = (transaction: Transaction | VersionedTransaction): string => {\n let serialized = transaction.serialize({ requireAllSignatures: false, verifySignatures: false });\n if (transaction instanceof VersionedTransaction) serialized = toBuffer(serialized);\n try {\n return serialized instanceof Buffer ? serialized.toString(\"base64\") : Buffer.from(serialized).toString(\"base64\");\n } catch {\n return serialized.toString(\"base64\");\n }\n};\n\nexport function printSimulate(transactions: Transaction[] | VersionedTransaction[]): string[] {\n const allBase64: string[] = [];\n transactions.forEach((transaction) => {\n if (transaction instanceof Transaction) {\n if (!transaction.recentBlockhash) transaction.recentBlockhash = TOKEN_PROGRAM_ID.toBase58();\n if (!transaction.feePayer) transaction.feePayer = Keypair.generate().publicKey;\n }\n allBase64.push(txToBase64(transaction));\n });\n console.log(\"simulate tx string:\", allBase64);\n\n return allBase64;\n}\n\nexport function transformTxToBase64(tx: Transaction | VersionedTransaction): string {\n let serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });\n if (tx instanceof VersionedTransaction) serialized = toBuffer(serialized);\n return serialized.toString(\"base64\");\n}\n","import { NetworkName } from \"@/config\";\nimport { getNetworkConfig } from \"@/config\";\nimport { PublicKey } from \"@solana/web3.js\";\n\n// cobaltx\nexport const FARM_PROGRAM_ID_V3 = new PublicKey(\"EhhTKczWMGQt46ynNeRX1WfeagwwJd7ufHvCDjRxjo5Q\");\n// temp fusion\nexport const FARM_PROGRAM_ID_V4 = new PublicKey(\"CBuCnLe26faBpcBP2fktp4rp8abpcAnTWft6ZrP5Q4T\");\n// \"fusion\"\nexport const FARM_PROGRAM_ID_V5 = new PublicKey(\"9KEPoZmtHUrBbhWN1v1KWLMkkvwY6WLtAVUCPRtRjP4z\");\n// echosystem\nexport const FARM_PROGRAM_ID_V6 = new PublicKey(\"FarmqiPv5eAj3j1GMdMCMUGXqPUvmquZtMy86QH6rzhG\");\n\nexport const UTIL1216 = new PublicKey(\"CLaimxFqjHzgTJtAGHU47NPhg6qrc5sCnpC4tBLyABQS\");\n\nexport const OPEN_BOOK_PROGRAM = new PublicKey(\"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\");\nexport const SERUM_PROGRAM_ID_V3 = new PublicKey(\"9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin\");\n\nexport const AMM_V4 = new PublicKey(\"675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8\");\nexport const AMM_STABLE = new PublicKey(\"5quBtoiQqxF9Jv6KYKctB59NT3gtJD2Y65kdnB1Uev3h\");\nexport const LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL = new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\");\n\nexport function getCLMMProgramId(network: NetworkName): PublicKey {\n const config = getNetworkConfig(network);\n return new PublicKey(config.CLMM_PROGRAMM_ID);\n}\n\nexport const CLMM_LOCK_PROGRAM_ID = new PublicKey(\"LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE\");\nexport const CLMM_LOCK_AUTH_ID = new PublicKey(\"kN1kEznaF5Xbd8LYuqtEFcxzWSBk5Fv6ygX6SqEGJVy\");\n\nexport const Router = new PublicKey(\"routeUGWgWzqBWFcrCfv8tritsqukccJPu3q5GPP3xS\");\nexport const FEE_DESTINATION_ID = new PublicKey(\"7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqtj2G5\");\n\nexport const IDO_PROGRAM_ID_V1 = new PublicKey(\"6FJon3QE27qgPVggARueB22hLvoh22VzJpXv4rBEoSLF\");\nexport const IDO_PROGRAM_ID_V2 = new PublicKey(\"CC12se5To1CdEuw7fDS27B7Geo5jJyL7t5UK2B44NgiH\");\nexport const IDO_PROGRAM_ID_V3 = new PublicKey(\"9HzJyW1qZsEiSfMUf6L2jo3CcTKAyBmSyKdwQeYisHrC\");\nexport const IDO_PROGRAM_ID_V4 = new PublicKey(\"DropEU8AvevN3UrXWXTMuz3rqnMczQVNjq3kcSdW2SQi\");\n\nexport const CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMMoo8L3F4NbTegBCKVNunggL7H1ZpdTHKxQB5qKP1C\");\nexport const CREATE_CPMM_POOL_AUTH = new PublicKey(\"GpMZbSM2GgvTKHJirzeGfMFoaZ8UR2X7F4v8vHTvxFbL\");\nexport const CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"DNXgeM9EiiaAbaWvwjHj9fQQLAX5ZsfHyvmYUNRAdNC8\");\n\nexport const DEV_CREATE_CPMM_POOL_PROGRAM = new PublicKey(\"CPMDWBwJDtYax9qW7AyRuVC19Cc4L4Vcy4n2BHAbHkCW\");\nexport const DEV_CREATE_CPMM_POOL_AUTH = new PublicKey(\"7rQ1QFNosMkUCuh7Z7fPbTHvh73b68sQYdirycEzJVuw\");\nexport const DEV_CREATE_CPMM_POOL_FEE_ACC = new PublicKey(\"G11FKBRaAkHAKuLCgLM6K6NUc9rTjPAznRCjZifrTQe2\");\n\nexport const LOCK_CPMM_PROGRAM = new PublicKey(\"LockrWmn6K5twhz3y9w1dQERbmgSaRkfnTeTKbpofwE\");\nexport const DEV_LOCK_CPMM_PROGRAM = new PublicKey(\"DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC\");\n\nexport const LOCK_CPMM_AUTH = new PublicKey(\"3f7GcQFG397GAaEnv51zR6tsTVihYRydnydDD1cXekxH\");\nexport const DEV_LOCK_CPMM_AUTH = new PublicKey(\"7AFUeLVRjBfzqK3tTGw8hN48KLQWSk6DTE8xprWdPqix\");\n\nexport const 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 getCLMMProgramId,\n CLMM_LOCK_PROGRAM_ID,\n CLMM_LOCK_AUTH_ID,\n\n FARM_PROGRAM_ID_V3,\n FARM_PROGRAM_ID_V5,\n FARM_PROGRAM_ID_V6,\n\n OPEN_BOOK_PROGRAM,\n SERUM_PROGRAM_ID_V3,\n\n UTIL1216,\n\n Router,\n\n CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC,\n\n LOCK_CPMM_PROGRAM,\n LOCK_CPMM_AUTH,\n};\n\nexport type ProgramIdConfig = Partial<typeof ALL_PROGRAM_ID>;\n\nexport const DEVNET_PROGRAM_ID = {\n SERUM_MARKET: PublicKey.default,\n OPENBOOK_MARKET: new PublicKey(\"EoTcMgcDRTJVZDMZWBoU6rhYHZfkNTVEAfz3uUJRcYGj\"),\n\n UTIL1216: PublicKey.default,\n\n FarmV3: new PublicKey(\"85BFyr98MbCUU9MVTEgzx1nbhWACbJqLzho6zd6DZcWL\"),\n FarmV5: new PublicKey(\"EcLzTrNg9V7qhcdyXDe2qjtPkiGzDM2UbdRaeaadU5r2\"),\n FarmV6: new PublicKey(\"Farm2hJLcqPtPg8M4rR6DMrsRNc5TPm5Cs4bVQrMe2T7\"),\n\n AmmV4: new PublicKey(\"HWy1jotHpo6UqeQxx49dpYYdQB8wj9Qk9MdxwjLvDHB8\"),\n AmmStable: new PublicKey(\"DDg4VmQaJV9ogWce7LpcjBA9bv22wRp5uaTPa5pGjijF\"),\n\n CLMM: new PublicKey(\"devi51mZmdwUJGU9hjN27vEz64Gps7uUefqxg27EAtH\"),\n CLMM_LOCK_PROGRAM_ID: new PublicKey(\"DLockwT7X7sxtLmGH9g5kmfcjaBtncdbUmi738m5bvQC\"),\n CLMM_LOCK_AUTH_ID: new PublicKey(\"8qmHNvu2Kr2C7U8mJL4Vz1vTDxMhVuXKREwU7TNoaVEo\"),\n\n Router: new PublicKey(\"BVChZ3XFEwTMUk1o9i3HAf91H6mFxSwa5X2wFAWhYPhU\"),\n\n CREATE_CPMM_POOL_PROGRAM: DEV_CREATE_CPMM_POOL_PROGRAM,\n CREATE_CPMM_POOL_AUTH: DEV_CREATE_CPMM_POOL_AUTH,\n CREATE_CPMM_POOL_FEE_ACC: DEV_CREATE_CPMM_POOL_FEE_ACC,\n\n FEE_DESTINATION_ID: new PublicKey(\"3XMrhbv989VxAMi3DErLV9eJht1pHppW5LbKxe9fkEFR\"),\n\n LOCK_CPMM_PROGRAM: DEV_LOCK_CPMM_PROGRAM,\n LCOK_CPMM_AUTH: DEV_LOCK_CPMM_AUTH,\n};\n","import { Connection, PublicKey, AddressLookupTableAccount } from \"@solana/web3.js\";\nimport { getMultipleAccountsInfo } from \"../accountInfo\";\nimport { getNetworkConfig, NetworkName } from \"@/config\";\n\nexport interface CacheLTA {\n [key: string]: AddressLookupTableAccount;\n}\n\nexport async function getMultipleLookupTableInfo({\n connection,\n address,\n network,\n}: {\n connection: Connection;\n address: PublicKey[];\n network: NetworkName;\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 getLookupTableCache(network)[key.toString()] = lookupAccount;\n }\n\n return outDict;\n}\n\nexport function getLookupTableCache(network: NetworkName): CacheLTA {\n const config = getNetworkConfig(network);\n return {\n [config.LOOKUP_TABLE_CACHE]: new AddressLookupTableAccount({\n key: new PublicKey(config.LOOKUP_TABLE_CACHE),\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}\n\n\n","import {\n Commitment,\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 { NetworkName } from \"@/config\";\nimport { Api } from \"../../api\";\nimport { ComputeBudgetConfig, SignAllTransactions } from \"../../cobaltx/type\";\nimport { Cluster } from \"../../solana\";\nimport { Owner } from \"../owner\";\nimport { CacheLTA, getLookupTableCache, getMultipleLookupTableInfo } from \"./lookupTable\";\nimport { TxVersion } from \"./txType\";\nimport {\n addComputeBudget,\n checkLegacyTxSize,\n checkV0TxSize,\n confirmTransaction,\n getRecentBlockHash,\n printSimulate,\n} from \"./txUtils\";\n\ninterface SolanaFeeInfo {\n min: number;\n max: number;\n avg: number;\n priorityTx: number;\n nonVotes: number;\n priorityRatio: number;\n avgCuPerBlock: number;\n blockspaceUsageRatio: number;\n}\ntype SolanaFeeInfoJson = {\n \"1\": SolanaFeeInfo;\n \"5\": SolanaFeeInfo;\n \"15\": SolanaFeeInfo;\n};\n\ninterface ExecuteParams {\n skipPreflight?: boolean;\n recentBlockHash?: string;\n sendAndConfirm?: boolean;\n}\n\ninterface TxBuilderInit {\n connection: Connection;\n feePayer: PublicKey;\n cluster: Cluster;\n owner?: Owner;\n blockhashCommitment?: Commitment;\n api?: Api;\n signAllTransactions?: SignAllTransactions;\n network: NetworkName;\n}\n\nexport interface AddInstructionParam {\n addresses?: Record<string, PublicKey>;\n instructions?: TransactionInstruction[];\n endInstructions?: TransactionInstruction[];\n lookupTableAddress?: string[];\n signers?: Signer[];\n instructionTypes?: string[];\n endInstructionTypes?: string[];\n}\n\nexport interface TxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transaction: Transaction;\n instructionTypes: string[];\n signers: Signer[];\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: Transaction }>;\n extInfo: T;\n}\n\nexport interface TxV0BuildData<T = Record<string, any>> extends Omit<TxBuildData<T>, \"transaction\" | \"execute\"> {\n builder: TxBuilder;\n transaction: VersionedTransaction;\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (params?: ExecuteParams) => Promise<{ txId: string; signedTx: VersionedTransaction }>;\n}\n\ntype TxUpdateParams = {\n txId: string;\n status: \"success\" | \"error\" | \"sent\";\n signedTx: Transaction | VersionedTransaction;\n};\nexport interface MultiTxExecuteParam extends ExecuteParams {\n sequentially: boolean;\n skipTxCount?: number;\n onTxUpdate?: (completeTxs: TxUpdateParams[]) => void;\n}\nexport interface MultiTxBuildData<T = Record<string, any>> {\n builder: TxBuilder;\n transactions: Transaction[];\n instructionTypes: string[];\n signers: Signer[][];\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: Transaction[] }>;\n extInfo: T;\n}\n\nexport interface MultiTxV0BuildData<T = Record<string, any>>\n extends Omit<MultiTxBuildData<T>, \"transactions\" | \"execute\"> {\n builder: TxBuilder;\n transactions: VersionedTransaction[];\n buildProps?: {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n };\n execute: (executeParams?: MultiTxExecuteParam) => Promise<{ txIds: string[]; signedTxs: VersionedTransaction[] }>;\n}\n\nexport type MakeMultiTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? MultiTxBuildData<O>\n : MultiTxV0BuildData<O>;\n\nexport type MakeTxData<T = TxVersion.LEGACY, O = Record<string, any>> = T extends TxVersion.LEGACY\n ? TxBuildData<O>\n : TxV0BuildData<O>;\n\nexport class TxBuilder {\n private connection: Connection;\n private owner?: Owner;\n private instructions: TransactionInstruction[] = [];\n private endInstructions: TransactionInstruction[] = [];\n private lookupTableAddress: string[] = [];\n private signers: Signer[] = [];\n private instructionTypes: string[] = [];\n private endInstructionTypes: string[] = [];\n private feePayer: PublicKey;\n private cluster: Cluster;\n private signAllTransactions?: SignAllTransactions;\n private blockhashCommitment?: Commitment;\n private api?: Api;\n private network: NetworkName;\n\n constructor(params: TxBuilderInit) {\n this.connection = params.connection;\n this.feePayer = params.feePayer;\n this.signAllTransactions = params.signAllTransactions;\n this.owner = params.owner;\n this.cluster = params.cluster;\n this.blockhashCommitment = params.blockhashCommitment;\n this.api = params.api;\n this.network = params.network;\n }\n\n get AllTxData(): {\n instructions: TransactionInstruction[];\n endInstructions: TransactionInstruction[];\n signers: Signer[];\n instructionTypes: string[];\n endInstructionTypes: string[];\n lookupTableAddress: string[];\n } {\n return {\n instructions: this.instructions,\n endInstructions: this.endInstructions,\n signers: this.signers,\n instructionTypes: this.instructionTypes,\n endInstructionTypes: this.endInstructionTypes,\n lookupTableAddress: this.lookupTableAddress,\n };\n }\n\n get allInstructions(): TransactionInstruction[] {\n return [...this.instructions, ...this.endInstructions];\n }\n\n public async getComputeBudgetConfig(): Promise<ComputeBudgetConfig | undefined> {\n const json = (\n await axios.get<SolanaFeeInfoJson>(`https://solanacompass.com/api/fees?cacheFreshTime=${5 * 60 * 1000}`)\n ).data;\n const { avg } = json?.[15] ?? {};\n if (!avg) return undefined;\n return {\n units: 600000,\n microLamports: Math.min(Math.ceil((avg * 1000000) / 600000), 25000),\n };\n }\n\n public addCustomComputeBudget(config?: ComputeBudgetConfig): boolean {\n if (config) {\n const { instructions, instructionTypes } = addComputeBudget(config);\n this.instructions.unshift(...instructions);\n this.instructionTypes.unshift(...instructionTypes);\n return true;\n }\n return false;\n }\n\n public async calComputeBudget({\n config: propConfig,\n defaultIns,\n }: {\n config?: ComputeBudgetConfig;\n defaultIns?: TransactionInstruction[];\n }): Promise<void> {\n try {\n const config = propConfig || (await this.getComputeBudgetConfig());\n if (this.addCustomComputeBudget(config)) return;\n defaultIns && this.instructions.unshift(...defaultIns);\n } catch {\n defaultIns && this.instructions.unshift(...defaultIns);\n }\n }\n\n public addInstruction({\n instructions = [],\n endInstructions = [],\n signers = [],\n instructionTypes = [],\n endInstructionTypes = [],\n lookupTableAddress = [],\n }: AddInstructionParam): TxBuilder {\n this.instructions.push(...instructions);\n this.endInstructions.push(...endInstructions);\n this.signers.push(...signers);\n this.instructionTypes.push(...instructionTypes);\n this.endInstructionTypes.push(...endInstructionTypes);\n this.lookupTableAddress.push(...lookupTableAddress.filter((address) => address !== PublicKey.default.toString()));\n return this;\n }\n\n public async versionBuild<O = Record<string, any>>({\n txVersion,\n extInfo,\n }: {\n txVersion?: TxVersion;\n extInfo?: O;\n }): Promise<MakeTxData<TxVersion.LEGACY, O> | MakeTxData<TxVersion.V0, O>> {\n if (txVersion === TxVersion.V0) return (await this.buildV0({ ...(extInfo || {}) })) as MakeTxData<TxVersion.V0, O>;\n return this.build<O>(extInfo) as MakeTxData<TxVersion.LEGACY, O>;\n }\n\n public build<O = Record<string, any>>(extInfo?: O): MakeTxData<TxVersion.LEGACY, O> {\n const transaction = new Transaction();\n if (this.allInstructions.length) transaction.add(...this.allInstructions);\n transaction.feePayer = this.feePayer;\n if (this.owner?.signer && !this.signers.some((s) => s.publicKey.equals(this.owner!.publicKey)))\n this.signers.push(this.owner.signer);\n\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { recentBlockHash: propBlockHash, skipPreflight = true, sendAndConfirm } = params || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n transaction.recentBlockhash = recentBlockHash;\n if (this.signers.length) transaction.sign(...this.signers);\n\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n const txId = sendAndConfirm\n ? await sendAndConfirmTransaction(\n this.connection,\n transaction,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n )\n : await this.connection.sendRawTransaction(transaction.serialize(), { skipPreflight });\n\n return {\n txId,\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions([transaction]);\n return {\n txId: await this.connection.sendRawTransaction(txs[0].serialize(), { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || ({} as O),\n };\n }\n\n public buildMultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.LEGACY>[];\n extInfo?: T;\n }): MultiTxBuildData {\n const { extraPreBuildData = [], extInfo } = params;\n const { transaction } = this.build(extInfo);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.transaction.instructions.length > 0);\n\n const allTransactions: Transaction[] = [transaction, ...filterExtraBuildData.map((data) => data.transaction)];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n if (this.owner?.signer) {\n allSigners.forEach((signers) => {\n if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) this.signers.push(this.owner!.signer!);\n });\n }\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const {\n sequentially,\n onTxUpdate,\n skipTxCount = 0,\n recentBlockHash: propBlockHash,\n skipPreflight = true,\n } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n let i = 0;\n for (const tx of allTransactions) {\n ++i;\n if (i <= skipTxCount) continue;\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n return {\n txIds: await await Promise.all(\n allTransactions.map(async (tx) => {\n tx.recentBlockhash = recentBlockHash;\n return await this.connection.sendRawTransaction(tx.serialize(), { skipPreflight });\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const partialSignedTxs = allTransactions.map((tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n return tx;\n });\n printSimulate(partialSignedTxs);\n const signedTxs = await this.signAllTransactions(partialSignedTxs);\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n 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 if (!signatureResult.err) 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 });\n txIds.push(txId);\n }\n return {\n txIds,\n signedTxs,\n };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async versionMultiBuild<T extends TxVersion, O = Record<string, any>>({\n extraPreBuildData,\n txVersion,\n extInfo,\n }: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[] | MakeTxData<TxVersion.LEGACY>[];\n txVersion?: T;\n extInfo?: O;\n }): Promise<MakeMultiTxData<T, O>> {\n if (txVersion === TxVersion.V0)\n return (await this.buildV0MultiTx({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.V0>[],\n buildProps: extInfo || {},\n })) as MakeMultiTxData<T, O>;\n return this.buildMultiTx<O>({\n extraPreBuildData: extraPreBuildData as MakeTxData<TxVersion.LEGACY>[],\n extInfo,\n }) as MakeMultiTxData<T, O>;\n }\n\n public async buildV0<O = Record<string, any>>(\n props?: O & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n forerunCreate?: boolean;\n recentBlockhash?: string;\n network?: NetworkName;\n },\n ): Promise<MakeTxData<TxVersion.V0, O>> {\n const {\n lookupTableCache = {},\n lookupTableAddress = [],\n forerunCreate,\n recentBlockhash: propRecentBlockhash,\n network = this.network,\n ...extInfo \n } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : getLookupTableCache(network)),\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, network });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const recentBlockhash = forerunCreate\n ? PublicKey.default.toBase58()\n : propRecentBlockhash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash,\n instructions: [...this.allInstructions],\n }).compileToV0Message();\n\n if (this.owner?.signer && !this.signers.some((s) => s.publicKey.equals(this.owner!.publicKey)))\n this.signers.push(this.owner.signer);\n const transaction = new VersionedTransaction(messageV0);\n transaction.sign(this.signers);\n return {\n builder: this,\n transaction,\n signers: this.signers,\n instructionTypes: [...this.instructionTypes, ...this.endInstructionTypes],\n execute: async (params) => {\n const { skipPreflight = true, sendAndConfirm } = params || {};\n printSimulate([transaction]);\n if (this.owner?.isKeyPair) {\n const txId = await this.connection.sendTransaction(transaction, { skipPreflight });\n if (sendAndConfirm) {\n await confirmTransaction(this.connection, txId);\n }\n\n return {\n txId,\n signedTx: transaction,\n };\n }\n if (this.signAllTransactions) {\n const txs = await this.signAllTransactions<VersionedTransaction>([transaction]);\n return {\n txId: await this.connection.sendTransaction(txs[0], { skipPreflight }),\n signedTx: txs[0],\n };\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: (extInfo || {}) as O,\n };\n }\n\n public async buildV0MultiTx<T = Record<string, any>>(params: {\n extraPreBuildData?: MakeTxData<TxVersion.V0>[];\n buildProps?: T & {\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n forerunCreate?: boolean;\n recentBlockhash?: string;\n };\n }): Promise<MultiTxV0BuildData> {\n const { extraPreBuildData = [], buildProps } = params;\n const { transaction } = await this.buildV0(buildProps);\n\n const filterExtraBuildData = extraPreBuildData.filter((data) => data.builder.instructions.length > 0);\n\n const allTransactions: VersionedTransaction[] = [\n transaction,\n ...filterExtraBuildData.map((data) => data.transaction),\n ];\n const allSigners: Signer[][] = [this.signers, ...filterExtraBuildData.map((data) => data.signers)];\n const allInstructionTypes: string[] = [\n ...this.instructionTypes,\n ...filterExtraBuildData.map((data) => data.instructionTypes).flat(),\n ];\n\n if (this.owner?.signer) {\n allSigners.forEach((signers) => {\n if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) this.signers.push(this.owner!.signer!);\n });\n }\n\n allTransactions.forEach(async (tx, idx) => {\n tx.sign(allSigners[idx]);\n });\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: allInstructionTypes,\n buildProps,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const { sequentially, onTxUpdate, recentBlockHash: propBlockHash, skipPreflight = true } = executeParams || {};\n if (propBlockHash) allTransactions.forEach((tx) => (tx.message.recentBlockhash = propBlockHash));\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await confirmTransaction(this.connection, txId);\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n return await this.connection.sendTransaction(tx, { skipPreflight });\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n\n if (this.signAllTransactions) {\n const signedTxs = await this.signAllTransactions(allTransactions);\n\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n 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 if (!signatureResult.err) 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 });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: buildProps || {},\n };\n }\n\n public async sizeCheckBuild(\n props?: Record<string, any> & { computeBudgetConfig?: ComputeBudgetConfig; splitIns?: TransactionInstruction[] },\n ): Promise<MultiTxBuildData> {\n const { splitIns = [], computeBudgetConfig, ...extInfo } = props || {};\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n\n const allTransactions: Transaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n let splitInsIdx = 0;\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n const _signerStrs = new Set<string>(\n _itemIns.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signer = [..._signerStrs.values()].map((i) => new PublicKey(i));\n\n if (\n item !== splitIns[splitInsIdx] &&\n instructionQueue.length < 12 &&\n (checkLegacyTxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, signers: _signer }) ||\n checkLegacyTxSize({ instructions: _itemIns, payer: this.feePayer, signers: _signer }))\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n splitInsIdx += item === splitIns[splitInsIdx] ? 1 : 0;\n // if add computeBudget still not exceed tx size limit\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signer,\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n checkLegacyTxSize({\n instructions: computeBudgetConfig\n ? [...computeBudgetData.instructions, ...instructionQueue]\n : [...instructionQueue],\n payer: this.feePayer,\n signers: _signers.map((s) => s.publicKey),\n })\n ) {\n allTransactions.push(new Transaction().add(...computeBudgetData.instructions, ...instructionQueue));\n } else {\n allTransactions.push(new Transaction().add(...instructionQueue));\n }\n allSigners.push(_signers);\n }\n allTransactions.forEach((tx) => (tx.feePayer = this.feePayer));\n\n if (this.owner?.signer) {\n allSigners.forEach((signers) => {\n if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) signers.push(this.owner!.signer!);\n });\n }\n\n return {\n builder: this,\n transactions: allTransactions,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const {\n sequentially,\n onTxUpdate,\n skipTxCount = 0,\n recentBlockHash: propBlockHash,\n skipPreflight = true,\n } = executeParams || {};\n const recentBlockHash = propBlockHash ?? (await getRecentBlockHash(this.connection, this.blockhashCommitment));\n allTransactions.forEach(async (tx, idx) => {\n tx.recentBlockhash = recentBlockHash;\n if (allSigners[idx].length) tx.sign(...allSigners[idx]);\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n let i = 0;\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n ++i;\n if (i <= skipTxCount) {\n txIds.push(\"tx skipped\");\n continue;\n }\n const txId = await sendAndConfirmTransaction(\n this.connection,\n tx,\n this.signers.find((s) => s.publicKey.equals(this.owner!.publicKey))\n ? this.signers\n : [...this.signers, this.owner.signer!],\n { skipPreflight },\n );\n txIds.push(txId);\n }\n\n return {\n txIds,\n signedTxs: allTransactions,\n };\n }\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n return await this.connection.sendRawTransaction(tx.serialize(), { skipPreflight });\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const needSignedTx = await this.signAllTransactions(\n allTransactions.slice(skipTxCount, allTransactions.length),\n );\n const signedTxs = [...allTransactions.slice(0, skipTxCount), ...needSignedTx];\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n if (i < skipTxCount) {\n // success before, do not send again\n processedTxs.push({ txId: \"\", status: \"success\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n checkSendTx();\n }\n const txId = await this.connection.sendRawTransaction(signedTxs[i].serialize(), { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n 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 if (!signatureResult.err) 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 });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n\n public async sizeCheckBuildV0(\n props?: Record<string, any> & {\n computeBudgetConfig?: ComputeBudgetConfig;\n lookupTableCache?: CacheLTA;\n lookupTableAddress?: string[];\n splitIns?: TransactionInstruction[];\n network?: NetworkName;\n },\n ): Promise<MultiTxV0BuildData> {\n const {\n computeBudgetConfig,\n splitIns = [],\n lookupTableCache = {},\n lookupTableAddress = [],\n network = this.network,\n ...extInfo\n } = props || {};\n const lookupTableAddressAccount = {\n ...(this.cluster === \"devnet\" ? {} : getLookupTableCache(network)),\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, network });\n for (const [key, value] of Object.entries(newCacheLTA)) lookupTableAddressAccount[key] = value;\n\n const computeBudgetData: { instructions: TransactionInstruction[]; instructionTypes: string[] } =\n computeBudgetConfig\n ? addComputeBudget(computeBudgetConfig)\n : {\n instructions: [],\n instructionTypes: [],\n };\n\n const blockHash = await getRecentBlockHash(this.connection, this.blockhashCommitment);\n\n const signerKey: { [key: string]: Signer } = this.signers.reduce(\n (acc, cur) => ({ ...acc, [cur.publicKey.toBase58()]: cur }),\n {},\n );\n const allTransactions: VersionedTransaction[] = [];\n const allSigners: Signer[][] = [];\n\n let instructionQueue: TransactionInstruction[] = [];\n let splitInsIdx = 0;\n this.allInstructions.forEach((item) => {\n const _itemIns = [...instructionQueue, item];\n const _itemInsWithCompute = computeBudgetConfig ? [...computeBudgetData.instructions, ..._itemIns] : _itemIns;\n if (\n item !== splitIns[splitInsIdx] &&\n instructionQueue.length < 12 &&\n (checkV0TxSize({ instructions: _itemInsWithCompute, payer: this.feePayer, lookupTableAddressAccount }) ||\n checkV0TxSize({ instructions: _itemIns, payer: this.feePayer, lookupTableAddressAccount }))\n ) {\n // current ins add to queue still not exceed tx size limit\n instructionQueue.push(item);\n } else {\n if (instructionQueue.length === 0) throw Error(\"item ins too big\");\n splitInsIdx += item === splitIns[splitInsIdx] ? 1 : 0;\n const lookupTableAddress: undefined | CacheLTA = {};\n for (const item of [...new Set<string>(allLTA)]) {\n if (lookupTableAddressAccount[item] !== undefined) lookupTableAddress[item] = lookupTableAddressAccount[item];\n }\n // if add computeBudget still not exceed tx size limit\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(\n Array.from(\n new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n ),\n )\n .map((i) => signerKey[i])\n .filter((i) => i !== undefined),\n );\n instructionQueue = [item];\n }\n });\n\n if (instructionQueue.length > 0) {\n const _signerStrs = new Set<string>(\n instructionQueue.map((i) => i.keys.filter((ii) => ii.isSigner).map((ii) => ii.pubkey.toString())).flat(),\n );\n const _signers = [..._signerStrs.values()].map((i) => signerKey[i]).filter((i) => i !== undefined);\n\n if (\n computeBudgetConfig &&\n checkV0TxSize({\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n payer: this.feePayer,\n lookupTableAddressAccount,\n recentBlockhash: blockHash,\n })\n ) {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...computeBudgetData.instructions, ...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n } else {\n const messageV0 = new TransactionMessage({\n payerKey: this.feePayer,\n recentBlockhash: blockHash,\n instructions: [...instructionQueue],\n }).compileToV0Message(Object.values(lookupTableAddressAccount));\n allTransactions.push(new VersionedTransaction(messageV0));\n }\n allSigners.push(_signers);\n }\n\n if (this.owner?.signer) {\n allSigners.forEach((signers) => {\n if (!signers.some((s) => s.publicKey.equals(this.owner!.publicKey))) signers.push(this.owner!.signer!);\n });\n }\n\n return {\n builder: this,\n transactions: allTransactions,\n buildProps: props,\n signers: allSigners,\n instructionTypes: this.instructionTypes,\n execute: async (executeParams?: MultiTxExecuteParam) => {\n const {\n sequentially,\n onTxUpdate,\n skipTxCount = 0,\n recentBlockHash: propBlockHash,\n skipPreflight = true,\n } = executeParams || {};\n allTransactions.map(async (tx, idx) => {\n if (allSigners[idx].length) tx.sign(allSigners[idx]);\n if (propBlockHash) tx.message.recentBlockhash = propBlockHash;\n });\n printSimulate(allTransactions);\n if (this.owner?.isKeyPair) {\n if (sequentially) {\n let i = 0;\n const txIds: string[] = [];\n for (const tx of allTransactions) {\n ++i;\n if (i <= skipTxCount) {\n console.log(\"skip tx: \", i);\n txIds.push(\"tx skipped\");\n continue;\n }\n const txId = await this.connection.sendTransaction(tx, { skipPreflight });\n await confirmTransaction(this.connection, txId);\n\n txIds.push(txId);\n }\n\n return { txIds, signedTxs: allTransactions };\n }\n\n return {\n txIds: await Promise.all(\n allTransactions.map(async (tx) => {\n return await this.connection.sendTransaction(tx, { skipPreflight });\n }),\n ),\n signedTxs: allTransactions,\n };\n }\n if (this.signAllTransactions) {\n const needSignedTx = await this.signAllTransactions(\n allTransactions.slice(skipTxCount, allTransactions.length),\n );\n const signedTxs = [...allTransactions.slice(0, skipTxCount), ...needSignedTx];\n if (sequentially) {\n let i = 0;\n const processedTxs: TxUpdateParams[] = [];\n const checkSendTx = async (): Promise<void> => {\n if (!signedTxs[i]) return;\n if (i < skipTxCount) {\n // success before, do not send again\n processedTxs.push({ txId: \"\", status: \"success\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n checkSendTx();\n return;\n }\n const txId = await this.connection.sendTransaction(signedTxs[i], { skipPreflight });\n processedTxs.push({ txId, status: \"sent\", signedTx: signedTxs[i] });\n onTxUpdate?.([...processedTxs]);\n i++;\n 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 if (!signatureResult.err) 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 });\n txIds.push(txId);\n }\n return { txIds, signedTxs };\n }\n }\n throw new Error(\"please provide owner in keypair format or signAllTransactions function\");\n },\n extInfo: extInfo || {},\n };\n }\n}\n","import 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\");\nexport const OBSERVATION_SEED = Buffer.from(\"observation\", \"utf8\");\n\nexport function getPdaAmmConfigId(\n programId: PublicKey,\n index: number,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([AMM_CONFIG_SEED, u16ToBytes(index)], programId);\n}\n\nexport function getPdaPoolId(\n programId: PublicKey,\n ammConfigId: PublicKey,\n mintA: PublicKey,\n mintB: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_SEED, ammConfigId.toBuffer(), mintA.toBuffer(), mintB.toBuffer()], programId);\n}\n\nexport function getPdaPoolVaultId(\n programId: PublicKey,\n poolId: PublicKey,\n vaultMint: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_VAULT_SEED, poolId.toBuffer(), vaultMint.toBuffer()], programId);\n}\n\nexport function getPdaPoolRewardVaulId(\n programId: PublicKey,\n poolId: PublicKey,\n rewardMint: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_REWARD_VAULT_SEED, poolId.toBuffer(), rewardMint.toBuffer()], programId);\n}\n\nexport function getPdaTickArrayAddress(\n programId: PublicKey,\n poolId: PublicKey,\n startIndex: number,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([TICK_ARRAY_SEED, poolId.toBuffer(), i32ToBytes(startIndex)], programId);\n}\n\nexport function getPdaProtocolPositionAddress(\n programId: PublicKey,\n poolId: PublicKey,\n tickLower: number,\n tickUpper: number,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress(\n [POSITION_SEED, poolId.toBuffer(), i32ToBytes(tickLower), i32ToBytes(tickUpper)],\n programId,\n );\n}\n\nexport function getPdaPersonalPositionAddress(\n programId: PublicKey,\n nftMint: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POSITION_SEED, nftMint.toBuffer()], programId);\n}\n\nexport function getPdaMetadataKey(mint: PublicKey): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress(\n [Buffer.from(\"metadata\", \"utf8\"), METADATA_PROGRAM_ID.toBuffer(), mint.toBuffer()],\n METADATA_PROGRAM_ID,\n );\n}\n\nexport function getPdaOperationAccount(programId: PublicKey): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([OPERATION_SEED], programId);\n}\n\nexport function getPdaExBitmapAccount(\n programId: PublicKey,\n poolId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_TICK_ARRAY_BITMAP_SEED, poolId.toBuffer()], programId);\n}\n\nexport function getPdaObservationAccount(\n programId: PublicKey,\n poolId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([OBSERVATION_SEED, poolId.toBuffer()], programId);\n}\n\nexport const POOL_LOCK_ID_SEED = Buffer.from(\"locked_position\", \"utf8\");\nexport function getPdaLockPositionId(\n programId: PublicKey,\n positionId: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_LOCK_ID_SEED, positionId.toBuffer()], programId);\n}\n\nexport function getPdaLockClPositionIdV2(\n programId: PublicKey,\n lockNftMint: PublicKey,\n): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([POOL_LOCK_ID_SEED, lockNftMint.toBuffer()], programId);\n}\n","import { TOKEN_2022_PROGRAM_ID } from \"@solana/spl-token\";\nimport { Connection, EpochInfo, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport {\n ClmmPoolInfo,\n ClmmPoolRewardInfo,\n ClmmPoolRewardLayoutInfo,\n ComputeClmmPoolInfo,\n ReturnTypeComputeAmountOut,\n ReturnTypeComputeAmountOutBaseOut,\n ReturnTypeComputeAmountOutFormat,\n ReturnTypeFetchExBitmaps,\n ReturnTypeFetchMultiplePoolTickArrays,\n ReturnTypeGetLiquidityAmountOut,\n SDKParsedConcentratedInfo,\n TickArrayBitmapExtensionType,\n} from \"../type\";\n\nimport { ApiV3PoolInfoConcentratedItem, ApiV3Token } from \"@/api/type\";\n\nimport { TokenAccountRaw } from \"@/cobaltx/account/types\";\nimport {\n getMultipleAccountsInfo,\n getMultipleAccountsInfoWithCustomFlags,\n getTransferAmountFeeV2,\n minExpirationTime,\n solToWSol,\n} from \"@/common\";\nimport { Percent, Price, Token, TokenAmount } from \"@/module\";\nimport Decimal from \"decimal.js\";\nimport { PoolInfoLayout, PositionInfoLayout, TickArrayBitmapExtensionLayout, TickArrayLayout } from \"../layout\";\nimport { MAX_SQRT_PRICE_X64, MAX_TICK, MIN_SQRT_PRICE_X64, MIN_TICK, NEGATIVE_ONE, Q64, ZERO } from \"./constants\";\nimport { LiquidityMath, MathUtil, SqrtPriceMath, SwapMath } from \"./math\";\nimport { getPdaExBitmapAccount, getPdaPersonalPositionAddress, getPdaTickArrayAddress } from \"./pda\";\nimport { PositionUtils } from \"./position\";\nimport { TICK_ARRAY_BITMAP_SIZE, Tick, TickArray, TickUtils } from \"./tick\";\nimport { TickArrayBitmap, TickArrayBitmapExtensionUtils } from \"./tickarrayBitmap\";\nimport { TickQuery } from \"./tickQuery\";\nimport { NetworkName } from \"@/config\";\n\nexport class PoolUtils {\n public network: NetworkName;\n\n constructor(network: NetworkName) {\n this.network = network;\n }\n\n public static getOutputAmountAndRemainAccounts(\n poolInfo: ComputeClmmPoolInfo,\n tickArrayCache: { [key: string]: TickArray },\n inputTokenMint: PublicKey,\n inputAmount: BN,\n sqrtPriceLimitX64?: BN,\n catchLiquidityInsufficient = false,\n ): {\n allTrade: boolean;\n expectedAmountOut: BN;\n remainingAccounts: PublicKey[];\n executionPrice: BN;\n feeAmount: BN;\n } {\n const zeroForOne = inputTokenMint.toBase58() === poolInfo.mintA.address;\n\n const allNeededAccounts: PublicKey[] = [];\n const {\n isExist,\n startIndex: firstTickArrayStartIndex,\n nextAccountMeta,\n } = this.getFirstInitializedTickArray(poolInfo, zeroForOne);\n if (!isExist || firstTickArrayStartIndex === undefined || !nextAccountMeta) throw new Error(\"Invalid tick array\");\n\n // try {\n // const preTick = this.preInitializedTickArrayStartIndex(poolInfo, !zeroForOne)\n // if (preTick.isExist) {\n // const { publicKey: address } = getPdaTickArrayAddress(\n // poolInfo.programId,\n // poolInfo.id,\n // preTick.nextStartIndex\n // );\n // allNeededAccounts.push(address)\n // }\n // } catch (e) { /* empty */ }\n\n allNeededAccounts.push(nextAccountMeta);\n const {\n allTrade,\n amountCalculated: outputAmount,\n accounts: reaminAccounts,\n sqrtPriceX64: executionPrice,\n feeAmount,\n } = SwapMath.swapCompute(\n poolInfo.programId,\n poolInfo.id,\n tickArrayCache,\n poolInfo.tickArrayBitmap,\n poolInfo.exBitmapInfo,\n zeroForOne,\n poolInfo.ammConfig.tradeFeeRate,\n poolInfo.liquidity,\n poolInfo.tickCurrent,\n poolInfo.tickSpacing,\n poolInfo.sqrtPriceX64,\n inputAmount,\n firstTickArrayStartIndex,\n sqrtPriceLimitX64,\n catchLiquidityInsufficient,\n );\n allNeededAccounts.push(...reaminAccounts);\n return {\n allTrade,\n expectedAmountOut: outputAmount.mul(NEGATIVE_ONE),\n remainingAccounts: allNeededAccounts,\n executionPrice,\n feeAmount,\n };\n }\n\n public static getInputAmountAndRemainAccounts(\n poolInfo: ComputeClmmPoolInfo,\n tickArrayCache: { [key: string]: TickArray },\n outputTokenMint: PublicKey,\n outputAmount: BN,\n sqrtPriceLimitX64?: BN,\n ): { expectedAmountIn: BN; remainingAccounts: PublicKey[]; executionPrice: BN; feeAmount: BN } {\n const zeroForOne = outputTokenMint.toBase58() === poolInfo.mintB.address;\n\n const allNeededAccounts: PublicKey[] = [];\n const {\n isExist,\n startIndex: firstTickArrayStartIndex,\n nextAccountMeta,\n } = this.getFirstInitializedTickArray(poolInfo, zeroForOne);\n if (!isExist || firstTickArrayStartIndex === undefined || !nextAccountMeta) throw new Error(\"Invalid tick array\");\n\n try {\n const preTick = this.preInitializedTickArrayStartIndex(poolInfo, zeroForOne);\n if (preTick.isExist) {\n const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, preTick.nextStartIndex);\n allNeededAccounts.push(address);\n }\n } catch (e) {\n /* empty */\n }\n\n allNeededAccounts.push(nextAccountMeta);\n const {\n amountCalculated: inputAmount,\n accounts: reaminAccounts,\n sqrtPriceX64: executionPrice,\n feeAmount,\n } = SwapMath.swapCompute(\n poolInfo.programId,\n poolInfo.id,\n tickArrayCache,\n poolInfo.tickArrayBitmap,\n poolInfo.exBitmapInfo,\n zeroForOne,\n poolInfo.ammConfig.tradeFeeRate,\n poolInfo.liquidity,\n poolInfo.tickCurrent,\n poolInfo.tickSpacing,\n poolInfo.sqrtPriceX64,\n outputAmount.mul(NEGATIVE_ONE),\n firstTickArrayStartIndex,\n sqrtPriceLimitX64,\n );\n allNeededAccounts.push(...reaminAccounts);\n return { expectedAmountIn: inputAmount, remainingAccounts: allNeededAccounts, executionPrice, feeAmount };\n }\n\n public static getFirstInitializedTickArray(\n poolInfo: ComputeClmmPoolInfo,\n zeroForOne: boolean,\n ):\n | { isExist: true; startIndex: number; nextAccountMeta: PublicKey }\n | { isExist: false; startIndex: undefined; nextAccountMeta: undefined } {\n const { isInitialized, startIndex } = PoolUtils.isOverflowDefaultTickarrayBitmap(poolInfo.tickSpacing, [\n poolInfo.tickCurrent,\n ])\n ? TickArrayBitmapExtensionUtils.checkTickArrayIsInit(\n TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing),\n poolInfo.tickSpacing,\n poolInfo.exBitmapInfo,\n )\n : TickUtils.checkTickArrayIsInitialized(\n TickUtils.mergeTickArrayBitmap(poolInfo.tickArrayBitmap),\n poolInfo.tickCurrent,\n poolInfo.tickSpacing,\n );\n\n if (isInitialized) {\n const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, startIndex);\n return {\n isExist: true,\n startIndex,\n nextAccountMeta: address,\n };\n }\n const { isExist, nextStartIndex } = this.nextInitializedTickArrayStartIndex(\n poolInfo,\n TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing),\n zeroForOne,\n );\n if (isExist) {\n const { publicKey: address } = getPdaTickArrayAddress(poolInfo.programId, poolInfo.id, nextStartIndex);\n return {\n isExist: true,\n startIndex: nextStartIndex,\n nextAccountMeta: address,\n };\n }\n return { isExist: false, nextAccountMeta: undefined, startIndex: undefined };\n }\n\n public static preInitializedTickArrayStartIndex(\n poolInfo: ComputeClmmPoolInfo,\n zeroForOne: boolean,\n ): { isExist: boolean; nextStartIndex: number } {\n const currentOffset = Math.floor(poolInfo.tickCurrent / TickQuery.tickCount(poolInfo.tickSpacing));\n\n const result: number[] = !zeroForOne\n ? TickUtils.searchLowBitFromStart(\n poolInfo.tickArrayBitmap,\n poolInfo.exBitmapInfo,\n currentOffset - 1,\n 1,\n poolInfo.tickSpacing,\n )\n : TickUtils.searchHightBitFromStart(\n poolInfo.tickArrayBitmap,\n poolInfo.exBitmapInfo,\n currentOffset + 1,\n 1,\n poolInfo.tickSpacing,\n );\n\n return result.length > 0 ? { isExist: true, nextStartIndex: result[0] } : { isExist: false, nextStartIndex: 0 };\n }\n\n public static nextInitializedTickArrayStartIndex(\n poolInfo:\n | {\n tickCurrent: number;\n tickSpacing: number;\n tickArrayBitmap: BN[];\n exBitmapInfo: TickArrayBitmapExtensionType;\n }\n | ClmmPoolInfo,\n lastTickArrayStartIndex: number,\n zeroForOne: boolean,\n ): { isExist: boolean; nextStartIndex: number } {\n lastTickArrayStartIndex = TickQuery.getArrayStartIndex(poolInfo.tickCurrent, poolInfo.tickSpacing);\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { isInit: startIsInit, tickIndex: startIndex } = TickArrayBitmap.nextInitializedTickArrayStartIndex(\n TickUtils.mergeTickArrayBitmap(poolInfo.tickArrayBitmap),\n lastTickArrayStartIndex,\n poolInfo.tickSpacing,\n zeroForOne,\n );\n if (startIsInit) {\n return { isExist: true, nextStartIndex: startIndex };\n }\n lastTickArrayStartIndex = startIndex;\n\n const { isInit, tickIndex } = TickArrayBitmapExtensionUtils.nextInitializedTickArrayFromOneBitmap(\n lastTickArrayStartIndex,\n poolInfo.tickSpacing,\n zeroForOne,\n poolInfo.exBitmapInfo,\n );\n if (isInit) return { isExist: true, nextStartIndex: tickIndex };\n\n lastTickArrayStartIndex = tickIndex;\n\n if (lastTickArrayStartIndex < MIN_TICK || lastTickArrayStartIndex > MAX_TICK)\n return { isExist: false, nextStartIndex: 0 };\n }\n\n // const tickArrayBitmap = TickUtils.mergeTickArrayBitmap(\n // poolInfo.tickArrayBitmap\n // );\n // const currentOffset = TickUtils.getTickArrayOffsetInBitmapByTick(\n // poolInfo.tickCurrent,\n // poolInfo.tickSpacing\n // );\n // const result: number[] = zeroForOne ? TickUtils.searchLowBitFromStart(\n // tickArrayBitmap,\n // currentOffset - 1,\n // 0,\n // 1,\n // poolInfo.tickSpacing\n // ) : TickUtils.searchHightBitFromStart(\n // tickArrayBitmap,\n // currentOffset,\n // 1024,\n // 1,\n // poolInfo.tickSpacing\n // );\n\n // return result.length > 0 ? { isExist: true, nextStartIndex: result[0] } : { isExist: false, nextStartIndex: 0 }\n }\n\n public static async updatePoolRewardInfos({\n connection,\n apiPoolInfo,\n chainTime,\n poolLiquidity,\n rewardInfos,\n }: {\n connection: Connection;\n apiPoolInfo: ApiV3PoolInfoConcentratedItem;\n chainTime: number;\n poolLiquidity: BN;\n rewardInfos: ClmmPoolRewardLayoutInfo[];\n }): Promise<ClmmPoolRewardInfo[]> {\n const nRewardInfo: ClmmPoolRewardInfo[] = [];\n for (let i = 0; i < rewardInfos.length; i++) {\n const _itemReward = rewardInfos[i];\n const apiRewardProgram =\n apiPoolInfo.rewardDefaultInfos[i]?.mint.programId ??\n (await connection.getAccountInfo(_itemReward.tokenMint))?.owner;\n if (apiRewardProgram === undefined) throw Error(\"get new reward mint info error\");\n\n const itemReward: ClmmPoolRewardInfo = {\n ..._itemReward,\n perSecond: MathUtil.x64ToDecimal(_itemReward.emissionsPerSecondX64),\n remainingRewards: undefined,\n tokenProgramId: new PublicKey(apiRewardProgram),\n };\n\n if (itemReward.tokenMint.equals(PublicKey.default)) continue;\n if (chainTime <= itemReward.openTime.toNumber() || poolLiquidity.eq(ZERO)) {\n nRewardInfo.push(itemReward);\n continue;\n }\n\n const latestUpdateTime = new BN(Math.min(itemReward.endTime.toNumber(), chainTime));\n const timeDelta = latestUpdateTime.sub(itemReward.lastUpdateTime);\n const rewardGrowthDeltaX64 = MathUtil.mulDivFloor(timeDelta, itemReward.emissionsPerSecondX64, poolLiquidity);\n const rewardGrowthGlobalX64 = itemReward.rewardGrowthGlobalX64.add(rewardGrowthDeltaX64);\n const rewardEmissionedDelta = MathUtil.mulDivFloor(timeDelta, itemReward.emissionsPerSecondX64, Q64);\n const rewardTotalEmissioned = itemReward.rewardTotalEmissioned.add(rewardEmissionedDelta);\n nRewardInfo.push({\n ...itemReward,\n rewardGrowthGlobalX64,\n rewardTotalEmissioned,\n lastUpdateTime: latestUpdateTime,\n });\n }\n return nRewardInfo;\n }\n\n public static isOverflowDefaultTickarrayBitmap(tickSpacing: number, tickarrayStartIndexs: number[]): boolean {\n const { maxTickBoundary, minTickBoundary } = this.tickRange(tickSpacing);\n\n for (const tickIndex of tickarrayStartIndexs) {\n const tickarrayStartIndex = TickUtils.getTickArrayStartIndexByTick(tickIndex, tickSpacing);\n\n if (tickarrayStartIndex >= maxTickBoundary || tickarrayStartIndex < minTickBoundary) {\n return true;\n }\n }\n\n return false;\n }\n\n public static tickRange(tickSpacing: number): {\n maxTickBoundary: number;\n minTickBoundary: number;\n } {\n let maxTickBoundary = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n let minTickBoundary = -maxTickBoundary;\n\n if (maxTickBoundary > MAX_TICK) {\n maxTickBoundary = TickQuery.getArrayStartIndex(MAX_TICK, tickSpacing) + TickQuery.tickCount(tickSpacing);\n }\n if (minTickBoundary < MIN_TICK) {\n minTickBoundary = TickQuery.getArrayStartIndex(MIN_TICK, tickSpacing);\n }\n return { maxTickBoundary, minTickBoundary };\n }\n\n public static get_tick_array_offset(tickarrayStartIndex: number, tickSpacing: number): number {\n if (!TickQuery.checkIsValidStartIndex(tickarrayStartIndex, tickSpacing)) {\n throw new Error(\"No enough initialized tickArray\");\n }\n\n return (tickarrayStartIndex / TickQuery.tickCount(tickSpacing)) * TICK_ARRAY_BITMAP_SIZE;\n }\n\n static async fetchExBitmaps({\n connection,\n exBitmapAddress,\n batchRequest,\n }: {\n connection: Connection;\n exBitmapAddress: PublicKey[];\n batchRequest: boolean;\n }): Promise<ReturnTypeFetchExBitmaps> {\n const fetchedBitmapAccount = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n exBitmapAddress.map((i) => ({ pubkey: i })),\n { batchRequest },\n );\n\n const returnTypeFetchExBitmaps: ReturnTypeFetchExBitmaps = {};\n for (const item of fetchedBitmapAccount) {\n if (item.accountInfo === null) continue;\n\n returnTypeFetchExBitmaps[item.pubkey.toString()] = TickArrayBitmapExtensionLayout.decode(item.accountInfo.data);\n }\n return returnTypeFetchExBitmaps;\n }\n\n static async fetchMultiplePoolTickArrays({\n connection,\n poolKeys,\n batchRequest,\n }: {\n connection: Connection;\n poolKeys: Omit<ComputeClmmPoolInfo, \"ammConfig\">[];\n batchRequest?: boolean;\n }): Promise<ReturnTypeFetchMultiplePoolTickArrays> {\n const tickArraysToPoolId: { [key: string]: PublicKey } = {};\n const tickArrays: { pubkey: PublicKey }[] = [];\n for (const itemPoolInfo of poolKeys) {\n const currentTickArrayStartIndex = TickUtils.getTickArrayStartIndexByTick(\n itemPoolInfo.tickCurrent,\n itemPoolInfo.tickSpacing,\n );\n const startIndexArray = TickUtils.getInitializedTickArrayInRange(\n itemPoolInfo.tickArrayBitmap,\n itemPoolInfo.exBitmapInfo,\n itemPoolInfo.tickSpacing,\n currentTickArrayStartIndex,\n 7,\n );\n for (const itemIndex of startIndexArray) {\n const { publicKey: tickArrayAddress } = getPdaTickArrayAddress(\n itemPoolInfo.programId,\n itemPoolInfo.id,\n itemIndex,\n );\n tickArrays.push({ pubkey: tickArrayAddress });\n tickArraysToPoolId[tickArrayAddress.toString()] = itemPoolInfo.id;\n }\n }\n\n const fetchedTickArrays = await getMultipleAccountsInfoWithCustomFlags(connection, tickArrays, { batchRequest });\n\n const tickArrayCache: ReturnTypeFetchMultiplePoolTickArrays = {};\n\n for (const itemAccountInfo of fetchedTickArrays) {\n if (!itemAccountInfo.accountInfo) continue;\n const poolId = tickArraysToPoolId[itemAccountInfo.pubkey.toString()];\n if (!poolId) continue;\n if (tickArrayCache[poolId.toString()] === undefined) tickArrayCache[poolId.toString()] = {};\n\n const accountLayoutData = TickArrayLayout.decode(itemAccountInfo.accountInfo.data);\n\n tickArrayCache[poolId.toString()][accountLayoutData.startTickIndex] = {\n ...accountLayoutData,\n address: itemAccountInfo.pubkey,\n };\n }\n return tickArrayCache;\n }\n\n // deprecated, new api doesn't need\n static async fetchPoolsAccountPosition({\n pools,\n connection,\n ownerInfo,\n batchRequest = false,\n updateOwnerRewardAndFee = true,\n }: {\n pools: SDKParsedConcentratedInfo[];\n connection: Connection;\n ownerInfo: { wallet: PublicKey; tokenAccounts: TokenAccountRaw[] };\n batchRequest?: boolean;\n updateOwnerRewardAndFee?: boolean;\n }): Promise<SDKParsedConcentratedInfo[]> {\n const programIds: PublicKey[] = [];\n\n for (let index = 0; index < pools.length; index++) {\n const accountInfo = pools[index];\n\n if (accountInfo === null) continue;\n\n if (!programIds.find((i) => i.equals(accountInfo.state.programId))) programIds.push(accountInfo.state.programId);\n }\n\n if (ownerInfo) {\n const allMint = ownerInfo.tokenAccounts.map((i) => i.accountInfo.mint);\n const allPositionKey: PublicKey[] = [];\n for (const itemMint of allMint) {\n for (const itemProgramId of programIds) {\n allPositionKey.push(getPdaPersonalPositionAddress(itemProgramId, itemMint).publicKey);\n }\n }\n const positionAccountInfos = await getMultipleAccountsInfo(connection, allPositionKey, { batchRequest });\n const keyToTickArrayAddress: { [key: string]: PublicKey } = {};\n for (const itemAccountInfo of positionAccountInfos) {\n if (itemAccountInfo === null) continue;\n // TODO: add check\n\n const position = PositionInfoLayout.decode(itemAccountInfo.data);\n const itemPoolId = position.poolId.toString();\n const poolInfoA = pools.find((pool) => pool.state.id.toBase58() === itemPoolId);\n if (poolInfoA === undefined) continue;\n\n const poolInfo = poolInfoA.state;\n\n const priceLower = TickUtils._getTickPriceLegacy({\n poolInfo,\n tick: position.tickLower,\n baseIn: true,\n });\n const priceUpper = TickUtils._getTickPriceLegacy({\n poolInfo,\n tick: position.tickUpper,\n baseIn: true,\n });\n const { amountA, amountB } = LiquidityMath.getAmountsFromLiquidity(\n poolInfo.sqrtPriceX64,\n priceLower.tickSqrtPriceX64,\n priceUpper.tickSqrtPriceX64,\n position.liquidity,\n false,\n );\n\n const leverage = 1 / (1 - Math.sqrt(Math.sqrt(priceLower.price.div(priceUpper.price).toNumber())));\n\n poolInfoA.positionAccount = [\n ...(poolInfoA.positionAccount ?? []),\n {\n poolId: position.poolId,\n nftMint: position.nftMint,\n\n priceLower: priceLower.price,\n priceUpper: priceUpper.price,\n amountA,\n amountB,\n tickLower: position.tickLower,\n tickUpper: position.tickUpper,\n liquidity: position.liquidity,\n feeGrowthInsideLastX64A: position.feeGrowthInsideLastX64A,\n feeGrowthInsideLastX64B: position.feeGrowthInsideLastX64B,\n tokenFeesOwedA: position.tokenFeesOwedA,\n tokenFeesOwedB: position.tokenFeesOwedB,\n rewardInfos: position.rewardInfos.map((i) => ({\n ...i,\n pendingReward: new BN(0),\n })),\n\n leverage,\n tokenFeeAmountA: new BN(0),\n tokenFeeAmountB: new BN(0),\n },\n ];\n\n const tickArrayLowerAddress = await TickUtils.getTickArrayAddressByTick(\n poolInfoA.state.programId,\n position.poolId,\n position.tickLower,\n poolInfoA.state.tickSpacing,\n );\n const tickArrayUpperAddress = await TickUtils.getTickArrayAddressByTick(\n poolInfoA.state.programId,\n position.poolId,\n position.tickUpper,\n poolInfoA.state.tickSpacing,\n );\n keyToTickArrayAddress[\n `${poolInfoA.state.programId.toString()}-${position.poolId.toString()}-${position.tickLower}`\n ] = tickArrayLowerAddress;\n keyToTickArrayAddress[\n `${poolInfoA.state.programId.toString()}-${position.poolId.toString()}-${position.tickUpper}`\n ] = tickArrayUpperAddress;\n }\n\n if (updateOwnerRewardAndFee) {\n const tickArrayKeys = Object.values(keyToTickArrayAddress);\n const tickArrayDatas = await getMultipleAccountsInfo(connection, tickArrayKeys, { batchRequest });\n const tickArrayLayout = {};\n for (let index = 0; index < tickArrayKeys.length; index++) {\n const tickArrayData = tickArrayDatas[index];\n if (tickArrayData === null) continue;\n const key = tickArrayKeys[index].toString();\n tickArrayLayout[key] = TickArrayLayout.decode(tickArrayData.data);\n }\n\n for (const { state, positionAccount } of pools) {\n if (!positionAccount) continue;\n for (const itemPA of positionAccount) {\n const keyLower = `${state.programId.toString()}-${state.id.toString()}-${itemPA.tickLower}`;\n const keyUpper = `${state.programId.toString()}-${state.id.toString()}-${itemPA.tickUpper}`;\n const tickArrayLower = tickArrayLayout[keyToTickArrayAddress[keyLower].toString()];\n const tickArrayUpper = tickArrayLayout[keyToTickArrayAddress[keyUpper].toString()];\n const tickLowerState: Tick =\n tickArrayLower.ticks[TickUtils.getTickOffsetInArray(itemPA.tickLower, state.tickSpacing)];\n const tickUpperState: Tick =\n tickArrayUpper.ticks[TickUtils.getTickOffsetInArray(itemPA.tickUpper, state.tickSpacing)];\n const { tokenFeeAmountA, tokenFeeAmountB } = await PositionUtils.GetPositionFees(\n state,\n itemPA,\n tickLowerState,\n tickUpperState,\n );\n const rewardInfos = await PositionUtils.GetPositionRewards(state, itemPA, tickLowerState, tickUpperState);\n itemPA.tokenFeeAmountA = tokenFeeAmountA.gte(new BN(0)) ? tokenFeeAmountA : new BN(0);\n itemPA.tokenFeeAmountB = tokenFeeAmountB.gte(new BN(0)) ? tokenFeeAmountB : new BN(0);\n for (let i = 0; i < rewardInfos.length; i++) {\n itemPA.rewardInfos[i].pendingReward = rewardInfos[i].gte(new BN(0)) ? rewardInfos[i] : new BN(0);\n }\n }\n }\n }\n }\n return pools;\n }\n\n static computeAmountOut({\n poolInfo,\n tickArrayCache,\n baseMint,\n epochInfo,\n amountIn,\n slippage,\n priceLimit = new Decimal(0),\n catchLiquidityInsufficient = false,\n }: {\n poolInfo: ComputeClmmPoolInfo;\n tickArrayCache: { [key: string]: TickArray };\n baseMint: PublicKey;\n\n epochInfo: EpochInfo;\n\n amountIn: BN;\n slippage: number;\n priceLimit?: Decimal;\n catchLiquidityInsufficient: boolean;\n }): ReturnTypeComputeAmountOut {\n let sqrtPriceLimitX64: BN;\n const isBaseIn = baseMint.toBase58() === poolInfo.mintA.address;\n const [baseFeeConfig, outFeeConfig] = isBaseIn\n ? [poolInfo.mintA.extensions.feeConfig, poolInfo.mintB.extensions.feeConfig]\n : [poolInfo.mintB.extensions.feeConfig, poolInfo.mintA.extensions.feeConfig];\n\n if (priceLimit.equals(new Decimal(0))) {\n sqrtPriceLimitX64 = isBaseIn ? MIN_SQRT_PRICE_X64.add(new BN(1)) : MAX_SQRT_PRICE_X64.sub(new BN(1));\n } else {\n sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n priceLimit,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n }\n\n const realAmountIn = getTransferAmountFeeV2(amountIn, baseFeeConfig, epochInfo, false);\n\n const {\n allTrade,\n expectedAmountOut: _expectedAmountOut,\n remainingAccounts,\n executionPrice: _executionPriceX64,\n feeAmount,\n } = PoolUtils.getOutputAmountAndRemainAccounts(\n poolInfo,\n tickArrayCache,\n baseMint,\n realAmountIn.amount.sub(realAmountIn.fee ?? ZERO),\n sqrtPriceLimitX64,\n catchLiquidityInsufficient,\n );\n\n const amountOut = getTransferAmountFeeV2(_expectedAmountOut, outFeeConfig, epochInfo, false);\n\n const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n _executionPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const executionPrice = isBaseIn ? _executionPrice : new Decimal(1).div(_executionPrice);\n\n const _minAmountOut = _expectedAmountOut\n .mul(new BN(Math.floor((1 - slippage) * 10000000000)))\n .div(new BN(10000000000));\n const minAmountOut = getTransferAmountFeeV2(_minAmountOut, outFeeConfig, epochInfo, false);\n\n const poolPrice = isBaseIn ? poolInfo.currentPrice : new Decimal(1).div(poolInfo.currentPrice);\n\n const _numerator = new Decimal(executionPrice).sub(poolPrice).abs();\n const _denominator = poolPrice;\n const priceImpact = new Percent(\n new Decimal(_numerator).mul(10 ** 15).toFixed(0),\n new Decimal(_denominator).mul(10 ** 15).toFixed(0),\n );\n\n return {\n allTrade,\n realAmountIn,\n amountOut,\n minAmountOut,\n expirationTime: minExpirationTime(realAmountIn.expirationTime, amountOut.expirationTime),\n currentPrice: poolInfo.currentPrice,\n executionPrice,\n priceImpact,\n fee: feeAmount,\n remainingAccounts,\n executionPriceX64: _executionPriceX64,\n };\n }\n\n static computeAmountOutFormat({\n poolInfo,\n tickArrayCache,\n amountIn,\n tokenOut: _tokenOut,\n slippage,\n epochInfo,\n catchLiquidityInsufficient = false,\n }: {\n poolInfo: ComputeClmmPoolInfo;\n tickArrayCache: { [key: string]: TickArray };\n amountIn: BN;\n tokenOut: ApiV3Token;\n slippage: number;\n epochInfo: EpochInfo;\n catchLiquidityInsufficient?: boolean;\n }): ReturnTypeComputeAmountOutFormat {\n const baseIn = _tokenOut.address === poolInfo.mintB.address;\n const [inputMint, outMint] = baseIn ? [poolInfo.mintA, poolInfo.mintB] : [poolInfo.mintB, poolInfo.mintA];\n const [baseToken, outToken] = [\n new Token({\n ...inputMint,\n mint: inputMint.address,\n isToken2022: inputMint.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n }),\n new Token({\n ...outMint,\n mint: outMint.address,\n isToken2022: outMint.programId === TOKEN_2022_PROGRAM_ID.toBase58(),\n }),\n ];\n\n const {\n allTrade,\n realAmountIn: _realAmountIn,\n amountOut: _amountOut,\n minAmountOut: _minAmountOut,\n expirationTime,\n currentPrice,\n executionPrice,\n priceImpact,\n fee,\n remainingAccounts,\n executionPriceX64,\n } = PoolUtils.computeAmountOut({\n poolInfo,\n tickArrayCache,\n baseMint: new PublicKey(inputMint.address),\n amountIn,\n slippage,\n epochInfo,\n catchLiquidityInsufficient,\n });\n\n const realAmountIn = {\n ..._realAmountIn,\n amount: new TokenAmount(baseToken, _realAmountIn.amount),\n fee: _realAmountIn.fee === undefined ? undefined : new TokenAmount(baseToken, _realAmountIn.fee),\n };\n\n const amountOut = {\n ..._amountOut,\n amount: new TokenAmount(outToken, _amountOut.amount),\n fee: _amountOut.fee === undefined ? undefined : new TokenAmount(outToken, _amountOut.fee),\n };\n const minAmountOut = {\n ..._minAmountOut,\n amount: new TokenAmount(outToken, _minAmountOut.amount),\n fee: _minAmountOut.fee === undefined ? undefined : new TokenAmount(outToken, _minAmountOut.fee),\n };\n\n const _currentPrice = new Price({\n baseToken,\n denominator: new BN(10).pow(new BN(20 + baseToken.decimals)),\n quoteToken: outToken,\n numerator: currentPrice.mul(new Decimal(10 ** (20 + outToken.decimals))).toFixed(0),\n });\n const _executionPrice = new Price({\n baseToken,\n denominator: new BN(10).pow(new BN(20 + baseToken.decimals)),\n quoteToken: outToken,\n numerator: executionPrice.mul(new Decimal(10 ** (20 + outToken.decimals))).toFixed(0),\n });\n const _fee = new TokenAmount(baseToken, fee);\n\n return {\n allTrade,\n realAmountIn,\n amountOut,\n minAmountOut,\n expirationTime,\n currentPrice: _currentPrice,\n executionPrice: _executionPrice,\n priceImpact,\n fee: _fee,\n remainingAccounts,\n executionPriceX64,\n };\n }\n\n static computeAmountIn({\n poolInfo,\n tickArrayCache,\n baseMint,\n epochInfo,\n amountOut,\n slippage,\n priceLimit = new Decimal(0),\n }: {\n poolInfo: ComputeClmmPoolInfo;\n tickArrayCache: { [key: string]: TickArray };\n baseMint: PublicKey;\n\n epochInfo: EpochInfo;\n\n amountOut: BN;\n slippage: number;\n priceLimit?: Decimal;\n }): ReturnTypeComputeAmountOutBaseOut {\n const isBaseIn = baseMint.toBase58() === poolInfo.mintA.address;\n const feeConfigs = {\n [poolInfo.mintA.address]: poolInfo.mintA.extensions.feeConfig,\n [poolInfo.mintB.address]: poolInfo.mintB.extensions.feeConfig,\n };\n\n let sqrtPriceLimitX64: BN;\n if (priceLimit.equals(new Decimal(0))) {\n sqrtPriceLimitX64 = !isBaseIn ? MIN_SQRT_PRICE_X64.add(new BN(1)) : MAX_SQRT_PRICE_X64.sub(new BN(1));\n } else {\n sqrtPriceLimitX64 = SqrtPriceMath.priceToSqrtPriceX64(\n priceLimit,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n }\n\n const realAmountOut = getTransferAmountFeeV2(amountOut, feeConfigs[baseMint.toString()], epochInfo, true);\n\n const {\n expectedAmountIn: _expectedAmountIn,\n remainingAccounts,\n executionPrice: _executionPriceX64,\n feeAmount,\n } = PoolUtils.getInputAmountAndRemainAccounts(\n poolInfo,\n tickArrayCache,\n baseMint,\n realAmountOut.amount.sub(realAmountOut.fee ?? ZERO),\n sqrtPriceLimitX64,\n );\n\n const inMint = isBaseIn ? poolInfo.mintB.address : poolInfo.mintA.address;\n\n const amountIn = getTransferAmountFeeV2(_expectedAmountIn, feeConfigs[inMint], epochInfo, false);\n // const amountIn = getTransferAmountFee(\n // _expectedAmountIn,\n // token2022Infos[inMint.toString()]?.feeConfig,\n // epochInfo,\n // true,\n // );\n\n const _executionPrice = SqrtPriceMath.sqrtPriceX64ToPrice(\n _executionPriceX64,\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const executionPrice = isBaseIn ? _executionPrice : new Decimal(1).div(_executionPrice);\n\n const _maxAmountIn = _expectedAmountIn\n .mul(new BN(Math.floor((1 + slippage) * 10000000000)))\n .div(new BN(10000000000));\n // const maxAmountIn = getTransferAmountFee(\n // _maxAmountIn,\n // token2022Infos[inMint.toString()]?.feeConfig,\n // epochInfo,\n // true,\n // );\n const maxAmountIn = getTransferAmountFeeV2(_maxAmountIn, feeConfigs[inMint], epochInfo, true);\n\n const poolPrice = isBaseIn ? poolInfo.currentPrice : new Decimal(1).div(poolInfo.currentPrice);\n\n const _numerator = new Decimal(executionPrice).sub(poolPrice).abs();\n const _denominator = poolPrice;\n const priceImpact = new Percent(\n new Decimal(_numerator).mul(10 ** 15).toFixed(0),\n new Decimal(_denominator).mul(10 ** 15).toFixed(0),\n );\n\n return {\n amountIn,\n maxAmountIn,\n realAmountOut,\n expirationTime: minExpirationTime(amountIn.expirationTime, realAmountOut.expirationTime),\n currentPrice: poolInfo.currentPrice,\n executionPrice,\n priceImpact,\n fee: feeAmount,\n\n remainingAccounts,\n };\n }\n\n static estimateAprsForPriceRangeMultiplier({\n poolInfo,\n aprType,\n positionTickLowerIndex,\n positionTickUpperIndex,\n }: {\n poolInfo: ApiV3PoolInfoConcentratedItem;\n aprType: \"day\" | \"week\" | \"month\";\n\n positionTickLowerIndex: number;\n positionTickUpperIndex: number;\n }): {\n feeApr: number;\n rewardsApr: number[];\n apr: number;\n } {\n const aprInfo = poolInfo[aprType];\n\n const priceLower = TickUtils.getTickPrice({\n poolInfo,\n tick: positionTickLowerIndex,\n baseIn: true,\n }).price.toNumber();\n const priceUpper = TickUtils.getTickPrice({\n poolInfo,\n tick: positionTickUpperIndex,\n baseIn: true,\n }).price.toNumber();\n\n const _minPrice = Math.max(priceLower, aprInfo.priceMin);\n const _maxPrice = Math.min(priceUpper, aprInfo.priceMax);\n\n const sub = _maxPrice - _minPrice;\n\n const userRange = priceUpper - priceLower;\n const tradeRange = aprInfo.priceMax - aprInfo.priceMin;\n\n let p: number;\n\n if (sub <= 0) p = 0;\n else if (userRange === sub) p = tradeRange / sub;\n else if (tradeRange === sub) p = sub / userRange;\n else p = (sub / tradeRange) * (sub / userRange);\n\n return {\n feeApr: aprInfo.feeApr * p,\n rewardsApr: [(aprInfo.rewardApr[0] ?? 0) * p, (aprInfo.rewardApr[1] ?? 0) * p, (aprInfo.rewardApr[2] ?? 0) * p],\n apr: aprInfo.apr * p,\n };\n }\n\n static estimateAprsForPriceRangeDelta({\n poolInfo,\n poolLiquidity,\n aprType,\n mintPrice,\n liquidity,\n positionTickLowerIndex,\n positionTickUpperIndex,\n chainTime,\n network,\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 network: NetworkName;\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, network).toString()];\n const mintPriceB = mintPrice[solToWSol(poolInfo.mintB.address, network).toString()];\n const mintDecimalsA = poolInfo.mintA.decimals;\n const mintDecimalsB = poolInfo.mintB.decimals;\n\n if (!aprInfo || !mintPriceA || !mintPriceB) return { feeApr: 0, rewardsApr: [0, 0, 0], apr: 0 };\n\n const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n new Decimal(poolInfo.price),\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n\n const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(positionTickLowerIndex);\n const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(positionTickUpperIndex);\n\n const { amountSlippageA: poolLiquidityA, amountSlippageB: poolLiquidityB } =\n LiquidityMath.getAmountsFromLiquidityWithSlippage(\n sqrtPriceX64,\n sqrtPriceX64A,\n sqrtPriceX64B,\n poolLiquidity,\n false,\n false,\n 0,\n );\n\n const { amountSlippageA: userLiquidityA, amountSlippageB: userLiquidityB } =\n LiquidityMath.getAmountsFromLiquidityWithSlippage(\n sqrtPriceX64,\n sqrtPriceX64A,\n sqrtPriceX64B,\n liquidity,\n false,\n false,\n 0,\n );\n\n const poolTvl = new Decimal(poolLiquidityA.toString())\n .div(new Decimal(10).pow(mintDecimalsA))\n .mul(mintPriceA.value)\n .add(new Decimal(poolLiquidityB.toString()).div(new Decimal(10).pow(mintDecimalsB)).mul(mintPriceB.value));\n const userTvl = new Decimal(userLiquidityA.toString())\n .div(new Decimal(10).pow(mintDecimalsA))\n .mul(mintPriceA.value)\n .add(new Decimal(userLiquidityB.toString()).div(new Decimal(10).pow(mintDecimalsB)).mul(mintPriceB.value));\n\n const p = new Decimal(1).div(poolTvl.add(userTvl));\n\n const feesPerYear = new Decimal(aprInfo.volumeFee).mul(365).div(aprTypeDay);\n const feeApr = feesPerYear.mul(p).mul(100).toNumber();\n\n const SECONDS_PER_YEAR = 3600 * 24 * 365;\n\n const rewardsApr = poolInfo.rewardDefaultInfos.map((i) => {\n const iDecimal = i.mint.decimals;\n const iPrice = mintPrice[i.mint.address];\n\n if (\n chainTime < ((i as any).startTime ?? 0) ||\n chainTime > ((i as any).endTime ?? 0) ||\n !i.perSecond ||\n !iPrice ||\n iDecimal === undefined\n )\n return 0;\n\n return new Decimal(iPrice.value)\n .mul(new Decimal(i.perSecond).mul(SECONDS_PER_YEAR))\n .div(new Decimal(10).pow(iDecimal))\n .mul(p)\n .mul(100)\n .toNumber();\n });\n\n return {\n feeApr,\n rewardsApr,\n apr: feeApr + rewardsApr.reduce((a, b) => a + b, 0),\n };\n }\n\n static 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 static async fetchComputeMultipleClmmInfo({\n connection,\n poolList,\n rpcDataMap = {},\n }: {\n rpcDataMap?: Record<string, ReturnType<typeof PoolInfoLayout.decode>>;\n connection: Connection;\n poolList: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\" | \"price\">[];\n }): Promise<Record<string, ComputeClmmPoolInfo>> {\n const fetchRpcList = poolList.filter((p) => !rpcDataMap[p.id]).map((p) => new PublicKey(p.id));\n const rpcRes = await getMultipleAccountsInfo(connection, fetchRpcList);\n rpcRes.forEach((r, idx) => {\n if (!r) return;\n rpcDataMap[fetchRpcList[idx].toBase58()] = PoolInfoLayout.decode(r.data);\n });\n\n const pdaList = poolList.map(\n (poolInfo) => getPdaExBitmapAccount(new PublicKey(poolInfo.programId), new PublicKey(poolInfo.id)).publicKey,\n );\n\n const exBitData = await PoolUtils.fetchExBitmaps({\n connection,\n exBitmapAddress: pdaList,\n batchRequest: false,\n });\n\n return poolList.reduce(\n (acc, cur) => ({\n ...acc,\n [cur.id]: {\n ...rpcDataMap[cur.id],\n id: new PublicKey(cur.id),\n version: 6,\n programId: new PublicKey(cur.programId),\n mintA: cur.mintA,\n mintB: cur.mintB,\n ammConfig: {\n ...cur.config,\n id: new PublicKey(cur.config.id),\n fundOwner: \"\",\n },\n currentPrice: new Decimal(cur.price),\n exBitmapAccount: getPdaExBitmapAccount(new PublicKey(cur.programId), new PublicKey(cur.id)).publicKey,\n exBitmapInfo:\n exBitData[getPdaExBitmapAccount(new PublicKey(cur.programId), new PublicKey(cur.id)).publicKey.toBase58()],\n startTime: rpcDataMap[cur.id].startTime.toNumber(),\n rewardInfos: rpcDataMap[cur.id].rewardInfos,\n },\n }),\n {} as Record<string, ComputeClmmPoolInfo>,\n );\n }\n\n static async fetchComputeClmmInfo({\n connection,\n poolInfo,\n rpcData,\n }: {\n connection: Connection;\n poolInfo: Pick<ApiV3PoolInfoConcentratedItem, \"id\" | \"programId\" | \"mintA\" | \"mintB\" | \"config\" | \"price\">;\n rpcData?: ReturnType<typeof PoolInfoLayout.decode>;\n }): Promise<ComputeClmmPoolInfo> {\n return (\n await this.fetchComputeMultipleClmmInfo({\n connection,\n rpcDataMap: rpcData ? { [poolInfo.id]: rpcData } : undefined,\n poolList: [poolInfo],\n })\n )[poolInfo.id];\n }\n}\n\nexport function getLiquidityFromAmounts({\n poolInfo,\n tickLower,\n tickUpper,\n amountA,\n amountB,\n slippage,\n add,\n epochInfo,\n amountHasFee,\n}: {\n poolInfo: ApiV3PoolInfoConcentratedItem;\n tickLower: number;\n tickUpper: number;\n amountA: BN;\n amountB: BN;\n slippage: number;\n add: boolean;\n epochInfo: EpochInfo;\n amountHasFee: boolean;\n}): ReturnTypeGetLiquidityAmountOut {\n const [_tickLower, _tickUpper, _amountA, _amountB] =\n tickLower < tickUpper ? [tickLower, tickUpper, amountA, amountB] : [tickUpper, tickLower, amountB, amountA];\n const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n new Decimal(poolInfo.price),\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(_tickLower);\n const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(_tickUpper);\n\n const [amountFeeA, amountFeeB] = [\n getTransferAmountFeeV2(_amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, !amountHasFee),\n getTransferAmountFeeV2(_amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, !amountHasFee),\n ];\n\n const liquidity = LiquidityMath.getLiquidityFromTokenAmounts(\n sqrtPriceX64,\n sqrtPriceX64A,\n sqrtPriceX64B,\n amountFeeA.amount.sub(amountFeeA.fee ?? ZERO),\n amountFeeB.amount.sub(amountFeeB.fee ?? ZERO),\n );\n\n return LiquidityMath.getAmountsOutFromLiquidity({\n poolInfo,\n tickLower,\n tickUpper,\n liquidity,\n slippage,\n add,\n epochInfo,\n amountAddFee: !amountHasFee,\n });\n}\n\nconst mockRewardData = {\n volume: 0,\n volumeQuote: 0,\n volumeFee: 0,\n apr: 0,\n feeApr: 0,\n priceMin: 0,\n priceMax: 0,\n rewardApr: [],\n};\n\nexport function clmmComputeInfoToApiInfo(pool: ComputeClmmPoolInfo): ApiV3PoolInfoConcentratedItem {\n return {\n ...pool,\n type: \"Concentrated\",\n programId: pool.programId.toString(),\n id: pool.id.toString(),\n rewardDefaultInfos: [],\n rewardDefaultPoolInfos: \"Clmm\",\n price: pool.currentPrice.toNumber(),\n mintAmountA: 0,\n mintAmountB: 0,\n feeRate: pool.ammConfig.tradeFeeRate,\n openTime: pool.startTime.toString(),\n tvl: 0,\n\n day: mockRewardData,\n week: mockRewardData,\n month: mockRewardData,\n pooltype: [],\n\n farmUpcomingCount: 0,\n farmOngoingCount: 0,\n farmFinishedCount: 0,\n burnPercent: 0,\n config: {\n ...pool.ammConfig,\n id: pool.ammConfig.id.toString(),\n defaultRange: 0,\n defaultRangePoint: [],\n },\n };\n}\n","import { PublicKey } from \"@solana/web3.js\";\nimport BN, { isBN } from \"bn.js\";\n\nimport {\n bits,\n blob,\n Blob,\n Layout,\n offset as _offset,\n seq as _seq,\n Structure as _Structure,\n u32 as _u32,\n u8 as _u8,\n UInt,\n union as _union,\n Union as _Union,\n} from \"./buffer-layout\";\n\nexport * from \"./buffer-layout\";\nexport { blob };\n\nexport class BNLayout<P extends string = \"\"> extends Layout<BN, P> {\n blob: Layout<Buffer>;\n signed: boolean;\n\n constructor(span: number, signed: boolean, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends, but it desn't matter\n super(span, property);\n this.blob = blob(span);\n this.signed = signed;\n }\n\n /** @override */\n decode(b: Buffer, offset = 0): BN {\n const num = new BN(this.blob.decode(b, offset), 10, \"le\");\n if (this.signed) {\n return num.fromTwos(this.span * 8).clone();\n }\n return num;\n }\n\n /** @override */\n encode(src: BN, b: Buffer, offset = 0): number {\n if (typeof src === \"number\") src = new BN(src); // src will pass a number accidently in union\n if (this.signed) {\n src = src.toTwos(this.span * 8);\n }\n return this.blob.encode(src.toArrayLike(Buffer, \"le\", this.span), b, offset);\n }\n}\n\nexport class WideBits<P extends string = \"\"> extends Layout<Record<string, boolean>, P> {\n _lower: any;\n _upper: any;\n // TODO: unknown\n constructor(property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(8, property);\n this._lower = bits(_u32(), false);\n this._upper = bits(_u32(), false);\n }\n\n addBoolean(property: string): void {\n if (this._lower.fields.length < 32) {\n this._lower.addBoolean(property);\n } else {\n this._upper.addBoolean(property);\n }\n }\n\n decode(b: Buffer, offset = 0): Record<string, boolean> {\n const lowerDecoded = this._lower.decode(b, offset);\n const upperDecoded = this._upper.decode(b, offset + this._lower.span);\n return { ...lowerDecoded, ...upperDecoded };\n }\n\n encode(src: any /* TEMP */, b: Buffer, offset = 0): any {\n return this._lower.encode(src, b, offset) + this._upper.encode(src, b, offset + this._lower.span);\n }\n}\n\nexport function u8<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(1, property);\n}\n\nexport function u32<P extends string = \"\">(property?: P): UInt<number, P> {\n return new UInt(4, property);\n}\n\nexport function u64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, false, property);\n}\n\nexport function u128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, false, property);\n}\n\nexport function i8<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(1, true, property);\n}\n\nexport function i64<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(8, true, property);\n}\n\nexport function i128<P extends string = \"\">(property?: P): BNLayout<P> {\n return new BNLayout(16, true, property);\n}\n\nexport class WrappedLayout<T, U, P extends string = \"\"> extends Layout<U, P> {\n layout: Layout<T>;\n decoder: (data: T) => U;\n encoder: (src: U) => T;\n\n constructor(layout: Layout<T>, decoder: (data: T) => U, encoder: (src: U) => T, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(layout.span, property);\n this.layout = layout;\n this.decoder = decoder;\n this.encoder = encoder;\n }\n\n decode(b: Buffer, offset?: number): U {\n return this.decoder(this.layout.decode(b, offset));\n }\n\n encode(src: U, b: Buffer, offset?: number): number {\n return this.layout.encode(this.encoder(src), b, offset);\n }\n\n getSpan(b: Buffer, offset?: number): number {\n return this.layout.getSpan(b, offset);\n }\n}\n\nexport function publicKey<P extends string = \"\">(property?: P): Layout<PublicKey, P> {\n return new WrappedLayout(\n blob(32),\n (b: Buffer) => new PublicKey(b),\n (key: PublicKey) => key.toBuffer(),\n property,\n );\n}\n\nexport class OptionLayout<T, P> extends Layout<T | null, P> {\n layout: Layout<T>;\n discriminator: Layout<number>;\n\n constructor(layout: Layout<T>, property?: P) {\n //@ts-expect-error type wrong for super()'s type different from extends , but it desn't matter\n super(-1, property);\n this.layout = layout;\n this.discriminator = _u8();\n }\n\n encode(src: T | null, b: Buffer, offset = 0): number {\n if (src === null || src === undefined) {\n return this.discriminator.encode(0, b, offset);\n }\n this.discriminator.encode(1, b, offset);\n return this.layout.encode(src, b, offset + 1) + 1;\n }\n\n decode(b: Buffer, offset = 0): T | null {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return null;\n } else if (discriminator === 1) {\n return this.layout.decode(b, offset + 1);\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n\n getSpan(b: Buffer, offset = 0): number {\n const discriminator = this.discriminator.decode(b, offset);\n if (discriminator === 0) {\n return 1;\n } else if (discriminator === 1) {\n return this.layout.getSpan(b, offset + 1) + 1;\n }\n throw new Error(\"Invalid option \" + this.property);\n }\n}\n\nexport function option<T, P extends string = \"\">(layout: Layout<T>, property?: P): Layout<T | null, P> {\n return new OptionLayout<T, P>(layout, property);\n}\n\nexport function bool<P extends string = \"\">(property?: P): Layout<boolean, P> {\n return new WrappedLayout(_u8(), decodeBool, encodeBool, property);\n}\n\nexport function decodeBool(value: number): boolean {\n if (value === 0) {\n return false;\n } else if (value === 1) {\n return true;\n }\n throw new Error(\"Invalid bool: \" + value);\n}\n\nexport function encodeBool(value: boolean): number {\n return value ? 1 : 0;\n}\n\nexport function vec<T, P extends string = \"\">(elementLayout: Layout<T>, property?: P): Layout<T[], P> {\n const length = _u32(\"length\");\n const layout: Layout<{ values: T[] }> = struct([\n length,\n seq(elementLayout, _offset(length, -length.span), \"values\"),\n ]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport function tagged<T, P extends string = \"\">(tag: BN, layout: Layout<T>, property?: P): Layout<T, P> {\n const wrappedLayout: Layout<{ tag: BN; data: T }> = struct([u64(\"tag\"), layout.replicate(\"data\")]) as any; // Something I don't know\n\n function decodeTag({ tag: receivedTag, data }: { tag: BN; data: T }): T {\n if (!receivedTag.eq(tag)) {\n throw new Error(\"Invalid tag, expected: \" + tag.toString(\"hex\") + \", got: \" + receivedTag.toString(\"hex\"));\n }\n return data;\n }\n\n return new WrappedLayout(wrappedLayout, decodeTag, (data) => ({ tag, data }), property);\n}\n\nexport function vecU8<P extends string = \"\">(property?: P): Layout<Buffer, P> {\n const length = _u32(\"length\");\n const layout: Layout<{ data: Buffer }> = struct([length, blob(_offset(length, -length.span), \"data\")]) as any; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ data }) => data,\n (data) => ({ data }),\n property,\n );\n}\n\nexport function str<P extends string = \"\">(property?: P): Layout<string, P> {\n return new WrappedLayout(\n vecU8(),\n (data) => data.toString(\"utf-8\"),\n (s) => Buffer.from(s, \"utf-8\"),\n property,\n );\n}\n\nexport interface EnumLayout<T, P extends string = \"\"> extends Layout<T, P> {\n registry: Record<string, Layout<any>>;\n}\n\nexport function rustEnum<T, P extends string = \"\">(variants: Layout<any>[], property?: P): EnumLayout<T, P> {\n const unionLayout = _union(_u8(), property);\n variants.forEach((variant, index) => unionLayout.addVariant(index, variant, variant.property));\n return unionLayout as any; // ?why use UnionLayout? This must be a fault\n}\n\nexport function array<T, P extends string = \"\">(\n elementLayout: Layout<T>,\n length: number,\n property?: P,\n): Layout<T[], P> {\n const layout = struct([seq(elementLayout, length, \"values\")]) as any as Layout<{ values: T[] }>; // Something I don't know\n return new WrappedLayout(\n layout,\n ({ values }) => values,\n (values) => ({ values }),\n property,\n );\n}\n\nexport class Structure<T, P, D extends { [key: string]: any; }> extends _Structure<T, P, D> {\n /** @override */\n decode(b: Buffer, offset?: number): D {\n return super.decode(b, offset);\n }\n}\n\nexport function struct<T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n): T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any {\n //@ts-expect-error this type is not quite satisfied the define, but, never no need to worry about.\n return new Structure(fields, property, decodePrefixes);\n}\n\nexport type GetLayoutSchemaFromStructure<T extends Structure<any, any, any>> = T extends Structure<any, any, infer S>\n ? S\n : any;\nexport type GetStructureFromLayoutSchema<S extends { [key: string]: any; }> = Structure<any, any, S>;\n\nexport class Union<Schema extends { [key: string]: any; }> extends _Union<Schema> {\n encodeInstruction(instruction: any): Buffer {\n const instructionMaxSpan = Math.max(...Object.values(this.registry).map((r) => r.span));\n const b = Buffer.alloc(instructionMaxSpan);\n return b.slice(0, this.encode(instruction, b));\n }\n\n decodeInstruction(instruction: any): Partial<Schema> {\n return this.decode(instruction);\n }\n}\nexport function union<UnionSchema extends { [key: string]: any } = any>(\n discr: any,\n defaultLayout?: any,\n property?: string,\n): Union<UnionSchema> {\n return new Union(discr, defaultLayout, property);\n}\n\nclass Zeros extends Blob {\n decode(b: Buffer, offset: number): Buffer {\n const slice = super.decode(b, offset);\n if (!slice.every((v) => v === 0)) {\n throw new Error(\"nonzero padding bytes\");\n }\n return slice;\n }\n}\n\nexport function zeros(length: number): Zeros {\n return new Zeros(length);\n}\n\nexport function seq<T, P extends string = \"\", AnotherP extends string = \"\">(\n elementLayout: Layout<T, P>,\n count: number | BN | Layout<BN | number, P>,\n property?: AnotherP,\n): Layout<T[], AnotherP> {\n let parsedCount: number;\n const superCount =\n typeof count === \"number\"\n ? count\n : isBN(count)\n ? count.toNumber()\n : new Proxy(count as unknown as Layout<number> /* pretend to be Layout<number> */, {\n get(target, property): any {\n if (!parsedCount) {\n // get count in targetLayout. note that count may be BN\n const countProperty = Reflect.get(target, \"count\");\n\n // let targetLayout's property:count be a number\n parsedCount = isBN(countProperty) ? countProperty.toNumber() : countProperty;\n\n // record the count\n Reflect.set(target, \"count\", parsedCount);\n }\n return Reflect.get(target, property);\n },\n set(target, property, value): any {\n if (property === \"count\") {\n parsedCount = value;\n }\n return Reflect.set(target, property, value);\n },\n });\n\n // @ts-expect-error force type\n return _seq(elementLayout, superCount, property);\n}\n","import {\n bits as _bits,\n BitStructure as _BitStructure,\n blob as _blob,\n Blob as _Blob,\n cstr as _cstr,\n f32 as _f32,\n f32be as _f32be,\n f64 as _f64,\n f64be as _f64be,\n greedy as _greedy,\n Layout as _Layout,\n ns64 as _ns64,\n ns64be as _ns64be,\n nu64 as _nu64,\n nu64be as _nu64be,\n offset as _offset,\n s16 as _s16,\n s16be as _s16be,\n s24 as _s24,\n s24be as _s24be,\n s32 as _s32,\n s32be as _s32be,\n s40 as _s40,\n s40be as _s40be,\n s48 as _s48,\n s48be as _s48be,\n s8 as _s8,\n seq as _seq,\n struct as _struct,\n Structure as _Structure,\n u16 as _u16,\n u16be as _u16be,\n u24 as _u24,\n u24be as _u24be,\n u32 as _u32,\n u32be as _u32be,\n u40 as _u40,\n u40be as _u40be,\n u48 as _u48,\n u48be as _u48be,\n u8 as _u8,\n UInt as _UInt,\n union as _union,\n Union as _Union,\n unionLayoutDiscriminator as _unionLayoutDiscriminator,\n utf8 as _utf8,\n} from \"@solana/buffer-layout\";\n\n//#region ------------------- Layout -------------------\nexport interface Layout<T = any, P = \"\"> {\n span: number;\n property?: P;\n decode(b: Buffer, offset?: number): T;\n encode(src: T, b: Buffer, offset?: number): number;\n getSpan(b: Buffer, offset?: number): number;\n replicate<AP extends string>(name: AP): Layout<T, AP>;\n}\nexport interface LayoutConstructor {\n new <T, P>(): Layout<T, P>; // for class extends syntex\n new <T, P>(span?: T, property?: P): Layout<T, P>;\n readonly prototype: Layout;\n}\nexport const Layout = _Layout as unknown as LayoutConstructor;\n//#endregion\n\n//#region ------------------- Structure -------------------\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface Structure<T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>\n extends Layout<DecodeSchema, P> {\n span: number;\n decode(b: Buffer, offset?: number): DecodeSchema;\n layoutFor<AP extends string>(property: AP): Layout<DecodeSchema[AP]>;\n offsetOf<AP extends string>(property: AP): number;\n}\ninterface StructureConstructor {\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(): Structure<T, P, DecodeSchema>;\n new <T = any, P = \"\", DecodeSchema extends { [key: string]: any } = any>(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n ): Structure<T, P, DecodeSchema>;\n}\nexport const Structure = _Structure as unknown as StructureConstructor;\n//#endregion\n\n//#region ------------------- Union -------------------\nexport interface Union<UnionSchema extends { [key: string]: any } = any> extends Layout {\n registry: object;\n decode(b: Buffer, offset?: number): Partial<UnionSchema>;\n addVariant(\n variant: number,\n layout: Structure<any, any, Partial<UnionSchema>> | Layout<any, keyof UnionSchema>,\n property?: string,\n ): any /* TEMP: code in Layout.js 1809 */;\n}\ninterface UnionConstructor {\n new <UnionSchema extends { [key: string]: any } = any>(): Union<UnionSchema>;\n new <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout: Layout<any, any>,\n property?: string,\n ): Union<UnionSchema>;\n}\nexport const Union = _Union as unknown as UnionConstructor;\n//#endregion\n\n//#region ------------------- BitStructure -------------------\nexport type BitStructure<T = unknown /* TEMP */, P = \"\"> = Layout<T, P>;\ninterface BitStructureConstructor {\n new (...params: any[]): BitStructure;\n}\nexport const BitStructure = _BitStructure as BitStructureConstructor;\n//#endregion\n\n//#region ------------------- UInt -------------------\nexport type UInt<T = any, P = \"\"> = Layout<T, P>;\ninterface UIntConstructor {\n new <T, P>(span?: T, property?: P): UInt<T, P>;\n}\nexport const UInt = _UInt as UIntConstructor;\n//#endregion\n\n//#region ------------------- Blob -------------------\nexport type Blob<P extends string = \"\"> = Layout<Buffer, P>;\ninterface BlobConstructor {\n new (...params: ConstructorParameters<LayoutConstructor>): Blob;\n}\nexport const Blob = _Blob as unknown as BlobConstructor;\n//#endregion\n\nexport const greedy = _greedy as <P extends string = \"\">(elementSpan?: number, property?: P) => Layout<number, P>;\nexport const u8 = _u8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16 = _u16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24 = _u24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32 = _u32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40 = _u40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48 = _u48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64 = _nu64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u16be = _u16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u24be = _u24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u32be = _u32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u40be = _u40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const u48be = _u48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const nu64be = _nu64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s8 = _s8 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16 = _s16 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24 = _s24 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32 = _s32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40 = _s40 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48 = _s48 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64 = _ns64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s16be = _s16be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s24be = _s24be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s32be = _s32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s40be = _s40be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const s48be = _s48be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const ns64be = _ns64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32 = _f32 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f32be = _f32be as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64 = _f64 as <P extends string = \"\">(property?: P) => Layout<number, P>;\nexport const f64be = _f64be as <P extends string = \"\">(property?: P) => Layout<number, P>;\n\nexport const struct = _struct as <T, P extends string = \"\">(\n fields: T,\n property?: P,\n decodePrefixes?: boolean,\n) => T extends Layout<infer Value, infer Property>[]\n ? Structure<\n Value,\n P,\n {\n [K in Exclude<Extract<Property, string>, \"\">]: Extract<T[number], Layout<any, K>> extends Layout<infer V, any>\n ? V\n : any;\n }\n >\n : any;\n\nexport const seq = _seq as unknown as <T, P>(\n elementLayout: Layout<T, string>,\n count: number | Layout<number, string>,\n property?: P,\n) => Layout<T[]>;\nexport const union = _union as <UnionSchema extends { [key: string]: any } = any>(\n discr: Layout<any, any>,\n defaultLayout?: any,\n property?: string,\n) => Union<UnionSchema>;\nexport const unionLayoutDiscriminator = _unionLayoutDiscriminator as <P extends string = \"\">(\n layout: Layout<any, P>,\n property?: P,\n) => any;\nexport const blob = _blob as unknown as <P extends string = \"\">(\n length: number | Layout<number, P>,\n property?: P,\n) => Blob<P>;\nexport const cstr = _cstr as <P extends string = \"\">(property?: P) => Layout<string, P>;\nexport const utf8 = _utf8 as <P extends string = \"\">(maxSpan: number, property?: P) => Layout<string, P>;\nexport const bits = _bits as unknown as <T, P extends string = \"\">(\n word: Layout<T>,\n msb?: boolean,\n property?: P,\n) => BitStructure<T, P>; // TODO: not quite sure\nexport const offset = _offset as unknown as <T, P extends string = \"\">(\n layout: Layout<T, P>,\n offset?: number,\n property?: P,\n) => Layout<T, P>;\n\nexport type GetStructureSchema<T extends Structure> = T extends Structure<any, any, infer S> ? S : unknown;\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\n\nimport { getMultipleAccountsInfo } from \"../../../common\";\nimport { TickArrayLayout } from \"../layout\";\n\nimport { TickArrayBitmapExtensionType } from \"../type\";\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { getPdaTickArrayAddress } from \"./pda\";\nimport { Tick, TICK_ARRAY_SIZE, TickArray, TickUtils } from \"./tick\";\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 BN from \"bn.js\";\n\nimport { TickArrayBitmapExtensionType } from \"../type\";\n\nimport { MAX_TICK, MIN_TICK } from \"./constants\";\nimport { TICK_ARRAY_BITMAP_SIZE, TICK_ARRAY_SIZE, TickUtils } from \"./tick\";\nimport { TickQuery } from \"./tickQuery\";\nimport { isZero, leadingZeros, leastSignificantBit, mostSignificantBit, trailingZeros } from \"./util\";\n\nexport const EXTENSION_TICKARRAY_BITMAP_SIZE = 14;\n\nexport class TickArrayBitmap {\n public static maxTickInTickarrayBitmap(tickSpacing: number): number {\n return tickSpacing * TICK_ARRAY_SIZE * TICK_ARRAY_BITMAP_SIZE;\n }\n\n public static getBitmapTickBoundary(\n tickarrayStartIndex: number,\n tickSpacing: number,\n ): {\n minValue: number;\n maxValue: number;\n } {\n const ticksInOneBitmap = this.maxTickInTickarrayBitmap(tickSpacing);\n let m = Math.floor(Math.abs(tickarrayStartIndex) / ticksInOneBitmap);\n if (tickarrayStartIndex < 0 && Math.abs(tickarrayStartIndex) % ticksInOneBitmap != 0) m += 1;\n\n const minValue = ticksInOneBitmap * m;\n\n return tickarrayStartIndex < 0\n ? { minValue: -minValue, maxValue: -minValue + ticksInOneBitmap }\n : { minValue, maxValue: minValue + ticksInOneBitmap };\n }\n\n public static nextInitializedTickArrayStartIndex(\n bitMap: BN,\n lastTickArrayStartIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n ): { isInit: boolean; tickIndex: number } {\n if (!TickQuery.checkIsValidStartIndex(lastTickArrayStartIndex, tickSpacing))\n throw Error(\"nextInitializedTickArrayStartIndex check error\");\n\n const tickBoundary = this.maxTickInTickarrayBitmap(tickSpacing);\n const nextTickArrayStartIndex = zeroForOne\n ? lastTickArrayStartIndex - TickQuery.tickCount(tickSpacing)\n : lastTickArrayStartIndex + TickQuery.tickCount(tickSpacing);\n\n if (nextTickArrayStartIndex < -tickBoundary || nextTickArrayStartIndex >= tickBoundary) {\n return { isInit: false, tickIndex: lastTickArrayStartIndex };\n }\n\n const multiplier = tickSpacing * TICK_ARRAY_SIZE;\n let compressed = nextTickArrayStartIndex / multiplier + 512;\n\n if (nextTickArrayStartIndex < 0 && nextTickArrayStartIndex % multiplier != 0) {\n compressed--;\n }\n\n const bitPos = Math.abs(compressed);\n\n if (zeroForOne) {\n const offsetBitMap = bitMap.shln(1024 - bitPos - 1);\n const nextBit = mostSignificantBit(1024, offsetBitMap);\n if (nextBit !== null) {\n const nextArrayStartIndex = (bitPos - nextBit - 512) * multiplier;\n return { isInit: true, tickIndex: nextArrayStartIndex };\n } else {\n return { isInit: false, tickIndex: -tickBoundary };\n }\n } else {\n const offsetBitMap = bitMap.shrn(bitPos);\n const nextBit = leastSignificantBit(1024, offsetBitMap);\n if (nextBit !== null) {\n const nextArrayStartIndex = (bitPos + nextBit - 512) * multiplier;\n return { isInit: true, tickIndex: nextArrayStartIndex };\n } else {\n return { isInit: false, tickIndex: tickBoundary - TickQuery.tickCount(tickSpacing) };\n }\n }\n }\n}\n\nexport class TickArrayBitmapExtensionUtils {\n public static getBitmapOffset(tickIndex: number, tickSpacing: number): number {\n if (!TickQuery.checkIsValidStartIndex(tickIndex, tickSpacing)) {\n throw new Error(\"No enough initialized tickArray\");\n }\n this.checkExtensionBoundary(tickIndex, tickSpacing);\n\n const ticksInOneBitmap = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n let offset = Math.floor(Math.abs(tickIndex) / ticksInOneBitmap) - 1;\n\n if (tickIndex < 0 && Math.abs(tickIndex) % ticksInOneBitmap === 0) offset--;\n return offset;\n }\n\n public static getBitmap(\n tickIndex: number,\n tickSpacing: number,\n tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n ): { offset: number; tickarrayBitmap: BN[] } {\n const offset = this.getBitmapOffset(tickIndex, tickSpacing);\n if (tickIndex < 0) {\n return { offset, tickarrayBitmap: tickArrayBitmapExtension.negativeTickArrayBitmap[offset] };\n } else {\n return { offset, tickarrayBitmap: tickArrayBitmapExtension.positiveTickArrayBitmap[offset] };\n }\n }\n\n public static checkExtensionBoundary(tickIndex: number, tickSpacing: number) {\n const { positiveTickBoundary, negativeTickBoundary } = this.extensionTickBoundary(tickSpacing);\n\n if (tickIndex >= negativeTickBoundary && tickIndex < positiveTickBoundary) {\n throw Error(\"checkExtensionBoundary -> InvalidTickArrayBoundary\");\n }\n }\n\n public static extensionTickBoundary(tickSpacing: number): {\n positiveTickBoundary: number;\n negativeTickBoundary: number;\n } {\n const positiveTickBoundary = TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n\n const negativeTickBoundary = -positiveTickBoundary;\n\n if (MAX_TICK <= positiveTickBoundary)\n throw Error(`extensionTickBoundary check error: ${MAX_TICK}, ${positiveTickBoundary}`);\n if (negativeTickBoundary <= MIN_TICK)\n throw Error(`extensionTickBoundary check error: ${negativeTickBoundary}, ${MIN_TICK}`);\n\n return { positiveTickBoundary, negativeTickBoundary };\n }\n\n public static checkTickArrayIsInit(\n tickArrayStartIndex: number,\n tickSpacing: number,\n tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n ): { isInitialized: boolean; startIndex: number } {\n const { tickarrayBitmap } = this.getBitmap(tickArrayStartIndex, tickSpacing, tickArrayBitmapExtension);\n\n const tickArrayOffsetInBitmap = this.tickArrayOffsetInBitmap(tickArrayStartIndex, tickSpacing);\n\n return {\n isInitialized: TickUtils.mergeTickArrayBitmap(tickarrayBitmap).testn(tickArrayOffsetInBitmap),\n startIndex: tickArrayStartIndex,\n };\n }\n\n public static nextInitializedTickArrayFromOneBitmap(\n lastTickArrayStartIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n tickArrayBitmapExtension: TickArrayBitmapExtensionType,\n ): {\n isInit: boolean;\n tickIndex: number;\n } {\n const multiplier = TickQuery.tickCount(tickSpacing);\n const nextTickArrayStartIndex = zeroForOne\n ? lastTickArrayStartIndex - multiplier\n : lastTickArrayStartIndex + multiplier;\n const { tickarrayBitmap } = this.getBitmap(nextTickArrayStartIndex, tickSpacing, tickArrayBitmapExtension);\n\n return this.nextInitializedTickArrayInBitmap(tickarrayBitmap, nextTickArrayStartIndex, tickSpacing, zeroForOne);\n }\n\n public static nextInitializedTickArrayInBitmap(\n tickarrayBitmap: BN[],\n nextTickArrayStartIndex: number,\n tickSpacing: number,\n zeroForOne: boolean,\n ): {\n isInit: boolean;\n tickIndex: number;\n } {\n const { minValue: bitmapMinTickBoundary, maxValue: bitmapMaxTickBoundary } = TickArrayBitmap.getBitmapTickBoundary(\n nextTickArrayStartIndex,\n tickSpacing,\n );\n\n const tickArrayOffsetInBitmap = this.tickArrayOffsetInBitmap(nextTickArrayStartIndex, tickSpacing);\n if (zeroForOne) {\n // tick from upper to lower\n // find from highter bits to lower bits\n const offsetBitMap = TickUtils.mergeTickArrayBitmap(tickarrayBitmap).shln(\n TICK_ARRAY_BITMAP_SIZE - 1 - tickArrayOffsetInBitmap,\n );\n\n const nextBit = isZero(512, offsetBitMap) ? null : leadingZeros(512, offsetBitMap);\n\n if (nextBit !== null) {\n const nextArrayStartIndex = nextTickArrayStartIndex - nextBit * TickQuery.tickCount(tickSpacing);\n return { isInit: true, tickIndex: nextArrayStartIndex };\n } else {\n // not found til to the end\n return { isInit: false, tickIndex: bitmapMinTickBoundary };\n }\n } else {\n // tick from lower to upper\n // find from lower bits to highter bits\n const offsetBitMap = TickUtils.mergeTickArrayBitmap(tickarrayBitmap).shrn(tickArrayOffsetInBitmap);\n\n const nextBit = isZero(512, offsetBitMap) ? null : trailingZeros(512, offsetBitMap);\n\n if (nextBit !== null) {\n const nextArrayStartIndex = nextTickArrayStartIndex + nextBit * TickQuery.tickCount(tickSpacing);\n return { isInit: true, tickIndex: nextArrayStartIndex };\n } else {\n // not found til to the end\n return { isInit: false, tickIndex: bitmapMaxTickBoundary - TickQuery.tickCount(tickSpacing) };\n }\n }\n }\n\n public static tickArrayOffsetInBitmap(tickArrayStartIndex: number, tickSpacing: number): number {\n const m = Math.abs(tickArrayStartIndex) % TickArrayBitmap.maxTickInTickarrayBitmap(tickSpacing);\n let tickArrayOffsetInBitmap = Math.floor(m / TickQuery.tickCount(tickSpacing));\n if (tickArrayStartIndex < 0 && m != 0) {\n tickArrayOffsetInBitmap = TICK_ARRAY_BITMAP_SIZE - tickArrayOffsetInBitmap;\n }\n return tickArrayOffsetInBitmap;\n }\n}\n","import { blob, bool, i128, i64, publicKey, s32, seq, struct, u128, u16, u32, u64, u8 } from \"../../marshmallow\";\n\nimport { TICK_ARRAY_SIZE } from \"./utils/tick\";\nimport { EXTENSION_TICKARRAY_BITMAP_SIZE } from \"./utils/tickarrayBitmap\";\n\nexport const ClmmConfigLayout = struct([\n blob(8),\n u8(\"bump\"),\n u16(\"index\"),\n publicKey(\"\"),\n u32(\"protocolFeeRate\"),\n u32(\"tradeFeeRate\"),\n u16(\"tickSpacing\"),\n seq(u64(), 8, \"\"),\n]);\n\nexport const ObservationLayout = struct([u32(\"blockTimestamp\"), i64(\"tickCumulative\"), seq(u64(), 4)]);\nexport const ObservationInfoLayout = struct([\n blob(8),\n bool(\"initialized\"),\n u64(\"recentEpoch\"),\n u16(\"observationIndex\"),\n publicKey(\"poolId\"),\n seq(ObservationLayout, 100, \"observations\"),\n seq(u64(), 4),\n]);\n\nexport const RewardInfo = struct([\n u8(\"rewardState\"),\n u64(\"openTime\"),\n u64(\"endTime\"),\n u64(\"lastUpdateTime\"),\n u128(\"emissionsPerSecondX64\"),\n u64(\"rewardTotalEmissioned\"),\n u64(\"rewardClaimed\"),\n publicKey(\"tokenMint\"),\n publicKey(\"tokenVault\"),\n publicKey(\"creator\"),\n u128(\"rewardGrowthGlobalX64\"),\n]);\nexport const PoolInfoLayout = struct([\n blob(8),\n u8(\"bump\"),\n publicKey(\"ammConfig\"),\n publicKey(\"creator\"),\n publicKey(\"mintA\"),\n publicKey(\"mintB\"),\n publicKey(\"vaultA\"),\n publicKey(\"vaultB\"),\n publicKey(\"observationId\"),\n u8(\"mintDecimalsA\"),\n u8(\"mintDecimalsB\"),\n u16(\"tickSpacing\"),\n u128(\"liquidity\"),\n u128(\"sqrtPriceX64\"),\n s32(\"tickCurrent\"),\n u32(),\n u128(\"feeGrowthGlobalX64A\"),\n u128(\"feeGrowthGlobalX64B\"),\n u64(\"protocolFeesTokenA\"),\n u64(\"protocolFeesTokenB\"),\n\n u128(\"swapInAmountTokenA\"),\n u128(\"swapOutAmountTokenB\"),\n u128(\"swapInAmountTokenB\"),\n u128(\"swapOutAmountTokenA\"),\n\n u8(\"status\"),\n\n seq(u8(), 7, \"\"),\n\n seq(RewardInfo, 3, \"rewardInfos\"),\n seq(u64(), 16, \"tickArrayBitmap\"),\n\n u64(\"totalFeesTokenA\"),\n u64(\"totalFeesClaimedTokenA\"),\n u64(\"totalFeesTokenB\"),\n u64(\"totalFeesClaimedTokenB\"),\n\n u64(\"fundFeesTokenA\"),\n u64(\"fundFeesTokenB\"),\n\n u64(\"startTime\"),\n\n seq(u64(), 15 * 4 - 3, \"padding\"),\n]);\n\nexport const PositionRewardInfoLayout = struct([u128(\"growthInsideLastX64\"), u64(\"rewardAmountOwed\")]);\nexport const PositionInfoLayout = struct([\n blob(8),\n u8(\"bump\"),\n publicKey(\"nftMint\"),\n publicKey(\"poolId\"),\n\n s32(\"tickLower\"),\n s32(\"tickUpper\"),\n u128(\"liquidity\"),\n u128(\"feeGrowthInsideLastX64A\"),\n u128(\"feeGrowthInsideLastX64B\"),\n u64(\"tokenFeesOwedA\"),\n u64(\"tokenFeesOwedB\"),\n\n seq(PositionRewardInfoLayout, 3, \"rewardInfos\"),\n\n seq(u64(), 8, \"\"),\n]);\n\nexport type ClmmPositionLayout = ReturnType<typeof PositionInfoLayout.decode>;\n\nexport const ProtocolPositionLayout = struct([\n blob(8),\n u8(\"bump\"),\n publicKey(\"poolId\"),\n s32(\"tickLowerIndex\"),\n s32(\"tickUpperIndex\"),\n u128(\"liquidity\"),\n u128(\"feeGrowthInsideLastX64A\"),\n u128(\"feeGrowthInsideLastX64B\"),\n u64(\"tokenFeesOwedA\"),\n u64(\"tokenFeesOwedB\"),\n seq(u128(), 3, \"rewardGrowthInside\"),\n\n seq(u64(), 8, \"\"),\n]);\n\nexport const TickLayout = struct([\n s32(\"tick\"),\n i128(\"liquidityNet\"),\n u128(\"liquidityGross\"),\n u128(\"feeGrowthOutsideX64A\"),\n u128(\"feeGrowthOutsideX64B\"),\n seq(u128(), 3, \"rewardGrowthsOutsideX64\"),\n\n seq(u32(), 13, \"\"),\n]);\n\nexport const TickArrayLayout = struct([\n blob(8),\n publicKey(\"poolId\"),\n s32(\"startTickIndex\"),\n seq(TickLayout, TICK_ARRAY_SIZE, \"ticks\"),\n u8(\"initializedTickCount\"),\n\n seq(u8(), 115, \"\"),\n]);\n\nexport const OperationLayout = struct([blob(329), seq(publicKey(), 100, \"whitelistMints\")]);\n\nexport const TickArrayBitmapExtensionLayout = struct([\n blob(8),\n publicKey(\"poolId\"),\n seq(seq(u64(), 8), EXTENSION_TICKARRAY_BITMAP_SIZE, \"positiveTickArrayBitmap\"),\n seq(seq(u64(), 8), EXTENSION_TICKARRAY_BITMAP_SIZE, \"negativeTickArrayBitmap\"),\n]);\n\nexport const LockPositionLayout = struct([\n u64(),\n u8(\"bump\"),\n publicKey(\"owner\"),\n publicKey(\"poolId\"),\n publicKey(\"positionId\"),\n publicKey(\"nftAccount\"),\n seq(u64(), 8),\n]);\n\nexport const LockClPositionLayoutV2 = struct([\n blob(8),\n u8(\"bump\"),\n publicKey(\"lockOwner\"),\n publicKey(\"poolId\"),\n publicKey(\"positionId\"),\n publicKey(\"nftAccount\"),\n publicKey(\"lockNftMint\"),\n u64(\"recentEpoch\"),\n seq(u64(), 8),\n]);\n","import BN from \"bn.js\";\n\nimport Decimal from \"decimal.js\";\nimport { getTransferAmountFeeV2, minExpirationTime } from \"../../../common\";\nimport { ClmmPositionLayout } from \"../layout\";\nimport { ClmmPoolInfo, ClmmPoolPersonalPosition, ClmmPoolRewardInfo, GetAmountParams, ReturnTypeGetLiquidityAmountOut } from \"../type\";\nimport { Q64 } from \"./constants\";\nimport { LiquidityMath, MathUtil, SqrtPriceMath } from \"./math\";\nimport { Tick } from \"./tick\";\n\nexport class PositionUtils {\n static getfeeGrowthInside(\n poolState: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64A\" | \"feeGrowthGlobalX64B\">,\n tickLowerState: Tick,\n tickUpperState: Tick,\n ): { feeGrowthInsideX64A: BN; feeGrowthInsideBX64: BN } {\n let feeGrowthBelowX64A = new BN(0);\n let feeGrowthBelowX64B = new BN(0);\n if (poolState.tickCurrent >= tickLowerState.tick) {\n feeGrowthBelowX64A = tickLowerState.feeGrowthOutsideX64A;\n feeGrowthBelowX64B = tickLowerState.feeGrowthOutsideX64B;\n } else {\n feeGrowthBelowX64A = poolState.feeGrowthGlobalX64A.sub(tickLowerState.feeGrowthOutsideX64A);\n feeGrowthBelowX64B = poolState.feeGrowthGlobalX64B.sub(tickLowerState.feeGrowthOutsideX64B);\n }\n\n let feeGrowthAboveX64A = new BN(0);\n let feeGrowthAboveX64B = new BN(0);\n if (poolState.tickCurrent < tickUpperState.tick) {\n feeGrowthAboveX64A = tickUpperState.feeGrowthOutsideX64A;\n feeGrowthAboveX64B = tickUpperState.feeGrowthOutsideX64B;\n } else {\n feeGrowthAboveX64A = poolState.feeGrowthGlobalX64A.sub(tickUpperState.feeGrowthOutsideX64A);\n feeGrowthAboveX64B = poolState.feeGrowthGlobalX64B.sub(tickUpperState.feeGrowthOutsideX64B);\n }\n\n const feeGrowthInsideX64A = MathUtil.wrappingSubU128(\n MathUtil.wrappingSubU128(poolState.feeGrowthGlobalX64A, feeGrowthBelowX64A),\n feeGrowthAboveX64A,\n );\n const feeGrowthInsideBX64 = MathUtil.wrappingSubU128(\n MathUtil.wrappingSubU128(poolState.feeGrowthGlobalX64B, feeGrowthBelowX64B),\n feeGrowthAboveX64B,\n );\n return { feeGrowthInsideX64A, feeGrowthInsideBX64 };\n }\n\n static GetPositionFees(\n ammPool: ClmmPoolInfo,\n positionState: ClmmPoolPersonalPosition,\n tickLowerState: Tick,\n tickUpperState: Tick,\n ): { tokenFeeAmountA: BN; tokenFeeAmountB: BN } {\n const { feeGrowthInsideX64A, feeGrowthInsideBX64 } = this.getfeeGrowthInside(\n ammPool,\n tickLowerState,\n tickUpperState,\n );\n\n const feeGrowthdeltaA = MathUtil.mulDivFloor(\n MathUtil.wrappingSubU128(feeGrowthInsideX64A, positionState.feeGrowthInsideLastX64A),\n positionState.liquidity,\n Q64,\n );\n const tokenFeeAmountA = positionState.tokenFeesOwedA.add(feeGrowthdeltaA);\n\n const feeGrowthdelta1 = MathUtil.mulDivFloor(\n MathUtil.wrappingSubU128(feeGrowthInsideBX64, positionState.feeGrowthInsideLastX64B),\n positionState.liquidity,\n Q64,\n );\n const tokenFeeAmountB = positionState.tokenFeesOwedB.add(feeGrowthdelta1);\n\n return { tokenFeeAmountA, tokenFeeAmountB };\n }\n\n static GetPositionFeesV2(\n ammPool: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64A\" | \"feeGrowthGlobalX64B\">,\n positionState: ClmmPositionLayout,\n tickLowerState: Tick,\n tickUpperState: Tick,\n ): { tokenFeeAmountA: BN; tokenFeeAmountB: BN } {\n const { feeGrowthInsideX64A, feeGrowthInsideBX64 } = this.getfeeGrowthInside(\n ammPool,\n tickLowerState,\n tickUpperState,\n );\n\n const feeGrowthdeltaA = MathUtil.mulDivFloor(\n MathUtil.wrappingSubU128(feeGrowthInsideX64A, positionState.feeGrowthInsideLastX64A),\n positionState.liquidity,\n Q64,\n );\n const tokenFeeAmountA = positionState.tokenFeesOwedA.add(feeGrowthdeltaA);\n\n const feeGrowthdelta1 = MathUtil.mulDivFloor(\n MathUtil.wrappingSubU128(feeGrowthInsideBX64, positionState.feeGrowthInsideLastX64B),\n positionState.liquidity,\n Q64,\n );\n const tokenFeeAmountB = positionState.tokenFeesOwedB.add(feeGrowthdelta1);\n\n return { tokenFeeAmountA, tokenFeeAmountB };\n }\n\n static GetPositionRewardsV2(\n ammPool: Pick<ClmmPoolInfo, \"tickCurrent\" | \"feeGrowthGlobalX64B\"> & {\n rewardInfos: { rewardGrowthGlobalX64: BN }[];\n },\n positionState: ClmmPositionLayout,\n tickLowerState: Tick,\n tickUpperState: Tick,\n ): BN[] {\n const rewards: BN[] = [];\n\n const rewardGrowthsInside = this.getRewardGrowthInsideV2(\n ammPool.tickCurrent,\n tickLowerState,\n tickUpperState,\n ammPool.rewardInfos,\n );\n for (let i = 0; i < rewardGrowthsInside.length; i++) {\n const rewardGrowthInside = rewardGrowthsInside[i];\n const currRewardInfo = positionState.rewardInfos[i];\n\n const rewardGrowthDelta = MathUtil.wrappingSubU128(rewardGrowthInside, currRewardInfo.growthInsideLastX64);\n const amountOwedDelta = MathUtil.mulDivFloor(rewardGrowthDelta, positionState.liquidity, Q64);\n const rewardAmountOwed = currRewardInfo.rewardAmountOwed.add(amountOwedDelta);\n rewards.push(rewardAmountOwed);\n }\n return rewards;\n }\n\n static GetPositionRewards(\n ammPool: ClmmPoolInfo,\n positionState: ClmmPoolPersonalPosition,\n tickLowerState: Tick,\n tickUpperState: Tick,\n ): BN[] {\n const rewards: BN[] = [];\n\n const rewardGrowthsInside = this.getRewardGrowthInside(\n ammPool.tickCurrent,\n tickLowerState,\n tickUpperState,\n ammPool.rewardInfos,\n );\n for (let i = 0; i < rewardGrowthsInside.length; i++) {\n const rewardGrowthInside = rewardGrowthsInside[i];\n const currRewardInfo = positionState.rewardInfos[i];\n\n const rewardGrowthDelta = MathUtil.wrappingSubU128(rewardGrowthInside, currRewardInfo.growthInsideLastX64);\n const amountOwedDelta = MathUtil.mulDivFloor(rewardGrowthDelta, positionState.liquidity, Q64);\n const rewardAmountOwed = currRewardInfo.rewardAmountOwed.add(amountOwedDelta);\n rewards.push(rewardAmountOwed);\n }\n return rewards;\n }\n\n static getRewardGrowthInside(\n tickCurrentIndex: number,\n tickLowerState: Tick,\n tickUpperState: Tick,\n rewardInfos: ClmmPoolRewardInfo[],\n ): BN[] {\n const rewardGrowthsInside: BN[] = [];\n for (let i = 0; i < rewardInfos.length; i++) {\n let rewardGrowthsBelow = new BN(0);\n if (tickLowerState.liquidityGross.eqn(0)) {\n rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64;\n } else if (tickCurrentIndex < tickLowerState.tick) {\n rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64.sub(tickLowerState.rewardGrowthsOutsideX64[i]);\n } else {\n rewardGrowthsBelow = tickLowerState.rewardGrowthsOutsideX64[i];\n }\n\n let rewardGrowthsAbove = new BN(0);\n if (tickUpperState.liquidityGross.eqn(0)) {\n //\n } else if (tickCurrentIndex < tickUpperState.tick) {\n rewardGrowthsAbove = tickUpperState.rewardGrowthsOutsideX64[i];\n } else {\n rewardGrowthsAbove = rewardInfos[i].rewardGrowthGlobalX64.sub(tickUpperState.rewardGrowthsOutsideX64[i]);\n }\n\n rewardGrowthsInside.push(\n MathUtil.wrappingSubU128(\n MathUtil.wrappingSubU128(rewardInfos[i].rewardGrowthGlobalX64, rewardGrowthsBelow),\n rewardGrowthsAbove,\n ),\n );\n }\n\n return rewardGrowthsInside;\n }\n\n static getRewardGrowthInsideV2(\n tickCurrentIndex: number,\n tickLowerState: Tick,\n tickUpperState: Tick,\n rewardInfos: Pick<ClmmPoolRewardInfo, \"rewardGrowthGlobalX64\">[],\n ): BN[] {\n const rewardGrowthsInside: BN[] = [];\n for (let i = 0; i < rewardInfos.length; i++) {\n let rewardGrowthsBelow = new BN(0);\n if (tickLowerState.liquidityGross.eqn(0)) {\n rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64;\n } else if (tickCurrentIndex < tickLowerState.tick) {\n rewardGrowthsBelow = rewardInfos[i].rewardGrowthGlobalX64.sub(tickLowerState.rewardGrowthsOutsideX64[i]);\n } else {\n rewardGrowthsBelow = tickLowerState.rewardGrowthsOutsideX64[i];\n }\n\n let rewardGrowthsAbove = new BN(0);\n if (tickUpperState.liquidityGross.eqn(0)) {\n //\n } else if (tickCurrentIndex < tickUpperState.tick) {\n rewardGrowthsAbove = tickUpperState.rewardGrowthsOutsideX64[i];\n } else {\n rewardGrowthsAbove = rewardInfos[i].rewardGrowthGlobalX64.sub(tickUpperState.rewardGrowthsOutsideX64[i]);\n }\n\n rewardGrowthsInside.push(\n MathUtil.wrappingSubU128(\n MathUtil.wrappingSubU128(rewardInfos[i].rewardGrowthGlobalX64, rewardGrowthsBelow),\n rewardGrowthsAbove,\n ),\n );\n }\n\n return rewardGrowthsInside;\n }\n\n static getAmountsFromLiquidity({\n poolInfo,\n ownerPosition,\n liquidity,\n slippage,\n add,\n epochInfo,\n }: GetAmountParams): ReturnTypeGetLiquidityAmountOut {\n const sqrtPriceX64 = SqrtPriceMath.priceToSqrtPriceX64(\n new Decimal(poolInfo.price),\n poolInfo.mintA.decimals,\n poolInfo.mintB.decimals,\n );\n const sqrtPriceX64A = SqrtPriceMath.getSqrtPriceX64FromTick(ownerPosition.tickLower);\n const sqrtPriceX64B = SqrtPriceMath.getSqrtPriceX64FromTick(ownerPosition.tickUpper);\n\n const coefficientRe = add ? 1 + slippage : 1 - slippage;\n\n const amounts = LiquidityMath.getAmountsFromLiquidity(sqrtPriceX64, sqrtPriceX64A, sqrtPriceX64B, liquidity, add);\n\n const [amountA, amountB] = [\n getTransferAmountFeeV2(amounts.amountA, poolInfo.mintA.extensions?.feeConfig, epochInfo, true),\n getTransferAmountFeeV2(amounts.amountB, poolInfo.mintB.extensions?.feeConfig, epochInfo, true),\n ];\n const [amountSlippageA, amountSlippageB] = [\n getTransferAmountFeeV2(\n new BN(new Decimal(amounts.amountA.toString()).mul(coefficientRe).toFixed(0)),\n poolInfo.mintA.extensions?.feeConfig,\n epochInfo,\n true,\n ),\n getTransferAmountFeeV2(\n new BN(new Decimal(amounts.amountB.toString()).mul(coefficientRe).toFixed(0)),\n poolInfo.mintB.extensions?.feeConfig,\n epochInfo,\n true,\n ),\n ];\n\n return {\n liquidity,\n amountA,\n amountB,\n amountSlippageA,\n amountSlippageB,\n expirationTime: minExpirationTime(amountA.expirationTime, amountB.expirationTime),\n };\n }\n}\n"],"mappings":"AACA,OAAOA,OAAQ,QCaf,IAAIC,GAAY,KAIdC,GAAa,IAGbC,GAAW,mBAGXC,GAAO,qgCAGPC,GAAK,qgCAILC,GAAW,CAOT,UAAW,GAiBX,SAAU,EAeV,OAAQ,EAIR,SAAU,GAIV,SAAW,GAIX,KAAM,CAACL,GAIP,KAAMA,GAGN,OAAQ,EACV,EAMAM,GAASC,GACTC,EAAW,GAEXC,GAAe,kBACfC,GAAkBD,GAAe,qBACjCE,GAAyBF,GAAe,2BACxCG,GAAoBH,GAAe,qBACnCI,GAAM,mBAENC,EAAY,KAAK,MACjBC,EAAU,KAAK,IAEfC,GAAW,6CACXC,GAAQ,yDACRC,GAAU,gDACVC,GAAY,qCAEZC,EAAO,IACPC,EAAW,EACXC,GAAmB,iBAEnBC,GAAiBpB,GAAK,OAAS,EAC/BqB,GAAepB,GAAG,OAAS,EAG3BqB,EAAI,CAAE,YAAaZ,EAAI,EA0EzBY,EAAE,cAAgBA,EAAE,IAAM,UAAY,CACpC,IAAIC,EAAI,IAAI,KAAK,YAAY,IAAI,EACjC,OAAIA,EAAE,EAAI,IAAGA,EAAE,EAAI,GACZC,EAASD,CAAC,CACn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,CAAC,EAAE,IAAID,CAAS,CAAE,CAC5F,CACF","names":["BN","EXP_LIMIT","MAX_DIGITS","NUMERALS","LN10","PI","DEFAULTS","inexact","quadrant","external","decimalError","invalidArgument","precisionLimitExceeded","cryptoUnavailable","tag","mathfloor","mathpow","isBinary","isHex","isOctal","isDecimal","BASE","LOG_BASE","MAX_SAFE_INTEGER","LN10_PRECISION","PI_PRECISION","P","x","finalise","min","max","k","Ctor","y","i","j","xdL","ydL","xd","yd","xs","ys","pr","rm","cosine","toLessThanHalfPi","e","m","rep","s","sd","t","t3","t3plusx","digitsToString","divide","w","d","n","len","one","tinyPow","taylorSeries","cosh2_x","d8","sinh2_x","d5","d16","d20","getPi","wpr","xsd","halfPi","px","r","x2","base","isBase10","denominator","inf","num","arg","guard","naturalLogarithm","getLn10","checkRoundingDigits","xe","xLTy","getBase10Exponent","q","naturalExponential","carry","z","getPrecision","sine","rL","toStringBinary","dp","checkInt32","str","finiteToString","maxD","d0","d1","d2","n0","n1","yn","intPow","ws","indexOfLastWord","getZeroString","repeating","di","rd","convertBase","baseIn","baseOut","arr","arrL","strL","cos2x","multiplyInteger","temp","compare","a","b","aL","bL","subtract","cmp","logBase","more","prod","prodL","qd","rem","remL","rem0","xi","xL","yd0","yL","yz","sign","isTruncated","digits","roundUp","xdi","out","isExp","nonFiniteToString","zs","truncate","isOdd","maxOrMin","args","pow","sum","c","c0","numerator","x1","parseDecimal","parseOther","divisor","isFloat","p","Decimal","sin2_x","isHyperbolic","u","isNeg","pi","abs","acos","acosh","add","asin","asinh","atan","atanh","atan2","cbrt","ceil","clamp","config","obj","v","useDefaults","ps","cos","cosh","clone","isDecimalInstance","div","exp","floor","hypot","ln","log","log10","log2","mod","mul","random","round","sin","sinh","sqrt","sub","tan","tanh","trunc","decimal_default","BN","ZERO","ONE","NEGATIVE_ONE","Q64","Q128","MaxU64","U64Resolution","MaxUint128","MIN_TICK","MAX_TICK","MIN_SQRT_PRICE_X64","MAX_SQRT_PRICE_X64","MIN_SQRT_PRICE_X64_ADD_ONE","MAX_SQRT_PRICE_X64_SUB_ONE","BIT_PRECISION","LOG_B_2_X32","LOG_B_P_ERR_MARGIN_LOWER_X64","LOG_B_P_ERR_MARGIN_UPPER_X64","FEE_RATE_DENOMINATOR","U64_IGNORE_RANGE","BN","BN","BN","MINT_SIZE","TOKEN_PROGRAM_ID","getTransferFeeConfig","unpackMint","PublicKey","get","set","Logger","params","logLevel","level","props","msg","arg","moduleLoggers","moduleLevels","createLogger","moduleName","logger","get","set","logger","createLogger","getMultipleAccountsInfo","connection","publicKeys","config","batchRequest","commitment","chunkCount","chunkedKeys","chunkArray","results","batch","keys","args","key","_batch","i","unsafeRes","accountInfo","data","executable","lamports","owner","rentEpoch","PublicKey","error","BN","_Big","BN","_toFarmat","toFormat","formatter_default","_Big","BN","_Decimal","BN","MAX_SAFE","parseBigNumberish","value","logger","createLogger","BN","logger","createLogger","Big","formatter_default","_Big","Decimal","_Decimal","toSignificantRounding","toFixedRounding","Fraction","numerator","denominator","BN","parseBigNumberish","other","otherParsed","significantDigits","format","rounding","quotient","decimalPlaces","logger","createLogger","Big","formatter_default","_Big","TOKEN_PROGRAM_ID","PublicKey","PublicKey","NETWORK_CONFIG","PublicKey","PublicKey","TOKEN_PROGRAM_ID","PublicKey","SystemProgram","SYSVAR_RENT_PUBKEY","accountMeta","pubkey","isSigner","isWritable","commonSystemAccountMeta","MEMO_PROGRAM_ID","PublicKey","MEMO_PROGRAM_ID2","RENT_PROGRAM_ID","CLOCK_PROGRAM_ID","METADATA_PROGRAM_ID","INSTRUCTION_PROGRAM_ID","SYSTEM_PROGRAM_ID","SystemProgram","SOLMint","BN","_100_PERCENT","Fraction","BN","logger","createLogger","PublicKey","BN","BN_ZERO","BN","BN_ONE","BN_TWO","BN_THREE","BN_FIVE","BN_TEN","BN_100","BN_1000","BN_10000","chunkArray","arr","chunkSize","cache","tmp","PublicKey","TOKEN_PROGRAM_ID","ComputeBudgetProgram","Keypair","PublicKey","Transaction","TransactionMessage","VersionedTransaction","TOKEN_PROGRAM_ID","logger","createLogger","findProgramAddress","seeds","programId","publicKey","nonce","PublicKey","PublicKey","FARM_PROGRAM_ID_V3","FARM_PROGRAM_ID_V4","FARM_PROGRAM_ID_V5","FARM_PROGRAM_ID_V6","UTIL1216","OPEN_BOOK_PROGRAM","SERUM_PROGRAM_ID_V3","AMM_V4","AMM_STABLE","LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL","CLMM_LOCK_PROGRAM_ID","PublicKey","CLMM_LOCK_AUTH_ID","Router","FEE_DESTINATION_ID","IDO_PROGRAM_ID_V1","IDO_PROGRAM_ID_V2","IDO_PROGRAM_ID_V3","IDO_PROGRAM_ID_V4","CREATE_CPMM_POOL_PROGRAM","CREATE_CPMM_POOL_AUTH","CREATE_CPMM_POOL_FEE_ACC","DEV_CREATE_CPMM_POOL_PROGRAM","DEV_CREATE_CPMM_POOL_AUTH","DEV_CREATE_CPMM_POOL_FEE_ACC","LOCK_CPMM_PROGRAM","DEV_LOCK_CPMM_PROGRAM","LOCK_CPMM_AUTH","DEV_LOCK_CPMM_AUTH","DEVNET_PROGRAM_ID","PublicKey","DEV_CREATE_CPMM_POOL_PROGRAM","DEV_CREATE_CPMM_POOL_AUTH","DEV_CREATE_CPMM_POOL_FEE_ACC","DEV_LOCK_CPMM_PROGRAM","DEV_LOCK_CPMM_AUTH","PublicKey","AddressLookupTableAccount","PublicKey","sendAndConfirmTransaction","Transaction","TransactionMessage","VersionedTransaction","axios","i32ToBytes","num","arr","AMM_CONFIG_SEED","POOL_SEED","POOL_VAULT_SEED","POOL_REWARD_VAULT_SEED","POSITION_SEED","TICK_ARRAY_SEED","OPERATION_SEED","POOL_TICK_ARRAY_BITMAP_SEED","OBSERVATION_SEED","getPdaTickArrayAddress","programId","poolId","startIndex","findProgramAddress","TICK_ARRAY_SEED","i32ToBytes","POOL_LOCK_ID_SEED","TOKEN_2022_PROGRAM_ID","PublicKey","BN","PublicKey","BN","isBN","_bits","_BitStructure","_blob","_Blob","_cstr","_f32","_f32be","_f64","_f64be","_greedy","_Layout","_ns64","_ns64be","_nu64","_nu64be","_offset","_s16","_s16be","_s24","_s24be","_s32","_s32be","_s40","_s40be","_s48","_s48be","_s8","_seq","_struct","_Structure","_u16","_u16be","_u24","_u24be","_u32","_u32be","_u40","_u40be","_u48","_u48be","_u8","_UInt","_union","_Union","_unionLayoutDiscriminator","_utf8","Layout","Structure","UInt","_UInt","u8","_u8","u16","_u16","s32","_s32","seq","_seq","blob","_blob","BNLayout","Layout","span","signed","property","blob","b","offset","num","BN","src","u8","property","UInt","u32","u64","BNLayout","u128","i64","property","BNLayout","i128","WrappedLayout","Layout","layout","decoder","encoder","b","offset","src","publicKey","blob","PublicKey","key","bool","property","WrappedLayout","u8","decodeBool","encodeBool","value","Structure","b","offset","struct","fields","property","decodePrefixes","seq","elementLayout","count","property","parsedCount","superCount","isBN","target","countProperty","value","FETCH_TICKARRAY_COUNT","TickQuery","connection","programId","poolId","tickCurrent","tickSpacing","tickArrayBitmapArray","exTickArrayBitmap","tickArraysToFetch","currentTickArrayStartIndex","TickUtils","startIndexArray","i","tickArrayAddress","getPdaTickArrayAddress","fetchedTickArrays","getMultipleAccountsInfo","TickArrayLayout","tickArrayCache","_info","tickIndex","zeroForOne","nextTick","tickArrayStartTickIndex","cachedTickArray","_nextTick","_tickArrayAddress","_tickArrayStartTickIndex","tickArrayBitmap","exBitmapInfo","currentOffset","result","tickArray","nextInitializedTick","TICK_ARRAY_SIZE","tickInArray","startIndex","tickPositionInArray","ticksInArray","MAX_TICK","minStartIndex","MIN_TICK","EXTENSION_TICKARRAY_BITMAP_SIZE","ClmmConfigLayout","struct","blob","u8","u16","publicKey","u32","seq","u64","ObservationLayout","i64","ObservationInfoLayout","bool","RewardInfo","u128","PoolInfoLayout","s32","PositionRewardInfoLayout","PositionInfoLayout","ProtocolPositionLayout","TickLayout","i128","TickArrayLayout","TICK_ARRAY_SIZE","OperationLayout","TickArrayBitmapExtensionLayout","EXTENSION_TICKARRAY_BITMAP_SIZE","LockPositionLayout","LockClPositionLayoutV2","BN","MathUtil","a","b","denominator","numerator","result","ZERO","ONE","num","decimalPlaces","decimal_default","BN","n0","n1","Q128","mulRightShift","val","mulBy","signedRightShift","signedLeftShift","shiftBy","bitWidth","twosN0","twoN0","SqrtPriceMath","sqrtPriceX64","decimalsA","decimalsB","price","liquidity","amountIn","zeroForOne","amountOut","amount","add","liquidityLeftShift","U64Resolution","numerator1","amountMulSqrtPrice","deltaY","amountDivLiquidity","tick","MIN_TICK","MAX_TICK","tickAbs","ratio","MaxUint128","MAX_SQRT_PRICE_X64","MIN_SQRT_PRICE_X64","msb","adjustedMsb","log2pIntegerX32","bit","precision","log2pFractionX64","r","BIT_PRECISION","rMoreThanTwo","log2pFractionX32","logbpX64","LOG_B_2_X32","tickLow","LOG_B_P_ERR_MARGIN_LOWER_X64","tickHigh","LOG_B_P_ERR_MARGIN_UPPER_X64","TickMath","tickSpacing","mintDecimalsA","mintDecimalsB","TICK_ARRAY_SIZE","TICK_ARRAY_BITMAP_SIZE","TickUtils","programId","poolId","tickIndex","tickSpacing","startIndex","tickArrayAddress","getPdaTickArrayAddress","startTickIndex","offsetInArray","ticksInArray","TickQuery","tick","multiplier","compressed","bitmap","bitPos","lastTickArrayStartIndex","zeroForOne","bns","b","BN","i","tickArrayBitmap","exTickArrayBitmap","tickArrayStartIndex","expectedCount","tickArrayOffset","result","allInitializedTickArrayIndex","address","tickArray","currentTickArrayBitStartIndex","tickArrayBitmaps","arrayIndex","searchIndex","tickCount","MIN_TICK","MAX_TICK","tickArrayCurrent","currentTickIndex","t","poolInfo","baseIn","tickSqrtPriceX64","SqrtPriceMath","tickPrice","decimal_default","price","_price","TickMath"]}