Swapping Tokens
Build DeFi flows with approvals and swaps
Swapping Tokens
Swapping tokens often requires two steps: Approval and Execution. RISE Wallet supports batching these operations into a single atomic transaction when using EIP-5792 sendCalls, providing a much smoother UX.
SwapNo session key available!
FromBalance: 0
MockUSD
ToBalance: 0
MockToken
"use client";import { useAccount, useSendCalls } from "wagmi";import { encodeFunctionData, parseUnits } from "viem";export function SwapWidget() { const { sendCallsAsync } = useSendCalls(); const handleSwap = async () => { const amount = parseUnits("10", 18); // 1. Create Approval Call const approveData = encodeFunctionData({ abi: ERC20_ABI, functionName: "approve", args: [ROUTER_ADDRESS, amount], }); // 2. Create Swap Call const swapData = encodeFunctionData({ abi: ROUTER_ABI, functionName: "swapExactTokensForTokens", args: [amount, minOut, path, recipient, deadline], }); // 3. Execute Atomically (Batch) await sendCallsAsync({ calls: [ { to: TOKEN_ADDRESS, data: approveData }, { to: ROUTER_ADDRESS, data: swapData }, ], }); }; return ( <Button onClick={handleSwap}> Approve & Swap </Button> );}Atomic Batching
Instead of asking the user to sign an "Approve" transaction, wait for it to land, and then sign a "Swap" transaction, you can bundle them together.
const approveData = encodeFunctionData({
abi: ERC20_ABI,
functionName: "approve",
args: [ROUTER_ADDRESS, amount],
});
const swapData = encodeFunctionData({
abi: ROUTER_ABI,
functionName: "swapExactTokensForTokens",
args: [amount, minOut, path, recipient, deadline],
});
// Send both calls in one user operation
await sendCallsAsync({
calls: [
{ to: TOKEN_ADDRESS, data: approveData },
{ to: ROUTER_ADDRESS, data: swapData },
],
});This reduces the time users spend waiting and clicking popups, making DeFi feel instant.