> For a complete index of Agora Finance documentation, fetch https://docs.agora.finance/llms.txt

# Swapping - Fixed Input

> Execute a swap specifying an exact input amount and receiving a calculated output

> **Note**
>
> If you want to run this example, be sure that you have followed the steps [here](/instant-settlement/guides/quick-start#setting-up-a-viem-wallet-client) to configure your Wallet Client.

[`SwapExactTokensForTokens`](/instant-settlement/smart-contracts/pair-contract#swapexacttokensfortokens) - Provide a fixed number of tokens you want to swap and receive the number of tokens that would result from that swap.
You'll still get a quote before executing the swap to ensure you agree with the variable output amount.

## Calculate the exact input (`amountIn`)

For the **fixed-input** flow we pick how much **`AUSD`** we're willing to spend and convert that to raw units with the token's decimals.
We'll be using the [getTokenDecimal function](/instant-settlement/guides/executing-swap#fetch-token-decimals) to do this.
It's also important to remember our [`swapPath`](/instant-settlement/guides/executing-swap#define-a-swappath) example showing that AUSD is token1 in the pair.

```tsx
  const { decimalsToken0, decimalsToken1 } = await getTokenDecimals(
    client,
    testnetPair,
  );
  // We define the exact amount of tokens that we would like to provide (in token1 Units)
  const amountIn = 1000n * 10n ** BigInt(decimalsToken1);
  console.log("Desired amount In ", amountIn);

```

```tsx
Desired amountIn (raw AUSD): 1000000000n
```

> **Why?**
>
> [`swapExactTokensForTokens`](/instant-settlement/smart-contracts/pair-contract#swapexacttokensfortokens) will debit precisely this amount of AUSD; the CTK you receive can only go **up** from the quote you accept next.

## Getting the quote for `AmountOutMin`

Now that we've defined the `amountIn`, we can get a quote from the pair to know how much **CTK (token0)** you'll get.
Furthermore we'll actually use the `swapPath` defined [here](/instant-settlement/guides/executing-swap#define-a-swappath) to execute this function.

```tsx
/**
 * Quote how much token0 is output for a fixed token1 input
 * Returns `[amountIn, amountOutMin]`
 */
async function getQuoteForAmountOut(
  pair: `0x${string}`,
  amountIn: bigint,
  swapPath: `0x${string}`[],
) {
  return await client.readContract({
    address: pair,
    abi: instantSettlementAbi,
    functionName: "getAmountsOut",
    args: [amountIn, swapPath],
  });
}
```

```tsx
const [, amountOutMin] = await getQuoteForAmountOut(
  TESTNET_PAIR_AUSD_CTK,
  amountIn,
  swapPath,
);
console.log("Quoted amountOutMin (raw CTK):", amountOutMin);

```

```tsx
Quoted amountOutMin (raw CTK): 999800000000000000000n
```

**Interpretation:**

* `1000 AUSD` will return **→ `999.8 CTK`** at the current price (fee included).

  You'll pass this value as a **floor**; if the final output is lower the swap reverts with [`InsufficientOutputAmount`](/instant-settlement/smart-contracts/pair-contract#errors) error message.

## Approve the allowance

[`AgoraStableSwapPair`](/instant-settlement/smart-contracts/pair-contract) cannot pull AUSD from your wallet unless the ERC-20 allowance is set.
This means we need to grant the pair permission to spend up to `amountIn` AUSD, and—as a best-practice—simulate the transaction before broadcasting it:

```tsx
/*
 * Give `pair` permission to spend `amount` of `tokenToApprove`.
 * Returns the transaction hash of the on-chain approval.
 */
async function approveAllowance(
  tokenToApprove: `0x${string}`,
  pair: `0x${string}`,
  amount: bigint,
) {
  // 1) Dry-run to catch reverts & obtain gas estimate
  const { request } = await client.simulateContract({
    address: tokenToApprove,
    abi: ausdImplementationAbi, // standard ERC-20 ABI
    functionName: "approve",
    args: [pair, amount],
  });

  // 2) Send the real transaction
  return await client.writeContract(request);
}
```

```tsx
   // Step 4. ─ approve AUSD allowance
  console.log(`Approving pair to spend ${amountIn} units of AUSD...`);
  const approveAllowanceTxHash = await approveAllowance(
    swapPath[0],
    TESTNET_PAIR_AUSD_CTK,
    amountIn,
  );
  console.log("Approve transaction hash:", approveAllowanceTxHash);

```

```tsx
Approving pair to spend 1000000000 units of AUSD..
Approve transaction hash: 0x360753e44c0be192cf633a9888c5cb31dc0a599c49197d7e969150d2f8f9824f
```

## Swapping tokens

With allowance set, we trigger the atomic swap. The swap call will use [`swapExactTokensForTokens`](/instant-settlement/smart-contracts/pair-contract#swapexacttokensfortokens), and it will take the following args:

| Arg             | Meaning                                                                              |
| --------------- | ------------------------------------------------------------------------------------ |
| `amountIn`      | Amount to be debited from your wallet (`1 000 AUSD` raw)                             |
| `amountOutMin`  | Minimum CTK you'll accept (`999.8 CTK` raw)                                          |
| `swapPath`      | Addresses of the tokens to swap: `[0xa90...22dC,0x7BE...cd9D]` (AUSD/CTK on Sepolia) |
| `callerAddress` | Wallet that will receive the CTK                                                     |
| `deadline`      | Time allowance before the transaction reverts (**+5 min** in this example)           |

```tsx
// Step 5. Execute the swap.
// Set a deadline for the swap (e.g. current time + 300 seconds)
const deadline = BigInt(Math.floor(Date.now() / 1000) + 300);

console.log("Executing swapExactTokensForTokens...");
const { request: swapRequest } = await client.simulateContract({
  address: TESTNET_PAIR_AUSD_CTK,
  abi: instantSettlementAbi,
  functionName: "swapExactTokensForTokens",
  args: [amountIn, amountOutMin, swapPath, callerAddress, BigInt(deadline)],
});
const swapRequestTxHash = await client.writeContract(swapRequest);
console.log("Swap transaction hash:", swapRequestTxHash);
```

```tsx
Executing swapExactTokensForTokens...
Swap transaction hash: 0x5693db026af155e5ce9a6678d2e0aa27ba62a0b15e91979b6bcd1c3731f7151c
```

If you want, you can choose to open the [Sepolia Explorer](https://sepolia.etherscan.io) and wait for it to process.
No matter what, if the transaction is successfully executed, we can expect to have `999.8 token0(CTK)` in the destination wallet's balance.

For the full example, please refer to [our examples repository](https://github.com/agora-finance/stable-swap-examples/blob/main/src/swapExactTokensForTokens.ts)