# Execute Swap

Perform token swaps through DLMM pairs using the bin-based liquidity system. Swaps traverse through multiple bins as needed to fill the order.

### Prerequisites

* Valid sender address with tokens
* Pair address for trading
* Sufficient balance of input token
* Gas for transaction execution

### Basic Swap

```typescript
const pair = await sdk.Pair.getPair(pairAddress);

// Swap 1 SUI for USDC
const tx = await sdk.Swap.prepareSwap(pair, {
  amount: 1000000000n,  // 1 SUI (9 decimals)
  xtoy: true,           // SUI (X) to USDC (Y)
  recipient: userAddress // Optional, defaults to sender
});

await sdk.fullClient.signAndExecuteTransaction({
  transaction: tx,
  signer: keypair
});
```

### Swap Parameters

```typescript
interface PrepareSwapParams {
  amount: bigint;        // Input token amount
  xtoy: boolean;         // Direction: true = X→Y, false = Y→X
  recipient?: string;    // Receiver address (optional)
}
```

### Swap Directions

#### X to Y Swap

```typescript
// Token X → Token Y
const swapXtoY = await sdk.Swap.prepareSwap(pair, {
  amount: inputAmount,
  xtoy: true
});
```

#### Y to X Swap

```typescript
// Token Y → Token X
const swapYtoX = await sdk.Swap.prepareSwap(pair, {
  amount: inputAmount,
  xtoy: false
});
```

### Understanding Token Order

```typescript
// Check pair token order
console.log("Token X:", pair.tokenXType); // e.g., "0x2::sui::SUI"
console.log("Token Y:", pair.tokenYType); // e.g., "0x...::usdc::USDC"

// X is always the "smaller" address
// SDK handles this automatically
```

### Complete Swap Example

```typescript
async function executeSwap(
  pairAddress: string,
  inputAmount: bigint,
  isXtoY: boolean
) {
  try {
    // Get pair info
    const pair = await sdk.Pair.getPair(pairAddress);
    
    // Prepare swap transaction
    const tx = await sdk.Swap.prepareSwap(pair, {
      amount: inputAmount,
      xtoy: isXtoY,
    });
    
    // Execute
    const result = await sdk.fullClient.signAndExecuteTransaction({
      transaction: tx,
      signer: keypair
    });
    
    console.log("Swap completed:", result.digest);
    return result;
    
  } catch (error) {
    console.error("Swap failed:", error);
    throw error;
  }
}
```

### Swap with Custom Recipient

```typescript
// Send output to different address
const tx = await sdk.Swap.prepareSwap(pair, {
  amount: swapAmount,
  xtoy: true,
  recipient: "0x456..." // Different wallet
});
```

### How Swaps Work

1. **Start at active bin**: Current trading price
2. **Consume liquidity**: Use available reserves
3. **Move to next bin**: If more needed
4. **Continue until filled**: Or liquidity exhausted

```
Before: [Bin-2][Bin-1][Active][Bin+1][Bin+2]
Swap:    →→→→→→→→→→→→→→→→→→→→→→→
After:  [Bin-2][Bin-1][Empty][Active][Bin+2]
```

### Common Patterns

#### Swap Exact Input

```typescript
// Know input amount, accept any output
const exactInput = 1000000000n; // 1 token

const tx = await sdk.Swap.prepareSwap(pair, {
  amount: exactInput,
  xtoy: true
});
```

#### Check Balance First

```typescript
// Verify sufficient balance
const balance = await getTokenBalance(userAddress, tokenType);

if (balance < swapAmount) {
  throw new Error("Insufficient balance");
}

const tx = await sdk.Swap.prepareSwap(pair, {
  amount: swapAmount,
  xtoy: true
});
```

### Error Handling

```typescript
try {
  const tx = await sdk.Swap.prepareSwap(pair, params);
  // Execute transaction
} catch (error) {
  if (error.message.includes("Invalid sender")) {
    console.error("Set sender address first");
  } else if (error.message.includes("Insufficient")) {
    console.error("Not enough input tokens");
  }
}
```

### Gas Optimization

* Swaps through fewer bins cost less gas
* Large swaps may traverse many bins
* Consider splitting very large swaps
* Active bin swaps are most efficient

### Related Topics

* [Swap Direction](/integration/dlmm/typescript-sdk/swap-operations/swap-direction.md) - Understanding X→Y vs Y→X
* [Calculate Swap Output](/integration/dlmm/typescript-sdk/swap-operations/calculate-swap-output.md) - Preview results
* [Price Impact](/integration/dlmm/typescript-sdk/swap-operations/price-impact.md) - Large swap effects
* [Slippage Protection](/integration/dlmm/typescript-sdk/swap-operations/slippage-protection.md) - Set minimum output


---

# 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/dlmm/typescript-sdk/swap-operations/execute-swap.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.
