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

# Swapping - Fixed Output

> Execute a swap specifying an exact output amount with the input calculated automatically

> **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.

[`SwapTokensForExactTokens`](/instant-settlement/smart-contracts/pair-contract#swaptokensforexacttokens) - Provide a the number of tokens you want your swap to result in and receive the number of tokens you need to send.
You'll get a quote before executing the swap to ensure you agree with the variable input amount

## Calculate the desired output (`AmountOut`)

For the **fixed-output** flow we pick how much CTK we want to receive and convert that to raw units with the token’s decimals.
We'll again be using the [getTokenDecimal function](/instant-settlement/guides/executing-swap#fetch-token-decimals) function 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 amount of tokens that we would like to get out (in token1 units)
const amountOut = 1000n * 10n ** BigInt(decimalsToken0);
console.log("Desired amount Out ", amountOut);
```

```tsx
Desired amount Out  1000000000000000000000n
```

> **Why?**
>
> [`swapTokensForExactTokens`](/instant-settlement/smart-contracts/pair-contract#swaptokensforexacttokens) guarantees you receive a fixed amount of `CTK` (token0) units. The contract will calculate how much `AUSD` (token1) it needs in order to guarantee that amount.

## Getting a quote for `AmountIn`

Get a quote from the pair for how much AUSD it would require (including the current purchase fee) to receive the fixed `amountOut` that was configured.

```tsx
/**
 * Quote how much token1 is required to guarantee the specificed token0 amount as an output.
 * Returns `[amountInMax, amountOut]`
 */
async function quoteAmountsIn(
  pair: `0x${string}`,
  amountOut: bigint,
  path: `0x${string}`[],
) {
  return await client.readContract({
    address: pair,
    abi: instantSettlementAbi,
    functionName: 'getAmountsIn',
    args: [amountOut, path],
  });
}
```

```tsx
const [amountInMax, amountOut] = await quoteAmountsIn(
  PAIR_CTK_AUSD,
  amountOut,
  [TOKEN0_CTK, TOKEN1_AUSD],
);

console.log('Quoted amountInMax (raw AUSD):', amountInMax)
```

```tsx
Quoted amountInMax (raw AUSD): 1000200000
```

This output means the pair will charge `1000.20 AUSD`, which already includes any fees. If you agree with this quote, the next step is to **approve the pair** to spend up to `amountInMax` AUSD before submitting the swap.

## 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 that we need to grant the pair permission to spend up to `amountInMax` 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
console.log(
  `Approving contract ${TESTNET_PAIR_AUSD_CTK} to spend ${amountInMax} units of token ${inputTokenAddress}...`,
);
const approveAllowanceTxHash = await approveAllowance(
  inputTokenAddress,
  TESTNET_PAIR_AUSD_CTK,
  amountInMax,
);
console.log("Approve transaction hash:", approveAllowanceTxHash);

```

```tsx
Approving pair to spend 1000200000 units of AUSD...
Approve transaction hash: 0x1d166bbc9ce4e0ba3000a42aa22360c14cb8a8ba8007d137915a3922e304e0f4
```

## Swapping tokens

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

| Arg             | Meaning                                                                              |
| --------------- | ------------------------------------------------------------------------------------ |
| `amountOut`     | Amount guaranteed to receive (`1000 CTK` raw)                                        |
| `amountInMax`   | The ceiling of AUSD you're willing to pay                                            |
| `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
console.log("Executing swapTokensForExactTokens...");
const { request: swapRequest } = await client.simulateContract({
  address: TESTNET_PAIR_AUSD_CTK,
  abi: instantSettlementAbi,
  functionName: "swapTokensForExactTokens",
  args: [amountOut, amountInMax, swapPath, callerAddress, BigInt(deadline)],
});
const swapRequestTxHash = await client.writeContract(swapRequest);
console.log("Swap transaction hash:", swapRequestTxHash);

```

```tsx
Executing swapTokensForExactTokens...
Swap transaction hash: 0x5d27ab73a4759720aedd71b32075366a427c8ce21220cd9910b6352715550c3a
```

If you want, you can choose to open the returned hash on the [Sepolia Explorer](https://sepolia.etherscan.io) and wait for it to process.
No matter what, if the transaction is successfully executed, the destination wallet balance should show `+1000 CTK`, and no more than `1000.20 AUSD` was spent.

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