Skip to main content

Execute a Swap

This guide performs a fixed(variable)-output(input) swap on Fuji, exchanging AUSD → CTK.

Prerequisite
  • Wallet client, AVAX gas, and AUSD balance from Getting Testnet Tokens
  • Your wallet must hold the APPROVED_SWAPPER role

Ensuring the wallet is whitelisted

Before spending gas, verify your address holds the APPROVED_SWAPPER role. If it does not, the swap will revert later.

To check wether the wallet is whitelisted, we'll call hasRole on the contract with the role identifier (APPROVED_SWAPPER ) and the wallet address.

async function isWhiteListed(
pair: `0x${string}`,
callerAddress: `0x${string}`,
) {
return await client.readContract({
address: pair,
abi: stableSwapAbi,
functionName: "hasRole",
args: ["APPROVED_SWAPPER", callerAddress],
});
}
Why?

AgoraStableSwapPair is permissioned, only approved wallets may call its swap functions.

Fetch token decimals

In order to calculate the swap amounts correctly, you need to know the decimal precision of both tokens in the pair. The AgoraStableSwapPair contract exposes the decimals for both tokens through getter functions:

async function getTokenDecimals(
client: PublicActions,
pairAddress: `0x${string}`,
) {
const [decimalsToken0, decimalsToken1] = await Promise.all([
client.readContract({
address: pairAddress,
abi: stableSwapAbi,
functionName: "token0Decimals",
args: [],
}),
client.readContract({
address: pairAddress,
abi: stableSwapAbi,
functionName: "token1Decimals",
args: [],
}),
]);

return { decimalsToken0, decimalsToken1 };
}

Define swapPath

swapPath tells the pair which direction you're swapping.

For an Agora pair (which always contains exactly two tokens) it must be:

  • [token0, token1] – swap token0 → token1
  • [token1, token0] – swap token1 → token0
Token order in the pair

AgoraStableSwapFactory deploys pairs with tokens sorted by address. Since AUSD's address has 6 leading zeros (0x00000000eFE302BEAA2b3e6e1b18d08D69a9012a), it will typically be token0 in most pairs. ::

Because you funded your wallet with AUSD earlier (see Get testnet ERC-20 tokens), we'll swap AUSD for CTK:

// token0 = AUSD, token1 = CTK on Fuji
const swapPath = [TOKEN0, TOKEN1] as const; // AUSD → CTK

// Need the opposite direction? Use:
// const swapPath = [TOKEN1, TOKEN0] as const; // CTK → AUSD

Once we have verified that the wallet is whitelisted we can proceed to swap. For swapping there are two high-level functions that abstract some of the low-level logic: