{"version":3,"sources":["../../src/modules/swapModule.ts"],"sourcesContent":["import {\n  AccountAddress,\n  InputEntryFunctionData,\n  Serializer,\n} from \"@aptos-labs/ts-sdk\";\nimport { ErrorNotFound } from \"../common/ErrorNotFound\";\nimport { TappSDK } from \"../core\";\nimport { Nullable, PoolInfo, RequestResult } from \"../types\";\nimport {\n  EstSwapBooks,\n  EstSwapResult,\n  GetEstSwapParams,\n  GetSOREstSwapParams,\n  SOREstSwapResult,\n  SOROrderBook,\n  SwapAMMParams,\n  SwapCLMMParams,\n  SwapSORParams,\n  SwapStableParams,\n} from \"../types/swap.type\";\nimport { EstSwapHandler } from \"./estSwapHandler\";\nimport { SOREstSwapHandler } from \"./SOREstSwapHandler\";\nimport { serializeSOR } from \"../helpers\";\n\nexport default class SwapModule {\n  protected _sdk: TappSDK;\n  constructor(sdk: TappSDK) {\n    this._sdk = sdk;\n  }\n\n  /**\n   * Creates a transaction payload for executing a swap on an AMM pool.\n   *\n   * @param params - An object containing:\n   * - `poolId`: The address of the pool in which the swap is performed.\n   * - `a2b`: Direction of the swap; `true` for token A to B, `false` for B to A.\n   * - `fixedAmountIn` (optional): Whether the input amount is fixed (defaults to `true`).\n   * - `amount0`: Amount of token A.\n   * - `amount1`: Amount of token B.\n   *\n   * @returns {InputEntryFunctionData} An object representing the transaction payload.\n   */\n  swapAMMTransactionPayload({\n    poolId,\n    a2b,\n    fixedAmountIn = true,\n    amount0,\n    amount1,\n  }: SwapAMMParams): InputEntryFunctionData {\n    const ser = new Serializer();\n\n    ser.serialize(AccountAddress.fromString(poolId));\n    ser.serializeBool(a2b);\n    ser.serializeBool(fixedAmountIn);\n    ser.serializeU64(amount0);\n    ser.serializeU64(amount1);\n\n    const payload: InputEntryFunctionData = {\n      function: `${this._sdk.sdkConfig.contractAddress}::router::swap`,\n      functionArguments: [ser.toUint8Array()],\n    };\n\n    return payload;\n  }\n\n  /**\n   * Creates a transaction payload for executing a swap on a CLMM (Concentrated Liquidity Market Maker) pool.\n   *\n   * @param params - An object containing:\n   * - `poolId`: The address of the CLMM pool.\n   * - `amountIn`: The input token amount for the swap.\n   * - `minAmountOut`: The minimum acceptable output amount (slippage protection).\n   * - `a2b`: Direction of the swap; `true` for token A to B, `false` for B to A.\n   * - `fixedAmountIn` (optional): Indicates whether `amountIn` is fixed (`true`) or calculated from `minAmountOut` (`false`). Defaults to `true`.\n   * - `targetSqrtPrice`: The target square root price to stop the swap at.\n   *\n   * @returns {InputEntryFunctionData} An object representing the transaction payload to be submitted.\n   */\n  swapCLMMTransactionPayload({\n    poolId,\n    amountIn,\n    minAmountOut,\n    a2b,\n    fixedAmountIn = true,\n    targetSqrtPrice,\n  }: SwapCLMMParams): InputEntryFunctionData {\n    const ser = new Serializer();\n\n    ser.serialize(AccountAddress.fromString(poolId));\n    ser.serializeBool(a2b);\n    ser.serializeBool(fixedAmountIn);\n    ser.serializeU64(amountIn);\n    ser.serializeU64(minAmountOut);\n    ser.serializeU128(targetSqrtPrice);\n\n    const payload: InputEntryFunctionData = {\n      function: `${this._sdk.sdkConfig.contractAddress}::router::swap`,\n      functionArguments: [ser.toUint8Array()],\n    };\n\n    return payload;\n  }\n\n  /**\n   * Creates a transaction payload for executing a swap on a Stable pool.\n   *\n   * @param params - An object containing:\n   * - `poolId`: The address of the Stable pool.\n   * - `tokenIn`: The index of the input token in the pool.\n   * - `tokenOut`: The index of the output token in the pool.\n   * - `amountIn`: The input token amount for the swap.\n   * - `minAmountOut`: The minimum acceptable output amount to protect against slippage.\n   *\n   * @returns {InputEntryFunctionData} An object representing the serialized transaction payload.\n   */\n  swapStableTransactionPayload({\n    poolId,\n    tokenIn,\n    tokenOut,\n    amountIn,\n    minAmountOut,\n  }: SwapStableParams): InputEntryFunctionData {\n    const ser = new Serializer();\n\n    ser.serialize(AccountAddress.fromString(poolId));\n    ser.serializeU64(tokenIn);\n    ser.serializeU64(tokenOut);\n    ser.serializeU256(amountIn);\n    ser.serializeU256(minAmountOut);\n\n    const payload: InputEntryFunctionData = {\n      function: `${this._sdk.sdkConfig.contractAddress}::router::swap`,\n      functionArguments: [ser.toUint8Array()],\n    };\n\n    return payload;\n  }\n\n  /**\n   * Estimates the swap output or required input amount for a given pool using the on-chain order book.\n   *\n   * @param params - An object containing:\n   * - `amount`: The amount for estimation (used as input or desired output depending on `field`).\n   * - `poolId`: The identifier of the pool.\n   * - `pair`: A tuple of token indexes to swap, e.g., `[0, 1]` means token at index 0 is being swapped for token at index 1.\n   * - `a2b`: Swap direction — `true` for token at `pair[0]` to `pair[1]`, `false` for `pair[1]` to `pair[0]`.\n   * - `field` (optional): Indicates if `amount` is an `\"input\"` or `\"output\"` amount (defaults to `\"input\"`).\n   *\n   * @returns {Promise<EstSwapResult>}.\n   *\n   * @throws Will throw an error if the order book is missing or malformed.\n   */\n  async getEstSwapAmount(params: GetEstSwapParams): Promise<EstSwapResult> {\n    const { amount, poolId, pair, a2b, field = \"input\" } = params;\n    const { result } = await this._sdk.request.post<\n      RequestResult<EstSwapBooks | null | undefined>\n    >(\"public/sc_est_swap\", {\n      poolId,\n      pair,\n    });\n\n    if (!result?.books || result.books.length != 2) {\n      throw new Error(\"Book structure is invalid\");\n    }\n\n    const { entries } = result.books[a2b ? 0 : 1];\n\n    return new EstSwapHandler(entries, field, amount).get();\n  }\n\n  /**\n   * Retrieves the pool route information between two tokens.\n   *\n   * @param tokenAddr0 - The address of the first token.\n   * @param tokenAddr1 - The address of the second token.\n   *\n   * @returns {Promise<PoolInfo>} object containing route details between the two tokens.\n   *\n   * @throws {ErrorNotFound} If no route is found between the given tokens.\n   */\n  async getRoute(tokenAddr0: string, tokenAddr1: string): Promise<PoolInfo> {\n    const res = await this._sdk.request.post<RequestResult<Nullable<PoolInfo>>>(\n      \"public/pool_info\",\n      {\n        tokenAddrs: [tokenAddr0, tokenAddr1],\n      }\n    );\n\n    if (!res.result) {\n      throw new ErrorNotFound(`Route not found. ${tokenAddr0} - ${tokenAddr1}`);\n    }\n\n    return res.result;\n  }\n\n  async getSOREstSwapAmount(\n    params: GetSOREstSwapParams\n  ): Promise<SOREstSwapResult> {\n    const { poolId, amount, fromAddr, toAddr, field = \"input\" } = params;\n    const { result } = await this._sdk.request.post<\n      RequestResult<SOROrderBook[] | null | undefined>\n    >(\"public/sc_est_swap2\", {\n      poolAddr: poolId,\n      pair: [fromAddr, toAddr],\n    });\n\n    const orderBook = (result ?? []).find(\n      (ob) => ob.fromAddr == fromAddr && ob.toAddr == toAddr\n    );\n\n    if (!orderBook) {\n      throw new ErrorNotFound(`Order book not found. ${fromAddr} - ${toAddr}`);\n    }\n\n    return new SOREstSwapHandler(orderBook, field, String(amount)).get();\n  }\n\n  swapSORTransactionPayload({\n    routeMatrix,\n    amounts,\n    slippage = 1,\n  }: SwapSORParams): InputEntryFunctionData {\n    const result = serializeSOR({\n      routeMatrix: routeMatrix,\n      amounts: amounts,\n      slippage: Number(slippage),\n    });\n\n    const data: InputEntryFunctionData = {\n      function: `${this._sdk.sdkConfig.sorContractAddress}::entry::execute_routes`,\n      functionArguments: [[...result]],\n    };\n\n    return data;\n  }\n}\n"],"mappings":"oKAAA,OACE,kBAAAA,EAEA,cAAAC,MACK,qBAoBP,IAAqBC,EAArB,KAAgC,CAE9B,YAAYC,EAAc,CACxB,KAAK,KAAOA,CACd,CAcA,0BAA0B,CACxB,OAAAC,EACA,IAAAC,EACA,cAAAC,EAAgB,GAChB,QAAAC,EACA,QAAAC,CACF,EAA0C,CACxC,IAAMC,EAAM,IAAIC,EAEhB,OAAAD,EAAI,UAAUE,EAAe,WAAWP,CAAM,CAAC,EAC/CK,EAAI,cAAcJ,CAAG,EACrBI,EAAI,cAAcH,CAAa,EAC/BG,EAAI,aAAaF,CAAO,EACxBE,EAAI,aAAaD,CAAO,EAEgB,CACtC,SAAU,GAAG,KAAK,KAAK,UAAU,eAAe,iBAChD,kBAAmB,CAACC,EAAI,aAAa,CAAC,CACxC,CAGF,CAeA,2BAA2B,CACzB,OAAAL,EACA,SAAAQ,EACA,aAAAC,EACA,IAA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,EAAoBC,EAAuC,CACxE,IAAMC,EAAM,MAAM,KAAK,KAAK,QAAQ,KAClC,mBACA,CACE,WAAY,CAACF,EAAYC,CAAU,CACrC,CACF,EAEA,GAAI,CAACC,EAAI,OACP,MAAM,IAAIC,EAAc,oBAAoBH,CAAU,MAAMC,CAAU,EAAE,EAG1E,OAAOC,EAAI,MACb,CAEA,MAAM,oBACJT,EAC2B,CAC3B,GAAM,CAAE,OAAAb,EAAQ,OAAAc,EAAQ,SAAAU,EAAU,OAAAC,EAAQ,MAAAT,EAAQ,OAAQ,EAAIH,EACxD,CAAE,OAAAI,CAAO,EAAI,MAAM,KAAK,KAAK,QAAQ,KAEzC,sBAAuB,CACvB,SAAUjB,EACV,KAAM,CAACwB,EAAUC,CAAM,CACzB,CAAC,EAEKC,GAAaT,GAAU,CAAC,GAAG,KAC9BU,GAAOA,EAAG,UAAYH,GAAYG,EAAG,QAAUF,CAClD,EAEA,GAAI,CAACC,EACH,MAAM,IAAIH,EAAc,yBAAyBC,CAAQ,MAAMC,CAAM,EAAE,EAGzE,OAAO,IAAIG,EAAkBF,EAAWV,EAAO,OAAOF,CAAM,CAAC,EAAE,IAAI,CACrE,CAEA,0BAA0B,CACxB,YAAAe,EACA,QAAAC,EACA,SAAAC,EAAW,CACb,EAA0C,CACxC,IAAMd,EAASe,EAAa,CAC1B,YAAaH,EACb,QAASC,EACT,SAAU,OAAOC,CAAQ,CAC3B,CAAC,EAOD,MALqC,CACnC,SAAU,GAAG,KAAK,KAAK,UAAU,kBAAkB,0BACnD,kBAAmB,CAAC,CAAC,GAAGd,CAAM,CAAC,CACjC,CAGF,CACF","names":["AccountAddress","Serializer","SwapModule","sdk","poolId","a2b","fixedAmountIn","amount0","amount1","ser","Serializer","AccountAddress","amountIn","minAmountOut","targetSqrtPrice","tokenIn","tokenOut","params","amount","pair","field","result","entries","EstSwapHandler","tokenAddr0","tokenAddr1","res","ErrorNotFound","fromAddr","toAddr","orderBook","ob","SOREstSwapHandler","routeMatrix","amounts","slippage","serializeSOR"]}