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. Before execution, approve the input token for the current Velora spender on the account's chain. The module does not submit approvals or reset allowances. See configuration for approval and fee prerequisites.
Basic exact-input swap
You can sell an exact amount of the input token using swap():
const result = await swapProtocol.swap({
tokenIn: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
tokenInAmount: 1000000n
})
console.log('Swap transaction hash:', result.hash)
console.log('Total fee (account units):', 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():
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():
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: 1,
provider: 'https://ethereum-rpc.publicnode.com',
bundlerUrl: process.env.BUNDLER_URL,
paymasterUrl: process.env.PAYMASTER_URL,
paymasterAddress: process.env.PAYMASTER_ADDRESS,
safeModulesVersion: '0.3.0',
paymasterToken: {
address: '0xdAC17F958D2ee523a2206206994597C13D831ec7'
}
})
// Exclusive cap: 0.01 USDt with this six-decimal paymaster token.
const swapAA = new VeloraProtocolEvm(aa, { swapMaxFee: 10000n })
const result = await swapAA.swap({
tokenIn: '0xdAC17F958D2ee523a2206206994597C13D831ec7',
tokenOut: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
tokenInAmount: 1000000n
}, {
paymasterToken: {
address: '0xdAC17F958D2ee523a2206206994597C13D831ec7'
},
swapMaxFee: 10000n
})
console.log('Swap hash:', result.hash)
console.log('Total fee (USDt base units):', result.fee)Token addresses must match the chain your account uses (for example, Ethereum USD₮ and Arbitrum USD₮0 use different contract addresses).
Next Steps
- Get swap quotes before sending
- Handle errors
- Get started if you still need setup