UNPKG

snapper-sdk

Version:

An SDK for building applications on top of Snapper.

1 lines 864 kB
{"version":3,"sources":["../../../src/raydium/tradeV2/instrument.ts","../../../src/common/accountInfo.ts","../../../src/common/logger.ts","../../../src/common/bignumber.ts","../../../node_modules/decimal.js/decimal.mjs","../../../src/module/amount.ts","../../../src/module/formatter.ts","../../../src/module/fraction.ts","../../../src/common/constant.ts","../../../src/raydium/token/constant.ts","../../../src/module/token.ts","../../../src/common/pubKey.ts","../../../src/module/currency.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/txTool/txType.ts","../../../src/common/programId.ts","../../../src/common/transfer.ts","../../../src/common/txTool/lookupTable.ts","../../../src/common/txTool/txTool.ts","../../../src/marshmallow/index.ts","../../../src/marshmallow/buffer-layout.ts","../../../src/raydium/clmm/clmm.ts","../../../src/raydium/token/utils.ts","../../../src/raydium/clmm/instrument.ts","../../../src/raydium/clmm/utils/tick.ts","../../../src/raydium/clmm/utils/constants.ts","../../../src/raydium/clmm/utils/math.ts","../../../src/raydium/clmm/utils/util.ts","../../../src/raydium/clmm/utils/pda.ts","../../../src/raydium/clmm/utils/pool.ts","../../../src/raydium/clmm/utils/position.ts","../../../src/raydium/clmm/utils/tickQuery.ts","../../../src/raydium/clmm/utils/tickarrayBitmap.ts","../../../src/raydium/clmm/layout.ts","../../../src/raydium/liquidity/instruction.ts","../../../src/raydium/liquidity/layout.ts","../../../src/raydium/liquidity/stable.ts","../../../src/raydium/cpmm/layout.ts","../../../src/raydium/cpmm/instruction.ts","../../../src/raydium/cpmm/pda.ts","../../../src/raydium/cpmm/curve/calculator.ts","../../../src/raydium/cpmm/curve/constantProduct.ts","../../../src/raydium/cpmm/curve/fee.ts"],"sourcesContent":["import { PublicKey, SystemProgram, TransactionInstruction } from \"@solana/web3.js\";\nimport BN from \"bn.js\";\nimport { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from \"@solana/spl-token\";\n\nimport {\n InstructionType,\n LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL,\n MEMO_PROGRAM_ID2,\n accountMeta,\n jsonInfo2PoolKeys,\n} from \"@/common\";\nimport { seq, struct, u128, u64, u8 } from \"../../marshmallow\";\nimport {\n ClmmInstrument,\n MAX_SQRT_PRICE_X64,\n MAX_SQRT_PRICE_X64_SUB_ONE,\n MIN_SQRT_PRICE_X64,\n MIN_SQRT_PRICE_X64_ADD_ONE,\n ONE,\n getPdaExBitmapAccount,\n} from \"../clmm\";\nimport { makeAMMSwapInstruction } from \"../liquidity/instruction\";\n\nimport { AmmV4Keys, AmmV5Keys, ApiV3PoolInfoItem, ClmmKeys, CpmmKeys, PoolKeys } from \"../../api/type\";\nimport { makeSwapCpmmBaseInInInstruction } from \"../../raydium/cpmm\";\nimport { ComputePoolType, MakeSwapInstructionParam, ReturnTypeMakeSwapInstruction } from \"./type\";\n\nexport function route1Instruction(\n programId: PublicKey,\n poolInfoA: ApiV3PoolInfoItem,\n poolKeyA: PoolKeys,\n poolKeyB: PoolKeys,\n\n userSourceToken: PublicKey,\n userRouteToken: PublicKey,\n // userDestinationToken: PublicKey,\n userPdaAccount: PublicKey,\n ownerWallet: PublicKey,\n\n inputMint: PublicKey,\n\n amountIn: BN,\n amountOut: BN,\n\n tickArrayA?: PublicKey[],\n // tickArrayB?: PublicKey[],\n): TransactionInstruction {\n const dataLayout = struct([u8(\"instruction\"), u64(\"amountIn\"), u64(\"amountOut\")]);\n\n const keys: { pubkey: PublicKey; isSigner: boolean; isWritable: boolean }[] = [\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: new PublicKey(poolKeyA.programId), isSigner: false, isWritable: false },\n { pubkey: new PublicKey(poolKeyA.id), isSigner: false, isWritable: true },\n { pubkey: new PublicKey(poolKeyB.id), isSigner: false, isWritable: true },\n\n { pubkey: userSourceToken, isSigner: false, isWritable: true },\n { pubkey: userRouteToken, isSigner: false, isWritable: true },\n { pubkey: userPdaAccount, isSigner: false, isWritable: true },\n { pubkey: ownerWallet, isSigner: true, isWritable: false },\n ];\n\n if (poolInfoA.type === \"Concentrated\") {\n const poolKey = jsonInfo2PoolKeys(poolKeyA as ClmmKeys);\n keys.push(\n ...[\n { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n {\n pubkey: poolKey.mintA.address.equals(inputMint) ? poolKey.vault.A : poolKey.vault.B,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: poolKey.mintA.address.equals(inputMint) ? poolKey.vault.B : poolKey.vault.A,\n isSigner: false,\n isWritable: true,\n },\n // { pubkey: poolKey.observationId, isSigner: false, isWritable: true }, // to do\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ...tickArrayA!.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n ],\n );\n } else if (poolInfoA.pooltype.includes(\"StablePool\")) {\n const poolKey = jsonInfo2PoolKeys(poolKeyA as AmmV5Keys);\n keys.push(\n ...[\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ],\n );\n } else {\n const poolKey = jsonInfo2PoolKeys(poolKeyA as AmmV4Keys);\n keys.push(\n ...[\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: false },\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n ? [\n { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n ]\n : [\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ]),\n ],\n );\n }\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n instruction: 4,\n amountIn,\n amountOut,\n },\n data,\n );\n\n return new TransactionInstruction({\n keys,\n programId,\n data,\n });\n}\n\nexport function route2Instruction(\n programId: PublicKey,\n poolInfoB: ApiV3PoolInfoItem,\n poolKeyA: PoolKeys,\n poolKeyB: PoolKeys,\n\n // userSourceToken: PublicKey,\n userRouteToken: PublicKey,\n userDestinationToken: PublicKey,\n userPdaAccount: PublicKey,\n ownerWallet: PublicKey,\n\n routeMint: PublicKey,\n\n // tickArrayA?: PublicKey[],\n tickArrayB?: PublicKey[],\n): TransactionInstruction {\n const dataLayout = struct([u8(\"instruction\")]);\n\n const keys: { pubkey: PublicKey; isSigner: boolean; isWritable: boolean }[] = [\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: new PublicKey(String(poolKeyB.programId)), isSigner: false, isWritable: false },\n { pubkey: new PublicKey(String(poolKeyB.id)), isSigner: false, isWritable: true },\n { pubkey: new PublicKey(String(poolKeyA.id)), isSigner: false, isWritable: true },\n\n { pubkey: userRouteToken, isSigner: false, isWritable: true },\n { pubkey: userDestinationToken, isSigner: false, isWritable: true },\n { pubkey: userPdaAccount, isSigner: false, isWritable: true },\n { pubkey: ownerWallet, isSigner: true, isWritable: false },\n ];\n\n if (poolInfoB.type === \"Concentrated\") {\n const poolKey = jsonInfo2PoolKeys(poolKeyB as ClmmKeys);\n keys.push(\n ...[\n { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n {\n pubkey: poolKey.mintA.address.equals(routeMint) ? poolKey.vault.A : poolKey.vault.B,\n isSigner: false,\n isWritable: true,\n },\n {\n pubkey: poolKey.mintA.address.equals(routeMint) ? poolKey.vault.B : poolKey.vault.A,\n isSigner: false,\n isWritable: true,\n },\n // { pubkey: poolKey.observationId, isSigner: false, isWritable: true }, // to do\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ...tickArrayB!.map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n ],\n );\n } else if (poolInfoB.pooltype.includes(\"StablePool\")) {\n const poolKey = jsonInfo2PoolKeys(poolKeyB as AmmV5Keys);\n keys.push(\n ...[\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ],\n );\n } else {\n const poolKey = jsonInfo2PoolKeys(poolKeyB as AmmV4Keys);\n keys.push(\n ...[\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: false },\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n ? [\n { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n ]\n : [\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ]),\n ],\n );\n }\n\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n instruction: 5,\n },\n data,\n );\n\n return new TransactionInstruction({\n keys,\n programId,\n data,\n });\n}\n\n/*\nfunction makeInnerInsKey(\n itemPool: ComputePoolType,\n itemPoolKey: PoolKeys,\n inMint: string,\n userInAccount: PublicKey,\n userOutAccount: PublicKey,\n remainingAccount: PublicKey[] | undefined,\n): AccountMeta[] {\n if (itemPool.version === 4) {\n const poolKey = jsonInfo2PoolKeys(itemPoolKey as AmmV4Keys);\n\n return [\n { pubkey: poolKey.programId, isSigner: false, isWritable: false },\n { pubkey: userInAccount, isSigner: false, isWritable: true },\n { pubkey: userOutAccount, isSigner: false, isWritable: true },\n\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketAuthority, isSigner: false, isWritable: true },\n\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n ...(poolKey.marketProgramId.toString() === \"srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX\"\n ? [\n { pubkey: poolKey.marketBaseVault, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketQuoteVault, isSigner: false, isWritable: true },\n ]\n : [\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ]),\n ];\n } else if (itemPool.version === 5) {\n const poolKey = jsonInfo2PoolKeys(itemPoolKey as AmmV4Keys);\n\n return [\n { pubkey: poolKey.programId, isSigner: false, isWritable: false },\n { pubkey: userInAccount, isSigner: false, isWritable: true },\n { pubkey: userOutAccount, isSigner: false, isWritable: true },\n\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.authority, isSigner: false, isWritable: false },\n { pubkey: poolKey.marketProgramId, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: new PublicKey(\"CDSr3ssLcRB6XYPJwAfFt18MZvEZp4LjHcvzBVZ45duo\"), isSigner: false, isWritable: false },\n { pubkey: poolKey.openOrders, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketId, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketBids, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketAsks, isSigner: false, isWritable: true },\n { pubkey: poolKey.marketEventQueue, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n ];\n } else if (itemPool.version === 6) {\n const pool = itemPool;\n const poolKey = jsonInfo2PoolKeys(itemPoolKey as ClmmKeys);\n const baseIn = pool.mintA.address === inMint;\n return [\n { pubkey: new PublicKey(String(itemPool.programId)), isSigner: false, isWritable: false },\n { pubkey: userInAccount, isSigner: false, isWritable: true },\n { pubkey: userOutAccount, isSigner: false, isWritable: true },\n { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: baseIn ? poolKey.vault.A : poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: baseIn ? poolKey.vault.B : poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: itemPool.observationId, isSigner: false, isWritable: true },\n ...(poolKey.mintA.programId.equals(TOKEN_2022_PROGRAM_ID) || poolKey.mintB.programId.equals(TOKEN_2022_PROGRAM_ID)\n ? [\n { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: baseIn ? poolKey.mintA.address : poolKey.mintB.address, isSigner: false, isWritable: false },\n { pubkey: baseIn ? poolKey.mintB.address : poolKey.mintA.address, isSigner: false, isWritable: false },\n ]\n : []),\n ...(remainingAccount ?? []).map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n {\n pubkey: getPdaExBitmapAccount(new PublicKey(String(itemPool.programId)), new PublicKey(itemPool.id)).publicKey,\n isSigner: false,\n isWritable: true,\n },\n ];\n } else if (itemPool.version === 7) {\n const pool = itemPool;\n const poolKey = jsonInfo2PoolKeys(itemPoolKey as CpmmKeys);\n const baseIn = pool.mintA.address === inMint;\n return [\n { pubkey: new PublicKey(String(itemPool.programId)), isSigner: false, isWritable: false },\n { pubkey: userInAccount, isSigner: false, isWritable: true },\n { pubkey: userOutAccount, isSigner: false, isWritable: true },\n { pubkey: poolKey.config.id, isSigner: false, isWritable: false },\n { pubkey: poolKey.id, isSigner: false, isWritable: true },\n { pubkey: baseIn ? poolKey.vault.A : poolKey.vault.B, isSigner: false, isWritable: true },\n { pubkey: baseIn ? poolKey.vault.B : poolKey.vault.A, isSigner: false, isWritable: true },\n { pubkey: itemPool.observationId, isSigner: false, isWritable: true },\n ...(poolKey.mintA.programId.equals(TOKEN_2022_PROGRAM_ID) || poolKey.mintB.programId.equals(TOKEN_2022_PROGRAM_ID)\n ? [\n { pubkey: TOKEN_2022_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: MEMO_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: baseIn ? poolKey.mintA.address : poolKey.mintB.address, isSigner: false, isWritable: false },\n { pubkey: baseIn ? poolKey.mintB.address : poolKey.mintA.address, isSigner: false, isWritable: false },\n ]\n : []),\n ...(remainingAccount ?? []).map((i) => ({ pubkey: i, isSigner: false, isWritable: true })),\n {\n pubkey: getPdaExBitmapAccount(new PublicKey(String(itemPool.programId)), new PublicKey(itemPool.id)).publicKey,\n isSigner: false,\n isWritable: true,\n },\n ];\n } else {\n throw Error(\"make swap ins error\");\n }\n}\n*/\n\nexport function routeInstruction(\n programId: PublicKey,\n wallet: PublicKey,\n\n userSourceToken: PublicKey,\n userRouteToken: PublicKey,\n userDestinationToken: PublicKey,\n\n inputMint: string,\n routeMint: string,\n outputMint: string,\n\n poolInfoA: ComputePoolType,\n poolInfoB: ComputePoolType,\n\n poolKeyA: PoolKeys,\n poolKeyB: PoolKeys,\n\n amountIn: BN,\n amountOut: BN,\n\n remainingAccounts: (PublicKey[] | undefined)[],\n): TransactionInstruction {\n const clmmPriceLimit: BN[] = [];\n const keys = [\n accountMeta({ pubkey: TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: TOKEN_2022_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: ASSOCIATED_TOKEN_PROGRAM_ID, isWritable: false }),\n accountMeta({ pubkey: SystemProgram.programId, isWritable: false }),\n accountMeta({ pubkey: wallet, isSigner: true }),\n ];\n\n keys.push(accountMeta({ pubkey: userSourceToken }));\n keys.push(accountMeta({ pubkey: userDestinationToken }));\n\n const poolInfos = [poolInfoA, poolInfoB];\n const poolKeys = [poolKeyA, poolKeyB];\n const routeMints = [inputMint, routeMint, outputMint];\n\n for (let index = 0; index < poolInfos.length; index++) {\n const _poolInfo = poolInfos[index];\n const inputIsA = routeMints[index] === _poolInfo.mintA.address;\n keys.push(accountMeta({ pubkey: new PublicKey(_poolInfo.programId), isWritable: false }));\n if (index === poolInfos.length - 1) {\n keys.push(accountMeta({ pubkey: userDestinationToken }));\n } else {\n keys.push(accountMeta({ pubkey: userRouteToken }));\n }\n keys.push(accountMeta({ pubkey: new PublicKey(routeMints[index]) }));\n keys.push(accountMeta({ pubkey: new PublicKey(routeMints[index + 1]) }));\n if (_poolInfo.version === 6) {\n const _poolKey = poolKeys[index] as ClmmKeys;\n\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.config.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(inputIsA ? _poolKey.vault.A : _poolKey.vault.B) }));\n keys.push(accountMeta({ pubkey: new PublicKey(inputIsA ? _poolKey.vault.B : _poolKey.vault.A) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolInfo.observationId) })); //todo\n keys.push(accountMeta({ pubkey: MEMO_PROGRAM_ID2 }));\n keys.push(\n accountMeta({\n pubkey: getPdaExBitmapAccount(new PublicKey(_poolInfo.programId), new PublicKey(_poolInfo.id)).publicKey,\n }),\n );\n clmmPriceLimit.push(clmmPriceLimitX64InsData(_poolInfo.sqrtPriceX64.toString(), inputIsA));\n for (const item of remainingAccounts[index] ?? []) {\n keys.push(accountMeta({ pubkey: new PublicKey(item) }));\n }\n } else if (_poolInfo.version === 5) {\n const _poolKey = poolKeys[index] as AmmV5Keys;\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.authority), isWritable: false }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketProgramId) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketAuthority) }));\n keys.push(accountMeta({ pubkey: LIQUIDITY_POOL_PROGRAM_ID_V5_MODEL, isWritable: false }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.openOrders) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.vault.A) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.vault.B) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketId) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketBids) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketAsks) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketEventQueue) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketBaseVault) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.marketQuoteVault) }));\n } else if (_poolInfo.version === 4) {\n const _poolKey = poolKeys[index] as AmmV4Keys;\n const isSupportIdOnly = _poolInfo.status !== 1;\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.authority), isWritable: false }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketProgramId) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketAuthority) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.openOrders) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.vault.A) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.vault.B) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketId) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketBids) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketAsks) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketEventQueue) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketBaseVault) }));\n keys.push(accountMeta({ pubkey: new PublicKey(isSupportIdOnly ? _poolKey.id : _poolKey.marketQuoteVault) }));\n } else if (_poolInfo.version === 7) {\n const _poolKey = poolKeys[index] as CpmmKeys;\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.authority) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.config.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolKey.id) }));\n keys.push(accountMeta({ pubkey: new PublicKey(inputIsA ? _poolKey.vault.A : _poolKey.vault.B) }));\n keys.push(accountMeta({ pubkey: new PublicKey(inputIsA ? _poolKey.vault.B : _poolKey.vault.A) }));\n keys.push(accountMeta({ pubkey: new PublicKey(_poolInfo.observationId) }));\n } else throw Error(\"pool type error\");\n }\n\n const dataLayout = struct([\n u8(\"insId\"),\n u64(\"amountIn\"),\n u64(\"amountOut\"),\n seq(u128(), clmmPriceLimit.length, \"clmmPriceLimit\"),\n ]);\n const data = Buffer.alloc(dataLayout.span);\n dataLayout.encode(\n {\n insId: 0,\n amountIn,\n amountOut,\n clmmPriceLimit,\n },\n data,\n );\n return new TransactionInstruction({\n keys,\n programId,\n data,\n });\n}\n\nfunction clmmPriceLimitX64InsData(x64Price: string | undefined, inputIsA: boolean): BN {\n if (x64Price) {\n if (inputIsA) {\n const _m = new BN(x64Price).div(new BN(25));\n return _m.gt(MIN_SQRT_PRICE_X64_ADD_ONE) ? _m : MIN_SQRT_PRICE_X64_ADD_ONE;\n } else {\n const _m = new BN(x64Price).mul(new BN(25));\n return _m.lt(MAX_SQRT_PRICE_X64_SUB_ONE) ? _m : MAX_SQRT_PRICE_X64_SUB_ONE;\n }\n } else {\n return inputIsA ? MIN_SQRT_PRICE_X64_ADD_ONE : MAX_SQRT_PRICE_X64_SUB_ONE;\n }\n}\n\nexport function makeSwapInstruction({\n routeProgram,\n ownerInfo,\n inputMint,\n swapInfo,\n}: MakeSwapInstructionParam): ReturnTypeMakeSwapInstruction {\n if (swapInfo.routeType === \"amm\") {\n if (swapInfo.poolInfo[0].version === 6) {\n const poolKeys = swapInfo.poolKey[0] as ClmmKeys;\n const _poolKey = jsonInfo2PoolKeys(poolKeys);\n const sqrtPriceLimitX64 = inputMint.equals(_poolKey.mintA.address)\n ? MIN_SQRT_PRICE_X64.add(ONE)\n : MAX_SQRT_PRICE_X64.sub(ONE);\n\n return ClmmInstrument.makeSwapBaseInInstructions({\n poolInfo: poolKeys,\n poolKeys,\n observationId: swapInfo.poolInfo[0].observationId,\n ownerInfo: {\n wallet: ownerInfo.wallet,\n tokenAccountA: _poolKey.mintA.address.equals(inputMint) ? ownerInfo.sourceToken : ownerInfo.destinationToken,\n tokenAccountB: _poolKey.mintA.address.equals(inputMint) ? ownerInfo.destinationToken : ownerInfo.sourceToken,\n },\n inputMint,\n amountIn: swapInfo.amountIn.amount.raw,\n amountOutMin: swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n sqrtPriceLimitX64,\n remainingAccounts: swapInfo.remainingAccounts[0] ?? [],\n });\n } else if (swapInfo.poolInfo[0].version === 7) {\n const poolInfo = swapInfo.poolInfo[0];\n const baseIn = inputMint.toString() === swapInfo.poolInfo[0].mintA.address;\n\n return {\n signers: [],\n instructions: [\n makeSwapCpmmBaseInInInstruction(\n poolInfo.programId,\n ownerInfo.wallet,\n poolInfo.authority,\n poolInfo.configId,\n poolInfo.id,\n ownerInfo.sourceToken!,\n ownerInfo.destinationToken!,\n baseIn ? poolInfo.vaultA : poolInfo.vaultB,\n baseIn ? poolInfo.vaultB : poolInfo.vaultA,\n baseIn ? poolInfo.mintProgramA : poolInfo.mintProgramB,\n baseIn ? poolInfo.mintProgramB : poolInfo.mintProgramA,\n new PublicKey(poolInfo[baseIn ? \"mintA\" : \"mintB\"].address),\n new PublicKey(poolInfo[baseIn ? \"mintB\" : \"mintA\"].address),\n poolInfo.observationId,\n\n swapInfo.amountIn.amount.raw,\n swapInfo.minAmountOut.amount.raw,\n ),\n ],\n lookupTableAddress: [],\n instructionTypes: [baseIn ? InstructionType.CpmmSwapBaseIn : InstructionType.CpmmSwapBaseOut],\n address: {},\n };\n } else {\n const _poolKey = swapInfo.poolKey[0] as AmmV4Keys | AmmV5Keys;\n\n return {\n signers: [],\n instructions: [\n makeAMMSwapInstruction({\n poolKeys: _poolKey,\n version: swapInfo.poolInfo[0].pooltype.includes(\"StablePool\") ? 5 : 4,\n userKeys: {\n tokenAccountIn: ownerInfo.sourceToken,\n tokenAccountOut: ownerInfo.destinationToken,\n owner: ownerInfo.wallet,\n },\n amountIn: swapInfo.amountIn.amount.raw,\n amountOut: swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n fixedSide: \"in\",\n }),\n ],\n lookupTableAddress: _poolKey.lookupTableAccount ? [_poolKey.lookupTableAccount] : [],\n instructionTypes: [\n swapInfo.poolInfo[0].pooltype.includes(\"StablePool\")\n ? InstructionType.AmmV5SwapBaseIn\n : InstructionType.AmmV4SwapBaseIn,\n ],\n address: {},\n };\n }\n } else if (swapInfo.routeType === \"route\") {\n const poolInfo1 = swapInfo.poolInfo[0];\n const poolInfo2 = swapInfo.poolInfo[1];\n const poolKey1 = swapInfo.poolKey[0];\n const poolKey2 = swapInfo.poolKey[1];\n\n if (ownerInfo.routeToken === undefined) throw Error(\"owner route token account check error\");\n\n return {\n signers: [],\n instructions: [\n routeInstruction(\n routeProgram,\n ownerInfo.wallet,\n ownerInfo.sourceToken,\n ownerInfo.routeToken,\n ownerInfo.destinationToken,\n\n inputMint.toString(),\n swapInfo.middleToken.mint.toString(),\n swapInfo.outputMint.toString(),\n\n poolInfo1,\n poolInfo2,\n poolKey1,\n poolKey2,\n\n swapInfo.amountIn.amount.raw,\n swapInfo.minAmountOut.amount.raw.sub(swapInfo.minAmountOut.fee?.raw ?? new BN(0)),\n\n swapInfo.remainingAccounts,\n ),\n ],\n instructionTypes: [InstructionType.RouteSwap],\n lookupTableAddress: [poolKey1.lookupTableAccount, poolKey2.lookupTableAccount].filter(\n (a) => a !== undefined,\n ) as string[],\n address: {},\n };\n } else {\n throw Error(\"route type error\");\n }\n}\n","import { AccountInfo, Commitment, Connection, PublicKey } from \"@solana/web3.js\";\nimport { ReturnTypeFetchMultipleMintInfos } from \"../raydium/type\";\nimport { WSOLMint, chunkArray, solToWSol } from \"./\";\nimport { createLogger } from \"./logger\";\nimport { MINT_SIZE, TOKEN_PROGRAM_ID, getTransferFeeConfig, unpackMint } from \"@solana/spl-token\";\n\ninterface MultipleAccountsJsonRpcResponse {\n jsonrpc: string;\n id: string;\n error?: {\n code: number;\n message: string;\n };\n result: {\n context: { slot: number };\n value: { data: Array<string>; executable: boolean; lamports: number; owner: string; rentEpoch: number }[];\n };\n}\n\nexport interface GetMultipleAccountsInfoConfig {\n batchRequest?: boolean;\n commitment?: Commitment;\n chunkCount?: number;\n}\n\nconst logger = createLogger(\"Raydium_accountInfo_util\");\n\nexport async function getMultipleAccountsInfo(\n connection: Connection,\n publicKeys: PublicKey[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<(AccountInfo<Buffer> | null)[]> {\n const {\n batchRequest,\n commitment = \"confirmed\",\n chunkCount = 100,\n } = {\n batchRequest: false,\n ...config,\n };\n\n const chunkedKeys = chunkArray(publicKeys, chunkCount);\n let results: (AccountInfo<Buffer> | null)[][] = new Array(chunkedKeys.length).fill([]);\n\n if (batchRequest) {\n const batch = chunkedKeys.map((keys) => {\n const args = connection._buildArgs([keys.map((key) => key.toBase58())], commitment, \"base64\");\n return {\n methodName: \"getMultipleAccounts\",\n args,\n };\n });\n\n const _batch = chunkArray(batch, 10);\n\n const unsafeResponse: MultipleAccountsJsonRpcResponse[] = await (\n await Promise.all(_batch.map(async (i) => await (connection as any)._rpcBatchRequest(i)))\n ).flat();\n results = unsafeResponse.map((unsafeRes: MultipleAccountsJsonRpcResponse) => {\n if (unsafeRes.error)\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${unsafeRes.error.message}`);\n\n return unsafeRes.result.value.map((accountInfo) => {\n if (accountInfo) {\n const { data, executable, lamports, owner, rentEpoch } = accountInfo;\n\n if (data.length !== 2 && data[1] !== \"base64\") logger.logWithError(`info must be base64 encoded, RPC_ERROR`);\n\n return {\n data: Buffer.from(data[0], \"base64\"),\n executable,\n lamports,\n owner: new PublicKey(owner),\n rentEpoch,\n };\n }\n return null;\n });\n });\n } else {\n try {\n results = (await Promise.all(\n chunkedKeys.map((keys) => connection.getMultipleAccountsInfo(keys, commitment)),\n )) as (AccountInfo<Buffer> | null)[][];\n } catch (error) {\n if (error instanceof Error) {\n logger.logWithError(`failed to get info for multiple accounts, RPC_ERROR, ${error.message}`);\n }\n }\n }\n\n return results.flat();\n}\n\nexport async function getMultipleAccountsInfoWithCustomFlags<T extends { pubkey: PublicKey }>(\n connection: Connection,\n publicKeysWithCustomFlag: T[],\n config?: GetMultipleAccountsInfoConfig,\n): Promise<({ accountInfo: AccountInfo<Buffer> | null } & T)[]> {\n const multipleAccountsInfo = await getMultipleAccountsInfo(\n connection,\n publicKeysWithCustomFlag.map((o) => o.pubkey),\n config,\n );\n\n return publicKeysWithCustomFlag.map((o, idx) => ({ ...o, accountInfo: multipleAccountsInfo[idx] }));\n}\n\nexport enum AccountType {\n Uninitialized,\n Mint,\n Account,\n}\nexport const ACCOUNT_TYPE_SIZE = 1;\n\nexport async function fetchMultipleMintInfos({\n connection,\n mints,\n config,\n}: {\n connection: Connection;\n mints: PublicKey[];\n config?: { batchRequest?: boolean };\n}): Promise<ReturnTypeFetchMultipleMintInfos> {\n if (mints.length === 0) return {};\n const mintInfos = await getMultipleAccountsInfoWithCustomFlags(\n connection,\n mints.map((i) => ({ pubkey: solToWSol(i) })),\n config,\n );\n\n const mintK: ReturnTypeFetchMultipleMintInfos = {};\n for (const i of mintInfos) {\n if (!i.accountInfo || i.accountInfo.data.length < MINT_SIZE) {\n console.log(\"invalid mint account\", i.pubkey.toBase58());\n continue;\n }\n const t = unpackMint(i.pubkey, i.accountInfo, i.accountInfo?.owner);\n mintK[i.pubkey.toString()] = {\n ...t,\n programId: i.accountInfo?.owner || TOKEN_PROGRAM_ID,\n feeConfig: getTransferFeeConfig(t) ?? undefined,\n };\n }\n mintK[PublicKey.default.toBase58()] = mintK[WSOLMint.toBase58()];\n\n return mintK;\n}\n","import { 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 { CurrencyAmount, TokenAmount } from \"../module/amount\";\nimport { Currency } from \"../module/currency\";\nimport { Fraction } from \"../module/fraction\";\nimport { Percent } from \"../module/percent\";\nimport { Price } from \"../module/price\";\nimport { Token } from \"../module/token\";\nimport { SplToken, TokenJson } from \"../raydium/token/type\";\nimport { ReplaceType } from \"../raydium/type\";\nimport { parseBigNumberish } from \"./constant\";\nimport { mul } from \"./fractionUtil\";\nimport { notInnerObject } from \"./utility\";\n\nexport const BN_ZERO = new BN(0);\nexport const BN_ONE = new BN(1);\nexport const BN_TWO = new BN(2);\nexport const BN_THREE = new BN(3);\nexport const BN_FIVE = new BN(5);\nexport const BN_TEN = new BN(10);\nexport const BN_100 = new BN(100);\nexport const BN_1000 = new BN(1000);\nexport const BN_10000 = new BN(10000);\nexport type BigNumberish = BN | string | number | bigint;\nexport type Numberish = number | string | bigint | Fraction | BN;\n\n\nexport function tenExponential(shift: BigNumberish): BN {\n return BN_TEN.pow(parseBigNumberish(shift));\n}\n\n/**\n *\n * @example\n * getIntInfo(0.34) => { numerator: '34', denominator: '100'}\n * getIntInfo('0.34') //=> { numerator: '34', denominator: '100'}\n */\nexport function parseNumberInfo(n: Numberish | undefined): {\n denominator: string;\n numerator: string;\n sign?: string;\n int?: string;\n dec?: string;\n} {\n if (n === undefined) return { denominator: \"1\", numerator: \"0\" };\n if (n instanceof BN) {\n return { numerator: n.toString(), denominator: \"1\" };\n }\n\n if (n instanceof Fraction) {\n return { denominator: n.denominator.toString(), numerator: n.numerator.toString() };\n }\n\n const s = String(n);\n const [, sign = \"\", int = \"\", dec = \"\"] = s.replace(\",\", \"\").match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n const denominator = \"1\" + \"0\".repeat(dec.length);\n const numerator = sign + (int === \"0\" ? \"\" : int) + dec || \"0\";\n return { denominator, numerator, sign, int, dec };\n}\n\n// round up\nexport function divCeil(a: BN, b: BN): BN {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n const dm = a.divmod(b);\n\n // Fast case - exact division\n if (dm.mod.isZero()) return dm.div;\n\n // Round up\n return dm.div.isNeg() ? dm.div.isubn(1) : dm.div.iaddn(1);\n}\n\nexport function shakeFractionDecimal(n: Fraction): string {\n const [, sign = \"\", int = \"\"] = n.toFixed(2).match(/(-?)(\\d*)\\.?(\\d*)/) ?? [];\n return `${sign}${int}`;\n}\n\nexport function toBN(n: Numberish, decimal: BigNumberish = 0): BN {\n if (n instanceof BN) return n;\n return new BN(shakeFractionDecimal(toFraction(n).mul(BN_TEN.pow(new BN(String(decimal))))));\n}\n\nexport function toFraction(value: Numberish): Fraction {\n // to complete math format(may have decimal), not int\n if (value instanceof Percent) return new Fraction(value.numerator, value.denominator);\n\n if (value instanceof Price) return value.adjusted;\n\n // to complete math format(may have decimal), not BN\n if (value instanceof TokenAmount)\n try {\n return toFraction(value.toExact());\n } catch {\n return new Fraction(BN_ZERO);\n }\n\n // do not ideal with other fraction value\n if (value instanceof Fraction) return value;\n\n // wrap to Fraction\n const n = String(value);\n const details = parseNumberInfo(n);\n return new Fraction(details.numerator, details.denominator);\n}\n\n/**\n * @example\n * toPercent(3.14) // => Percent { 314.00% }\n * toPercent(3.14, { alreadyDecimaled: true }) // => Percent {3.14%}\n */\nexport function toPercent(\n n: Numberish,\n options?: { /* usually used for backend data */ alreadyDecimaled?: boolean },\n): Percent {\n const { numerator, denominator } = parseNumberInfo(n);\n return new Percent(new BN(numerator), new BN(denominator).mul(options?.alreadyDecimaled ? new BN(100) : new BN(1)));\n}\n\nexport function toTokenPrice(params: {\n token: TokenJson | Token | SplToken;\n numberPrice: Numberish;\n decimalDone?: boolean;\n}): Price {\n const { token, numberPrice, decimalDone } = params;\n const usdCurrency = new Token({ mint: \"\", decimals: 6, symbol: \"usd\", name: \"usd\", skipMint: true });\n const { numerator, denominator } = parseNumberInfo(numberPrice);\n const parsedNumerator = decimalDone ? new BN(numerator).mul(BN_TEN.pow(new BN(token.decimals))) : numerator;\n const parsedDenominator = new BN(denominator).mul(BN_TEN.pow(new BN(usdCurrency.decimals)));\n\n return new Price({\n baseToken: usdCurrency,\n denominator: parsedDenominator.toString(),\n quoteToken: new Token({ ...token, skipMint: true, mint: \"\" }),\n numerator: parsedNumerator.toString(),\n });\n}\n\nexport function toUsdCurrency(amount: Numberish): CurrencyAmount {\n const usdCurrency = new Currency({ decimals: 6, symbol: \"usd\", name: \"usd\" });\n const amountBigNumber = toBN(mul(amount, 10 ** usdCurrency.decimals)!);\n return new CurrencyAmount(usdCurrency, amountBigNumber);\n}\n\nexport function toTotalPrice(amount: Numberish | undefined, price: Price | undefined): CurrencyAmount {\n if (!price || !amount) return toUsdCurrency(0);\n return toUsdCurrency(mul(amount, price)!);\n}\n\nexport function decimalToFraction(n: Decimal | undefined): Fraction | undefined {\n if (n == null) return undefined;\n const { numerator, denominator } = parseNumberInfo(n.toString());\n return new Fraction(numerator, denominator);\n}\n\nexport function isDecimal(val: unknown): boolean {\n return val instanceof Decimal;\n}\n\nexport function recursivelyDecimalToFraction<T>(info: T): ReplaceType<T, Decimal, Fraction> {\n // @ts-expect-error no need type for inner code\n return isDecimal(info)\n ? decimalToFraction(info as any)\n : Array.isArray(info)\n ? info.map((k) => recursivelyDecimalToFraction(k))\n : notInnerObject(info)\n ? Object.fromEntries(Object.entries(info as any).map(([k, v]) => [k, recursivelyDecimalToFraction(v)]))\n : info;\n}\n","/*!\r\n * decimal.js v10.4.3\r\n * An arbitrary-precision Decimal type for JavaScript.\r\n * https://github.com/MikeMcl/decimal.js\r\n * Copyright (c) 2022 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