UNPKG

@raydium-io/raydium-sdk-v2

Version:

An SDK for building applications on top of Raydium.

1 lines 437 kB
{"version":3,"sources":["../../../src/raydium/liquidity/constant.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/raydium/liquidity/layout.ts","../../../src/raydium/liquidity/utils.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/common/txTool/txUtils.ts","../../../src/common/logger.ts","../../../src/common/txTool/txType.ts","../../../src/raydium/token/utils.ts","../../../src/module/amount.ts","../../../src/common/bignumber.ts","../../../src/raydium/token/constant.ts","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/module/currency.ts","../../../src/module/fraction.ts","../../../src/common/constant.ts","../../../src/module/formatter.ts","../../../src/module/percent.ts","../../../src/module/price.ts","../../../src/common/accountInfo.ts","../../../src/common/pda.ts","../../../src/common/programId.ts","../../../src/common/transfer.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/txTool/txTool.ts","../../../src/common/utility.ts","../../../src/common/fee.ts","../../../src/raydium/liquidity/instruction.ts","../../../src/raydium/liquidity/serum.ts","../../../src/raydium/liquidity/stable.ts","../../../src/raydium/account/layout.ts","../../../src/raydium/account/util.ts","../../../src/raydium/account/instruction.ts","../../../src/raydium/token/layout.ts"],"sourcesContent":["import BN from \"bn.js\";\nimport { SerumVersion } from \"../serum\";\n\nexport const LIQUIDITY_FEES_NUMERATOR = new BN(25);\nexport const LIQUIDITY_FEES_DENOMINATOR = new BN(10000);\n\n// liquidity version => serum version\nexport const LIQUIDITY_VERSION_TO_SERUM_VERSION: {\n [key in 4 | 5]?: SerumVersion;\n} = {\n 4: 3,\n 5: 3,\n};\n","import { PublicKey } from \"@solana/web3.js\";\nimport 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 { GetStructureSchema, publicKey, seq, struct, u128, u64, u8 } from \"../../marshmallow\";\n\nexport const fixedSwapInLayout = struct([u8(\"instruction\"), u64(\"amountIn\"), u64(\"minAmountOut\")]);\nexport const fixedSwapOutLayout = struct([u8(\"instruction\"), u64(\"maxAmountIn\"), u64(\"amountOut\")]);\n\nexport const createPoolV4Layout = struct([u8(\"instruction\"), u8(\"nonce\")]);\nexport const initPoolLayout = struct([u8(\"instruction\"), u8(\"nonce\"), u64(\"startTime\")]);\n/* ================= state layouts ================= */\nexport const liquidityStateV4Layout = struct([\n u64(\"status\"),\n u64(\"nonce\"),\n u64(\"maxOrder\"),\n u64(\"depth\"),\n u64(\"baseDecimal\"),\n u64(\"quoteDecimal\"),\n u64(\"state\"),\n u64(\"resetFlag\"),\n u64(\"minSize\"),\n u64(\"volMaxCutRatio\"),\n u64(\"amountWaveRatio\"),\n u64(\"baseLotSize\"),\n u64(\"quoteLotSize\"),\n u64(\"minPriceMultiplier\"),\n u64(\"maxPriceMultiplier\"),\n u64(\"systemDecimalValue\"),\n u64(\"minSeparateNumerator\"),\n u64(\"minSeparateDenominator\"),\n u64(\"tradeFeeNumerator\"),\n u64(\"tradeFeeDenominator\"),\n u64(\"pnlNumerator\"),\n u64(\"pnlDenominator\"),\n u64(\"swapFeeNumerator\"),\n u64(\"swapFeeDenominator\"),\n u64(\"baseNeedTakePnl\"),\n u64(\"quoteNeedTakePnl\"),\n u64(\"quoteTotalPnl\"),\n u64(\"baseTotalPnl\"),\n u64(\"poolOpenTime\"),\n u64(\"punishPcAmount\"),\n u64(\"punishCoinAmount\"),\n u64(\"orderbookToInitTime\"),\n // u128('poolTotalDepositPc'),\n // u128('poolTotalDepositCoin'),\n u128(\"swapBaseInAmount\"),\n u128(\"swapQuoteOutAmount\"),\n u64(\"swapBase2QuoteFee\"),\n u128(\"swapQuoteInAmount\"),\n u128(\"swapBaseOutAmount\"),\n u64(\"swapQuote2BaseFee\"),\n // amm vault\n publicKey(\"baseVault\"),\n publicKey(\"quoteVault\"),\n // mint\n publicKey(\"baseMint\"),\n publicKey(\"quoteMint\"),\n publicKey(\"lpMint\"),\n // market\n publicKey(\"openOrders\"),\n publicKey(\"marketId\"),\n publicKey(\"marketProgramId\"),\n publicKey(\"targetOrders\"),\n publicKey(\"withdrawQueue\"),\n publicKey(\"lpVault\"),\n publicKey(\"owner\"),\n // true circulating supply without lock up\n u64(\"lpReserve\"),\n seq(u64(), 3, \"padding\"),\n]);\n\nexport type LiquidityStateLayoutV4 = typeof liquidityStateV4Layout;\nexport type LiquidityStateV4 = GetStructureSchema<LiquidityStateLayoutV4>;\n\nexport const liquidityStateV5Layout = struct([\n u64(\"accountType\"),\n u64(\"status\"),\n u64(\"nonce\"),\n u64(\"maxOrder\"),\n u64(\"depth\"),\n u64(\"baseDecimal\"),\n u64(\"quoteDecimal\"),\n u64(\"state\"),\n u64(\"resetFlag\"),\n u64(\"minSize\"),\n u64(\"volMaxCutRatio\"),\n u64(\"amountWaveRatio\"),\n u64(\"baseLotSize\"),\n u64(\"quoteLotSize\"),\n u64(\"minPriceMultiplier\"),\n u64(\"maxPriceMultiplier\"),\n u64(\"systemDecimalsValue\"),\n u64(\"abortTradeFactor\"),\n u64(\"priceTickMultiplier\"),\n u64(\"priceTick\"),\n // Fees\n u64(\"minSeparateNumerator\"),\n u64(\"minSeparateDenominator\"),\n u64(\"tradeFeeNumerator\"),\n u64(\"tradeFeeDenominator\"),\n u64(\"pnlNumerator\"),\n u64(\"pnlDenominator\"),\n u64(\"swapFeeNumerator\"),\n u64(\"swapFeeDenominator\"),\n // OutPutData\n u64(\"baseNeedTakePnl\"),\n u64(\"quoteNeedTakePnl\"),\n u64(\"quoteTotalPnl\"),\n u64(\"baseTotalPnl\"),\n u64(\"poolOpenTime\"),\n u64(\"punishPcAmount\"),\n u64(\"punishCoinAmount\"),\n u64(\"orderbookToInitTime\"),\n u128(\"swapBaseInAmount\"),\n u128(\"swapQuoteOutAmount\"),\n u128(\"swapQuoteInAmount\"),\n u128(\"swapBaseOutAmount\"),\n u64(\"swapQuote2BaseFee\"),\n u64(\"swapBase2QuoteFee\"),\n\n publicKey(\"baseVault\"),\n publicKey(\"quoteVault\"),\n publicKey(\"baseMint\"),\n publicKey(\"quoteMint\"),\n publicKey(\"lpMint\"),\n\n publicKey(\"modelDataAccount\"),\n publicKey(\"openOrders\"),\n publicKey(\"marketId\"),\n publicKey(\"marketProgramId\"),\n publicKey(\"targetOrders\"),\n publicKey(\"owner\"),\n seq(u64(), 64, \"padding\"),\n]);\n\nexport const addLiquidityLayout = struct([\n u8(\"instruction\"),\n u64(\"baseAmountIn\"),\n u64(\"quoteAmountIn\"),\n u64(\"fixedSide\"),\n u64(\"otherAmountMin\"),\n]);\n\nexport const removeLiquidityLayout = struct([\n u8(\"instruction\"),\n u64(\"lpAmount\"),\n u64(\"baseAmountMin\"),\n u64(\"quoteAmountMin\"),\n]);\n\nexport type LiquidityStateLayoutV5 = typeof liquidityStateV5Layout;\nexport type LiquidityStateV5 = GetStructureSchema<LiquidityStateLayoutV5>;\n\nexport type LiquidityState = LiquidityStateV4 | LiquidityStateV5;\nexport type LiquidityStateLayout = LiquidityStateLayoutV4 | LiquidityStateLayoutV5;\n\n/* ================= index ================= */\n// version => liquidity state layout\nexport const LIQUIDITY_VERSION_TO_STATE_LAYOUT: {\n [version: number]: LiquidityStateLayout;\n} = {\n 4: liquidityStateV4Layout,\n 5: liquidityStateV5Layout,\n};\nexport const createPoolFeeLayout = struct([u64(\"fee\")]);\n","import { Connection, PublicKey } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport Decimal from \"decimal.js\";\nimport { AmmV4Keys, AmmV5Keys } from \"../../api/type\";\nimport { TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\nimport {\n findProgramAddress,\n parseSimulateLogToJson,\n parseSimulateValue,\n simulateMultipleInstruction,\n} from \"@/common/txTool/txUtils\";\nimport { toApiV3Token } from \"../../raydium/token/utils\";\nimport { makeSimulatePoolInfoInstruction } from \"./instruction\";\nimport { getSerumAssociatedAuthority } from \"./serum\";\nimport { StableLayout } from \"./stable\";\nimport { AmmRpcData, ComputeAmountOutParam, LiquidityPoolKeys } from \"./type\";\nimport { liquidityStateV4Layout } from \"./layout\";\nimport { splAccountLayout } from \"../account\";\nimport { SPL_MINT_LAYOUT } from \"../token\";\n\ntype AssociatedName =\n | \"amm_associated_seed\"\n | \"lp_mint_associated_seed\"\n | \"coin_vault_associated_seed\"\n | \"pc_vault_associated_seed\"\n | \"lp_mint_associated_seed\"\n | \"temp_lp_token_associated_seed\"\n | \"open_order_associated_seed\"\n | \"target_associated_seed\"\n | \"withdraw_associated_seed\";\n\ninterface GetAssociatedParam {\n name: AssociatedName;\n programId: PublicKey;\n marketId: PublicKey;\n}\n\nexport function getAssociatedConfigId({ programId }: { programId: PublicKey }): PublicKey {\n const { publicKey } = findProgramAddress([Buffer.from(\"amm_config_account_seed\", \"utf-8\")], programId);\n return publicKey;\n}\n\nexport function getLiquidityAssociatedId({ name, programId, marketId }: GetAssociatedParam): PublicKey {\n const { publicKey } = findProgramAddress(\n [programId.toBuffer(), marketId.toBuffer(), Buffer.from(name, \"utf-8\")],\n programId,\n );\n return publicKey;\n}\n\nexport function getAssociatedOpenOrders({ programId, marketId }: { programId: PublicKey; marketId: PublicKey }) {\n const { publicKey } = findProgramAddress(\n [programId.toBuffer(), marketId.toBuffer(), Buffer.from(\"open_order_associated_seed\", \"utf-8\")],\n programId,\n );\n return publicKey;\n}\n\nexport function getLiquidityAssociatedAuthority({ programId }: { programId: PublicKey }): {\n publicKey: PublicKey;\n nonce: number;\n} {\n return findProgramAddress([Buffer.from([97, 109, 109, 32, 97, 117, 116, 104, 111, 114, 105, 116, 121])], programId);\n}\n\nexport function getAssociatedPoolKeys({\n version,\n marketVersion,\n marketId,\n baseMint,\n quoteMint,\n baseDecimals,\n quoteDecimals,\n programId,\n marketProgramId,\n}: {\n version: 4 | 5;\n marketVersion: 3;\n marketId: PublicKey;\n baseMint: PublicKey;\n quoteMint: PublicKey;\n baseDecimals: number;\n quoteDecimals: number;\n programId: PublicKey;\n marketProgramId: PublicKey;\n}): LiquidityPoolKeys {\n const id = getLiquidityAssociatedId({ name: \"amm_associated_seed\", programId, marketId });\n const lpMint = getLiquidityAssociatedId({ name: \"lp_mint_associated_seed\", programId, marketId });\n const { publicKey: authority, nonce } = getLiquidityAssociatedAuthority({ programId });\n const baseVault = getLiquidityAssociatedId({ name: \"coin_vault_associated_seed\", programId, marketId });\n const quoteVault = getLiquidityAssociatedId({ name: \"pc_vault_associated_seed\", programId, marketId });\n const lpVault = getLiquidityAssociatedId({ name: \"temp_lp_token_associated_seed\", programId, marketId });\n const openOrders = getAssociatedOpenOrders({ programId, marketId });\n const targetOrders = getLiquidityAssociatedId({ name: \"target_associated_seed\", programId, marketId });\n const withdrawQueue = getLiquidityAssociatedId({ name: \"withdraw_associated_seed\", programId, marketId });\n\n const { publicKey: marketAuthority } = getSerumAssociatedAuthority({\n programId: marketProgramId,\n marketId,\n });\n\n return {\n // base\n id,\n baseMint,\n quoteMint,\n lpMint,\n baseDecimals,\n quoteDecimals,\n lpDecimals: baseDecimals,\n // version\n version,\n programId,\n // keys\n authority,\n nonce,\n baseVault,\n quoteVault,\n lpVault,\n openOrders,\n targetOrders,\n withdrawQueue,\n // market version\n marketVersion,\n marketProgramId,\n // market keys\n marketId,\n marketAuthority,\n lookupTableAccount: PublicKey.default,\n configId: getAssociatedConfigId({ programId }),\n };\n}\n\nlet stableLayout: StableLayout | undefined;\n\nexport async function fetchMultipleInfo({\n connection,\n poolKeysList,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n config,\n modelDataPubKey,\n}: {\n connection: Connection;\n poolKeysList: (AmmV4Keys | AmmV5Keys)[];\n config: any;\n modelDataPubKey?: PublicKey;\n}): Promise<\n {\n status: BN;\n baseDecimals: number;\n quoteDecimals: number;\n lpDecimals: number;\n baseReserve: BN;\n quoteReserve: BN;\n lpSupply: BN;\n startTime: BN;\n }[]\n> {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const loadStable = poolKeysList.find((i) => i.modelDataAccount);\n if (loadStable) {\n if (!stableLayout) {\n stableLayout = new StableLayout({ connection, modelDataPubKey });\n await stableLayout.initStableModelLayout();\n }\n }\n return await Promise.all(\n poolKeysList.map(async (itemPoolKey) => {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n if (itemPoolKey.modelDataAccount) {\n const instructions = makeSimulatePoolInfoInstruction({ poolKeys: itemPoolKey });\n const logs = await simulateMultipleInstruction(connection, [instructions.instruction], \"GetPoolData\");\n const poolsInfo = logs.map((log) => {\n const json = parseSimulateLogToJson(log, \"GetPoolData\");\n const status = new BN(parseSimulateValue(json, \"status\"));\n const baseDecimals = Number(parseSimulateValue(json, \"coin_decimals\"));\n const quoteDecimals = Number(parseSimulateValue(json, \"pc_decimals\"));\n const lpDecimals = Number(parseSimulateValue(json, \"lp_decimals\"));\n const baseReserve = new BN(parseSimulateValue(json, \"pool_coin_amount\"));\n const quoteReserve = new BN(parseSimulateValue(json, \"pool_pc_amount\"));\n const lpSupply = new BN(parseSimulateValue(json, \"pool_lp_supply\"));\n // TODO fix it when split stable\n let startTime = \"0\";\n try {\n startTime = parseSimulateValue(json, \"pool_open_time\");\n } catch (error) {\n //\n }\n return {\n status,\n baseDecimals,\n quoteDecimals,\n lpDecimals,\n baseReserve,\n quoteReserve,\n lpSupply,\n startTime: new BN(startTime),\n };\n })[0];\n return poolsInfo;\n } else {\n const [poolAcc, vaultAccA, vaultAccB, mintAccLp] = await connection.getMultipleAccountsInfo([\n new PublicKey(itemPoolKey.id),\n new PublicKey(itemPoolKey.vault.A),\n new PublicKey(itemPoolKey.vault.B),\n new PublicKey(itemPoolKey.mintLp.address),\n ]);\n if (poolAcc === null) throw Error(\"fetch pool error\");\n if (vaultAccA === null) throw Error(\"fetch vaultAccA error\");\n if (vaultAccB === null) throw Error(\"fetch vaultAccB error\");\n if (mintAccLp === null) throw Error(\"fetch mintAccLp error\");\n const poolInfo = liquidityStateV4Layout.decode(poolAcc.data);\n const vaultInfoA = splAccountLayout.decode(vaultAccA.data);\n const vaultInfoB = splAccountLayout.decode(vaultAccB.data);\n const lpInfo = SPL_MINT_LAYOUT.decode(mintAccLp.data);\n return {\n status: poolInfo.status,\n baseDecimals: poolInfo.baseDecimal.toNumber(),\n quoteDecimals: poolInfo.quoteDecimal.toNumber(),\n lpDecimals: lpInfo.decimals,\n baseReserve: vaultInfoA.amount.sub(poolInfo.baseNeedTakePnl),\n quoteReserve: vaultInfoB.amount.sub(poolInfo.quoteNeedTakePnl),\n lpSupply: poolInfo.lpReserve,\n startTime: poolInfo.poolOpenTime,\n };\n }\n }),\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 const toAmmComputePoolInfo = (\n poolData: Record<string, AmmRpcData>,\n): Record<string, ComputeAmountOutParam[\"poolInfo\"]> => {\n const data: Record<string, ComputeAmountOutParam[\"poolInfo\"]> = {};\n const tokenProgramStr = TOKEN_PROGRAM_ID.toBase58();\n\n Object.keys(poolData).map((poolId) => {\n const poolInfo = poolData[poolId];\n const [mintA, mintB] = [poolInfo.baseMint.toBase58(), poolInfo.quoteMint.toBase58()];\n data[poolId] = {\n id: poolId,\n version: 4,\n status: poolInfo.status.toNumber(),\n programId: poolInfo.programId.toBase58(), // needed\n mintA: toApiV3Token({\n address: mintA, // needed\n programId: tokenProgramStr,\n decimals: poolInfo.baseDecimal.toNumber(),\n }),\n mintB: toApiV3Token({\n address: mintB, // needed\n programId: tokenProgramStr,\n decimals: poolInfo.quoteDecimal.toNumber(),\n }),\n rewardDefaultInfos: [],\n rewardDefaultPoolInfos: \"Ecosystem\",\n price: poolInfo.poolPrice.toNumber(),\n mintAmountA: new Decimal(poolInfo.mintAAmount.toString()).div(10 ** poolInfo.baseDecimal.toNumber()).toNumber(),\n mintAmountB: new Decimal(poolInfo.mintBAmount.toString()).div(10 ** poolInfo.quoteDecimal.toNumber()).toNumber(),\n baseReserve: poolInfo.baseReserve, // needed\n quoteReserve: poolInfo.quoteReserve, // needed\n feeRate: new Decimal(poolInfo.tradeFeeNumerator.toString())\n .div(poolInfo.tradeFeeDenominator.toString())\n .toNumber(),\n openTime: poolInfo.poolOpenTime.toString(),\n tvl: 0,\n day: mockRewardData,\n week: mockRewardData,\n month: mockRewardData,\n pooltype: [],\n farmUpcomingCount: 0,\n farmOngoingCount: 0,\n farmFinishedCount: 0,\n type: \"Standard\",\n marketId: poolInfo.marketId.toBase58(),\n configId: getAssociatedConfigId({ programId: poolInfo.programId }).toBase58(),\n lpPrice: 0,\n lpAmount: new Decimal(poolInfo.lpReserve.toString())\n .div(10 ** Math.min(poolInfo.baseDecimal.toNumber(), poolInfo.quoteDecimal.toNumber()))\n .toNumber(),\n lpMint: toApiV3Token({\n address: poolInfo.lpMint.toBase58(),\n programId: tokenProgramStr,\n decimals: Math.min(poolInfo.baseDecimal.toNumber(), poolInfo.quoteDecimal.toNumber()),\n }),\n burnPercent: 0,\n };\n });\n return data;\n};\n","/*\r\n * decimal.js v10.3.1\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2021 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licence\r\n */\r\n\r\n\r\n// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //\r\n\r\n\r\n // The maximum exponent magnitude.\r\n // The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.\r\nvar EXP_LIMIT = 9e15, // 0 to 9e15\r\n\r\n // The limit on the value of `precision`, and on the value of the first argument to\r\n // `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.\r\n MAX_DIGITS = 1e9, // 0 to 1e9\r\n\r\n // Base conversion alphabet.\r\n NUMERALS = '0123456789abcdef',\r\n\r\n // The natural logarithm of 10 (1025 digits).\r\n LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',\r\n\r\n // Pi (1025 digits).\r\n PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',\r\n\r\n\r\n // The initial configuration properties of the Decimal constructor.\r\n DEFAULTS = {\r\n\r\n // These values must be integers within the stated ranges (inclusive).\r\n // Most of these values can be changed at run-time using the `Decimal.config` method.\r\n\r\n // The maximum number of significant digits of the result of a calculation or base conversion.\r\n // E.g. `Decimal.config({ precision: 20 });`\r\n precision: 20, // 1 to MAX_DIGITS\r\n\r\n // The rounding mode used when rounding to `precision`.\r\n //\r\n // ROUND_UP 0 Away from zero.\r\n // ROUND_DOWN 1 Towards zero.\r\n // ROUND_CEIL 2 Towards +Infinity.\r\n // ROUND_FLOOR 3 Towards -Infinity.\r\n // ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n //\r\n // E.g.\r\n // `Decimal.rounding = 4;`\r\n // `Decimal.rounding = Decimal.ROUND_HALF_UP;`\r\n rounding: 4, // 0 to 8\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend (JavaScript %).\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 The IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.\r\n //\r\n // Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian\r\n // division (9) are commonly used for the modulus operation. The other rounding modes can also\r\n // be used, but they may not give useful results.\r\n modulo: 1, // 0 to 9\r\n\r\n // The exponent value at and beneath which `toString` returns exponential notation.\r\n // JavaScript numbers: -7\r\n toExpNeg: -7, // 0 to -EXP_LIMIT\r\n\r\n // The exponent value at and above which `toString` returns exponential notation.\r\n // JavaScript numbers: 21\r\n toExpPos: 21, // 0 to EXP_LIMIT\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // JavaScript numbers: -324 (5e-324)\r\n minE: -EXP_LIMIT, // -1 to -EXP_LIMIT\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // JavaScript numbers: 308 (1.7976931348623157e+308)\r\n maxE: EXP_LIMIT, // 1 to EXP_LIMIT\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n crypto: false // true/false\r\n },\r\n\r\n\r\n// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //\r\n\r\n\r\n inexact, quadrant,\r\n external = true,\r\n\r\n decimalError = '[DecimalError] ',\r\n invalidArgument = decimalError + 'Invalid argument: ',\r\n precisionLimitExceeded = decimalError + 'Precision limit exceeded',\r\n cryptoUnavailable = decimalError + 'crypto unavailable',\r\n tag = '[object Decimal]',\r\n\r\n mathfloor = Math.floor,\r\n mathpow = Math.pow,\r\n\r\n isBinary = /^0b([01]+(\\.[01]*)?|\\.[01]+)(p[+-]?\\d+)?$/i,\r\n isHex = /^0x([0-9a-f]+(\\.[0-9a-f]*)?|\\.[0-9a-f]+)(p[+-]?\\d+)?$/i,\r\n isOctal = /^0o([0-7]+(\\.[0-7]*)?|\\.[0-7]+)(p[+-]?\\d+)?$/i,\r\n isDecimal = /^(\\d+(\\.\\d*)?|\\.\\d+)(e[+-]?\\d+)?$/i,\r\n\r\n BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_SAFE_INTEGER = 9007199254740991,\r\n\r\n LN10_PRECISION = LN10.length - 1,\r\n PI_PRECISION = PI.length - 1,\r\n\r\n // Decimal.prototype object\r\n P = { toStringTag: tag };\r\n\r\n\r\n// Decimal prototype methods\r\n\r\n\r\n/*\r\n * absoluteValue abs\r\n * ceil\r\n * clampedTo clamp\r\n * comparedTo cmp\r\n * cosine cos\r\n * cubeRoot cbrt\r\n * decimalPlaces dp\r\n * dividedBy div\r\n * dividedToIntegerBy divToInt\r\n * equals eq\r\n * floor\r\n * greaterThan gt\r\n * greaterThanOrEqualTo gte\r\n * hyperbolicCosine cosh\r\n * hyperbolicSine sinh\r\n * hyperbolicTangent tanh\r\n * inverseCosine acos\r\n * inverseHyperbolicCosine acosh\r\n * inverseHyperbolicSine asinh\r\n * inverseHyperbolicTangent atanh\r\n * inverseSine asin\r\n * inverseTangent atan\r\n * isFinite\r\n * isInteger isInt\r\n * isNaN\r\n * isNegative isNeg\r\n * isPositive isPos\r\n * isZero\r\n * lessThan lt\r\n * lessThanOrEqualTo lte\r\n * logarithm log\r\n * [maximum] [max]\r\n * [minimum] [min]\r\n * minus sub\r\n * modulo mod\r\n * naturalExponential exp\r\n * naturalLogarithm ln\r\n * negated neg\r\n * plus add\r\n * precision sd\r\n * round\r\n * sine sin\r\n * squareRoot sqrt\r\n * tangent tan\r\n * times mul\r\n * toBinary\r\n * toDecimalPlaces toDP\r\n * toExponential\r\n * toFixed\r\n * toFraction\r\n * toHexadecimal toHex\r\n * toNearest\r\n * toNumber\r\n * toOctal\r\n * toPower pow\r\n * toPrecision\r\n * toSignificantDigits toSD\r\n * toString\r\n * truncated trunc\r\n * valueOf toJSON\r\n */\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the absolute value of this Decimal.\r\n *\r\n */\r\nP.absoluteValue = P.abs = function () {\r\n var x = new this.constructor(this);\r\n if (x.s < 0) x.s = 1;\r\n return finalise(x);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the\r\n * direction of positive Infinity.\r\n *\r\n */\r\nP.ceil = function () {\r\n return finalise(new this.constructor(this), this.e + 1, 2);\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the value of this Decimal clamped to the range\r\n * delineated by `min` and `max`.\r\n *\r\n * min {number|string|Decimal}\r\n * max {number|string|Decimal}\r\n *\r\n */\r\nP.clampedTo = P.clamp = function (min, max) {\r\n var k,\r\n x = this,\r\n Ctor = x.constructor;\r\n min = new Ctor(min);\r\n max = new Ctor(max);\r\n if (!min.s || !max.s) return new Ctor(NaN);\r\n if (min.gt(max)) throw Error(invalidArgument + max);\r\n k = x.cmp(min);\r\n return k < 0 ? min : x.cmp(max) > 0 ? max : new Ctor(x);\r\n};\r\n\r\n\r\n/*\r\n * Return\r\n * 1 if the value of this Decimal is greater than the value of `y`,\r\n * -1 if the value of this Decimal is less than the value of `y`,\r\n * 0 if they have the same value,\r\n * NaN if the value of either Decimal is NaN.\r\n *\r\n */\r\nP.comparedTo = P.cmp = function (y) {\r\n var i, j, xdL, ydL,\r\n x = this,\r\n xd = x.d,\r\n yd = (y = new x.constructor(y)).d,\r\n xs = x.s,\r\n ys = y.s;\r\n\r\n // Either NaN or ±Infinity?\r\n if (!xd || !yd) {\r\n return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Either zero?\r\n if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;\r\n\r\n // Signs differ?\r\n if (xs !== ys) return xs;\r\n\r\n // Compare exponents.\r\n if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;\r\n\r\n xdL = xd.length;\r\n ydL = yd.length;\r\n\r\n // Compare digit by digit.\r\n for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {\r\n if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;\r\n }\r\n\r\n // Compare lengths.\r\n return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;\r\n};\r\n\r\n\r\n/*\r\n * Return a new Decimal whose value is the cosine of the value in radians of this Decimal.\r\n *\r\n * Domain: [-Infinity, Infinity]\r\n * Range: [-1, 1]\r\n *\r\n * cos(0) = 1\r\n * cos(-0)