# PreSwap

### Quick Start

```typescript
// Simulate swap before execution
const pool = await sdk.Pool.getPool(poolId)

const preSwapResult = await sdk.Swap.preswap({
  pool: pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,  // SUI decimals
  decimalsB: 6,  // USDC decimals
  a2b: true,     // SUI -> USDC
  byAmountIn: true,
  amount: '1000000000',  // 1 SUI
  currentSqrtPrice: pool.current_sqrt_price
})

console.log({
  amountIn: preSwapResult.estimatedAmountIn,
  amountOut: preSwapResult.estimatedAmountOut,
  fee: preSwapResult.estimatedFeeAmount,
  priceAfter: preSwapResult.estimatedEndSqrtPrice
})
```

### PreSwap Methods

#### Single Pool PreSwap

```typescript
const params = {
  pool: pool,
  coinTypeA: '0x2::sui::SUI',
  coinTypeB: '0x...::usdc::USDC',
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,           // Direction: A to B
  byAmountIn: true,    // Fix input amount
  amount: '1000000000',
  currentSqrtPrice: pool.current_sqrt_price
}

const result = await sdk.Swap.preswap(params)

if (result.isExceed) {
  console.log('Swap exceeds pool liquidity')
}
```

#### Multi-Pool PreSwap

Find best pool for swap:

```typescript
const pools = ['0xpool1...', '0xpool2...', '0xpool3...']

const result = await sdk.Swap.preSwapWithMultiPool({
  poolAddresses: pools,
  coinTypeA: '0x2::sui::SUI',
  coinTypeB: '0x...::usdc::USDC',
  a2b: true,
  byAmountIn: true,
  amount: '1000000000'
})

console.log('Best pool:', result.poolAddress)
console.log('Best output:', result.estimatedAmountOut)
```

### Calculate Price Impact

```typescript
// Local calculation with tick data
const ticks = await sdk.Pool.fetchTicks({
  pool_id: poolId,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB
})

const rateResult = sdk.Swap.calculateRates({
  currentPool: pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,
  byAmountIn: true,
  amount: new BN('1000000000'),
  swapTicks: ticks
})

console.log({
  priceImpact: rateResult.priceImpactPct.toFixed(2) + '%',
  isExceed: rateResult.isExceed,
  extraGas: rateResult.extraComputeLimit
})
```

### Response Types

```typescript
interface PreSwapResult {
  poolAddress: string
  estimatedAmountIn: string
  estimatedAmountOut: string
  estimatedEndSqrtPrice: string
  estimatedFeeAmount: string
  isExceed: boolean        // Exceeds liquidity
  amount: string
  aToB: boolean
  byAmountIn: boolean
}

interface CalculateRatesResult {
  estimatedAmountIn: BN
  estimatedAmountOut: BN
  estimatedEndSqrtPrice: BN
  estimatedFeeAmount: BN
  isExceed: boolean
  extraComputeLimit: number
  priceImpactPct: number
}
```

### Usage Examples

#### Check Slippage

```typescript
// 1. PreSwap to get expected output
const preSwap = await sdk.Swap.preswap(params)

// 2. Calculate minimum output with 1% slippage
const expectedOut = new BN(preSwap.estimatedAmountOut)
const minOutput = expectedOut.mul(new BN(99)).div(new BN(100))

console.log({
  expected: expectedOut.toString(),
  minimum: minOutput.toString()
})
```

#### Compare Pools

```typescript
const pools = await sdk.Pool.getPools()
const suiUsdcPools = pools.filter(p => 
  p.coinTypeA.includes('sui') && 
  p.coinTypeB.includes('usdc')
)

// Test each pool
const results = []
for (const pool of suiUsdcPools) {
  const result = await sdk.Swap.preswap({
    pool,
    coinTypeA: pool.coinTypeA,
    coinTypeB: pool.coinTypeB,
    decimalsA: 9,
    decimalsB: 6,
    a2b: true,
    byAmountIn: true,
    amount: '1000000000',
    currentSqrtPrice: pool.current_sqrt_price
  })
  
  if (!result.isExceed) {
    results.push({
      pool: pool.poolAddress,
      output: result.estimatedAmountOut,
      fee: result.estimatedFeeAmount
    })
  }
}

// Find best rate
const best = results.sort((a, b) => 
  Number(b.output) - Number(a.output)
)[0]
```

#### Fix Output Amount

```typescript
// Want exactly 1000 USDC output
const params = {
  pool,
  coinTypeA: pool.coinTypeA,
  coinTypeB: pool.coinTypeB,
  decimalsA: 9,
  decimalsB: 6,
  a2b: true,
  byAmountIn: false,    // Fix output
  amount: '1000000000', // 1000 USDC
  currentSqrtPrice: pool.current_sqrt_price
}

const result = await sdk.Swap.preswap(params)
console.log('Need SUI:', result.estimatedAmountIn)
```

### Important Notes

* PreSwap uses simulation for accurate results
* Multi-pool automatically finds best execution
* `isExceed` indicates insufficient liquidity
* Always check price impact before large swaps
* Results include fees in calculations


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ferra.ag/integration/clmm/typescript-sdk/preswap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
