WDK logoWDK documentation

Execute Swaps

Run exact-input swaps, exact-output swaps, and swaps with ERC-4337 accounts.

This guide explains how to run a basic exact-input swap, an exact-output swap, and a swap from an ERC-4337 smart account. You should already have a VeloraProtocolEvm instance.

Swaps spend tokens and gas on-chain. Use amounts you control and an RPC you trust.

Basic exact-input swap

You can sell an exact amount of the input token using swap():

Exact input: USDT to WETH
const result = await swapProtocol.swap({
  tokenIn: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
  tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
  tokenInAmount: 1000000n
})

console.log('Swap transaction hash:', result.hash)
console.log('Total fee (wei):', result.fee)
console.log('Tokens sold (base units):', result.tokenInAmount)
console.log('Tokens bought (base units):', result.tokenOutAmount)

Exact output swap

You can receive an exact amount of the output token by passing tokenOutAmount to swap():

Exact output amount
const result = await swapProtocol.swap({
  tokenIn: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
  tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
  tokenOutAmount: 500000000000000000n
})

console.log('Swap hash:', result.hash)
console.log('Tokens sold (base units):', result.tokenInAmount)
console.log('Tokens bought (base units):', result.tokenOutAmount)

Swap with ERC-4337

You can perform a user-operation-backed swap by constructing VeloraProtocolEvm with WalletAccountEvmErc4337 and passing paymaster options to swap():

Swap with smart account and paymaster
import { WalletAccountEvmErc4337 } from '@tetherto/wdk-wallet-evm-erc-4337'
import VeloraProtocolEvm from '@tetherto/wdk-protocol-swap-velora-evm'

const aa = new WalletAccountEvmErc4337(seedPhrase, "0'/0/0", {
  chainId: 42161,
  provider: 'https://arb1.arbitrum.io/rpc',
  bundlerUrl: process.env.BUNDLER_URL,
  paymasterUrl: process.env.PAYMASTER_URL
})

const swapAA = new VeloraProtocolEvm(aa, { swapMaxFee: 200000000000000n })

const result = await swapAA.swap({
  tokenIn: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
  tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
  tokenInAmount: 1000000n
}, {
  paymasterToken: 'USDT',
  swapMaxFee: 200000000000000n
})

console.log('Swap hash:', result.hash)
console.log('Total fee (wei):', result.fee)

Token addresses must match the chain your account uses (for example, mainnet USD₮ addresses differ from Arbitrum).

Next Steps

On this page