2.4 Token Interactions and Transactions
Sending tokens from one address to another is the simplest thing you can do on a blockchain. It's also just the beginning.
The real power of tokens emerges when they interact with protocols, combine with other tokens, and execute complex operations in single transactions. A swap on Uniswap. A deposit into a lending pool. A flash loan that borrows millions, arbitrages across exchanges, and repays everything in one atomic transaction.
These aren't separate products built by separate companies requiring separate integrations. They're composable operations using standardized token interfaces. The same ERC-20 functions that enable basic transfers also power billion-dollar DeFi protocols.
"Understanding token interactions is the difference between holding crypto and actually using it. The mechanics covered in previous sections, state changes, approvals, gas costs, all come together here in practical operations you'll perform daily.
The Approval-Then-Execute Pattern
Most token interactions follow a two-step dance.
Step one: approve. You grant a smart contract permission to move your tokens. This creates an allowance entry in the token contract's storage. No tokens move yet.
Step two: execute. The protocol calls transferFrom() to pull your tokens into its contract. The operation you requested, whether a swap, deposit, or stake, happens atomically.
Why two steps? Security and control. Protocols can't touch your tokens without explicit permission. You decide exactly how much access to grant. The approval creates a ceiling. The protocol can only pull up to that amount.
Here's the trap: many dApps request unlimited approvals by default. The interface shows "Approve USDC" and buries the actual amount in fine print. That amount? Often the maximum possible value: 2^256-1 tokens. Effectively infinite.
Why do protocols do this? Convenience. Unlimited approval means you never need to approve again. Every future transaction skips step one. Gas savings add up. User experience improves.
The risk calculation changes entirely if that contract gets exploited. A limited approval for 1,000 USDC caps your exposure at 1,000 USDC. An unlimited approval exposes your entire balance. The Badger DAO attack in 2021 exploited exactly this pattern. Users who had granted unlimited approvals lost everything. Users with limited approvals lost only what they'd approved [1].
Some wallets now warn about unlimited approvals or let you modify the amount before signing. Take the extra step. Approve only what you need for that specific transaction.
Modern interfaces try to streamline this further. Permit signatures (EIP-2612) eliminate separate approval transactions entirely for supported tokens [2]. You sign an off-chain permit message, and the swap transaction includes this signature and handles approval atomically. One transaction instead of two. Supported tokens include USDC, DAI, and an expanding list.
Swapping: The Most Common Interaction
Token swaps happen millions of times daily. You have token A. You want token B. A decentralized exchange makes it happen.
Automated Market Makers (AMMs) like Uniswap don't use order books. They use liquidity pools. Each pool contains two tokens in a mathematical relationship. When you swap, you're trading against the pool itself, not another user [3].
The mechanics: You send token A to the pool. The pool calculates how much token B you receive based on its reserves and a pricing formula (typically x * y = k). You receive token B. The pool's ratio shifts, affecting prices for the next trader.
A simple swap on Uniswap v3 costs roughly 150,000-200,000 gas [4]. At $2 per unit of gas, that's $3-4 per trade. The same swap on Arbitrum might cost $0.10-0.30. On Solana, fractions of a penny.
These costs matter. A $100 swap with a $4 fee eats 4% of your value. The same swap for $10,000 costs the same $4 fee: 0.04%. Blockchain economics favor larger transactions.
Slippage adds another cost layer. Large swaps move prices against you. Request a $100,000 swap, and you might receive 0.5-2% less than the quoted rate. DEX aggregators like 1inch and Paraswap split large orders across multiple pools to minimize this impact [5].
Lending and Borrowing
DeFi lending protocols turn tokens into productive assets.
Supplying: Deposit tokens into a lending pool. The protocol gives you receipt tokens representing your share. Aave issues aTokens (aUSDC for USDC deposits). Compound issues cTokens [6]. These receipt tokens accrue interest automatically. Your aUSDC balance grows over time without any additional transactions.
Borrowing: Use deposited tokens as collateral to borrow other assets. Deposit $10,000 in ETH, borrow up to $7,500 in USDC (typical 75% loan-to-value ratio). Interest accrues on your debt. If your collateral value drops too far relative to your loan, liquidation kicks in.
Liquidation: When collateral ratios breach thresholds, anyone can repay part of your loan and claim discounted collateral. This protects lenders but penalizes borrowers. Liquidations are automated and ruthless. During the May 2021 crash, Aave processed over $660 million in liquidations in a single day [7].
The interaction flow:
Approve lending protocol to access your tokens
Call deposit function, receive receipt tokens
(Optional) Enable collateral, call borrow function
Receive borrowed tokens directly to your wallet
Each step costs gas. A full deposit-and-borrow sequence might run 300,000-500,000 gas on Ethereum mainnet.
Staking and Yield Generation
Staking locks tokens to earn rewards. The mechanics vary by protocol, but the pattern repeats.
Protocol staking: Lock tokens to help secure a network or participate in governance. Ethereum staking requires 32 ETH locked in a validator contract. Rewards come from network fees and new issuance. Current yields hover around 3-4% annually [8].
Liquidity provision: Deposit token pairs into DEX pools. Earn trading fees when others swap through your liquidity. Uniswap LPs earn 0.3% of each trade proportional to their pool share. High-volume pools generate meaningful returns. Low-volume pools don't [9].
Yield farming: Move tokens between protocols chasing the highest returns. Deposit into Aave, stake the aTokens in another protocol, stake those receipt tokens elsewhere. Each layer adds yield. Each layer adds risk and gas costs.
The staking interaction pattern:
Approve staking contract
Call stake function with token amount
Receive staking receipt or position NFT
Claim rewards periodically (costs gas each time)
Unstake when ready (often with time delays)
Some protocols auto-compound rewards. Others require manual claiming. The difference affects both returns and gas efficiency.
Transaction Finality
The transaction lifecycle covered in Section 2.1 applies to all token interactions. What varies across networks is finality, how long until your transaction becomes irreversible.
One confirmation means one block. But one block can theoretically be reorganized. Most platforms wait for multiple confirmations. Ethereum typically considers 12-32 confirmations final. Exchanges often require more [10].
Time from click to finality: 15 seconds to several minutes on Ethereum. 400 milliseconds on Solana. Hours on Bitcoin. The network you choose affects your experience dramatically.
When Transactions Fail
Transactions fail. Understanding why saves money and frustration.
Insufficient gas: You set a gas limit too low for the operation's complexity. The transaction runs out of fuel mid-execution. Result: all state changes revert, but you still pay for the gas consumed. You lose money and accomplish nothing.
Reverted execution: The smart contract's logic rejected your transaction. Maybe you tried to swap with too much slippage. Maybe the token you're selling charges a fee your settings didn't account for. Maybe the liquidity pool's state changed between your transaction submission and execution. The transaction fails, gas still consumed.
Nonce errors: Transactions from each address must execute in order, numbered by nonce. Submit transaction #5 before #4 confirms, and #5 waits forever. Stuck transactions can block all subsequent activity from that address.
Out of gas for the network: You set a gas price too low during congestion. Your transaction sits in the mempool, ignored by validators seeking higher fees. It eventually drops or you manually cancel it.
Cancellation requires submitting a new transaction with the same nonce but higher gas. You're paying to replace your stuck transaction with one that does nothing.
Failed transactions on Ethereum mainnet commonly cost $1-10 in wasted gas. Some wallets now simulate transactions before submission, catching many failures before they cost real money [11].
Batching and Transaction Efficiency
Smart users combine operations to minimize gas costs.
Multicall contracts: Execute multiple operations in a single transaction. Claim rewards from three protocols, swap the tokens, and deposit the result. One transaction instead of five. Uniswap, Aave, and most major protocols support multicall patterns [12].
Permit signatures: EIP-2612 allows approvals through signatures rather than transactions [13]. Instead of an approval transaction followed by a swap transaction, you sign an off-chain permit message. The swap transaction includes this signature and handles approval atomically. One transaction instead of two.
Account abstraction wallets: ERC-4337 wallets can batch arbitrary operations. Approve five tokens, swap three pairs, stake the results. One transaction. One signature. Gas sponsored by the dApp or paid in any token [14].
Batching becomes more valuable as base gas costs rise. Saving one transaction at $0.10 each on L2 barely matters. Saving one transaction at $10 each on Ethereum mainnet adds up fast.
MEV: The Hidden Cost of Transactions
Your pending transaction is visible to everyone. Some people profit from this.
Maximal Extractable Value (MEV) refers to profit validators and searchers can extract by reordering, inserting, or censoring transactions within blocks they produce. It affects almost every token interaction [15].
Sandwich attacks: You submit a large swap. A bot sees it in the mempool. The bot front-runs you with its own swap, moving the price against you. Your swap executes at the worse price. The bot back-runs with a reverse swap, pocketing the difference. You received less than you should have.
Arbitrage: Price differences between exchanges create opportunities. Bots monitor for swaps that will create imbalances, then immediately arbitrage the difference. Unlike sandwich attacks, arbitrage MEV serves a legitimate market function. It keeps prices aligned across venues and improves overall market efficiency.
Liquidation racing: When positions become liquidatable, bots compete to execute the liquidation first. The winner claims the liquidation bonus. Fast liquidations protect lending protocols from bad debt, keeping them solvent for all users.
MEV extraction on Ethereum exceeded $600 million in 2023 alone [16]. Individual users rarely see the impact directly. It appears as slightly worse swap rates, slightly higher slippage, slightly less favorable execution.
Protection strategies exist. Private mempools like Flashbots Protect hide your transaction from public view until inclusion [17]. MEV-aware aggregators like CoW Swap use batch auctions that resist front-running [18]. Slippage limits cap how much price impact you'll accept.
Cross-Chain Transactions
Tokens on Ethereum can't natively interact with tokens on Solana. Bridges solve this.
Lock and mint: Deposit tokens into a bridge contract on the source chain. The bridge mints equivalent "wrapped" tokens on the destination chain. Your ETH on Ethereum becomes WETH on Arbitrum or wrapped ETH on Solana.
Burn and release: Going back, you burn the wrapped tokens. The bridge releases your original tokens from its locked reserves.
The interaction feels simple. Click, wait, receive. But bridge transactions involve multiple chains, multiple confirmation periods, and multiple trust assumptions.
Every bridge relies on some trust assumption. Validator bridges trust a committee of signers to honestly attest to cross-chain state. Light client bridges trust that the source chain's consensus remains secure. Smart contract bridges trust that the code has no exploitable bugs. Even the most decentralized bridge designs concentrate risk in ways that single-chain transactions don't.
Bridge exploits have cost over $1 billion collectively. The Ronin bridge lost $625 million when attackers compromised five of nine validator keys [19]. Wormhole's smart contract had a signature verification bug that cost $320 million [20]. Each exploited different vulnerabilities, but all demonstrated that bridges concentrate risk.
Before using any bridge, understand its security model. How many validators or signers? What's the threshold for moving funds? Has the contract been audited? How long has it operated without incident?
Bridge wait times vary enormously. Optimistic rollup withdrawals to Ethereum take 7 days [21]. ZK rollup withdrawals complete in hours. Same-ecosystem bridges (Ethereum to Arbitrum) finish in minutes.
Transaction Privacy Considerations
Every token interaction creates permanent, public records.
Your address, visible on every transaction, links to your entire on-chain history. Bought tokens from a centralized exchange? That exchange knows your address connects to your identity. Every subsequent transaction is traceable.
Address rotation: Use fresh addresses for different purposes. One for DeFi. One for NFTs. One for each exchange relationship. More addresses mean more fragmented history.
But address rotation alone provides limited protection. Chain analysis firms like Chainalysis specialize in linking addresses through transaction patterns [22]. Send tokens from your exchange withdrawal address to your "private" DeFi address? Now they're linked. Use similar amounts or interact with the same protocols at similar times? Statistical correlation builds.
Mixing services: Protocols like Tornado Cash mixed tokens to break transaction chains. Regulatory crackdowns have made these services legally risky in many jurisdictions [23]. The OFAC sanctions on Tornado Cash in 2022 demonstrated that privacy tools face significant legal pressure.
Privacy-focused chains: Zcash, Monero, and others offer native transaction privacy. But moving between these chains and public blockchains creates linkable events at the bridges.
Layer 2 privacy: Some L2s explore privacy features. Aztec Network provides private transactions on Ethereum. Adoption remains limited but growing [24].
Complete privacy on public blockchains remains difficult. Every interaction leaves traces.
Practical Transaction Patterns
Experience teaches common patterns for efficient token interactions.
Check before you act: Simulate transactions when possible. Tenderly, wallet simulations, and protocol preview features show what will happen before you commit gas [25].
Time your transactions: Gas prices fluctuate by time of day and day of week. Weekends and early morning (US time) typically see lower fees.
Set appropriate limits: Slippage tolerance affects both success rate and execution quality. Too tight (0.1%) and transactions fail frequently. Too loose (5%) and you accept poor execution. 0.5-1% works for most stable pairs. Volatile tokens need wider tolerance.
Verify contracts: Before interacting with any protocol, verify you're using the correct contract address. Bookmark official sites. Check addresses against block explorers.
Plan withdrawal paths: Before depositing into any protocol, understand how to exit. What's the withdrawal process? Any time locks? Any fees? Getting in is always easier than getting out.
The Complete Token Interaction Stack
Every section in this chapter connects.
Tokens exist as ledger entries (2.1). Smart contracts create and govern them (2.2). Wallets provide key management for controlling them (2.3). And transactions, the focus of this section, are how you actually use them.
A single Uniswap swap demonstrates the full stack:
Ledger state changes when your balance decreases and increases
Smart contract logic determines swap math and executes the trade
Your wallet signs the transaction with your private key
The transaction propagates, executes, and confirms
Your wallet queries the new state and displays updated balances
Understanding each layer turns confusion into clarity. When a transaction fails, you can diagnose why. When gas costs spike, you know how to respond. When a new protocol launches, you understand what it's actually doing with your tokens.
The foundation is set. Part II explores what makes different token types, fungible, non-fungible, governance, utility, and others, distinct from each other and suited for different purposes.
References
[1] BadgerDAO Exploit Analysis - https://rekt.news/badger-rekt/
[2] EIP-2612: Permit Extension for ERC-20 - https://eips.ethereum.org/EIPS/eip-2612
[3] How do Uniswap v3 Liquidity Pools and Swaps Work? - https://uniswapv3book.com/milestone_1/introduction.html
[4] Uniswap Gas Benchmark - https://docs.uniswap.org/concepts/protocol/integration-considerations
[5] 1inch Aggregation Protocol - https://docs.1inch.io/docs/aggregation-protocol/introduction
[6] Aave aTokens - https://docs.aave.com/developers/tokens/atoken
[7] Aave Liquidations Dashboard - https://dune.com/queries/4966/9748
[8] Ethereum Staking Rewards - https://ethereum.org/en/staking/
[9] Uniswap Fee Structure - https://docs.uniswap.org/concepts/protocol/fees
[10] Ethereum Finality - https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/#finality
[11] Transaction Simulation - https://docs.tenderly.co/simulations
[12] Uniswap Multicall - https://docs.uniswap.org/contracts/v3/reference/periphery/base/Multicall
[13] Permit2 - https://docs.uniswap.org/contracts/permit2/overview
[14] ERC-4337 Account Abstraction - https://eips.ethereum.org/EIPS/eip-4337
[15] Flashbots MEV Research - https://writings.flashbots.net/
[16] MEV-Explore - https://explore.flashbots.net/
[17] Flashbots Protect - https://docs.flashbots.net/flashbots-protect/overview
[18] CoW Protocol - https://docs.cow.fi/
[19] Ronin Bridge Hack - https://roninblockchain.substack.com/p/community-alert-ronin-validators
[20] Wormhole Exploit - https://rekt.news/wormhole-rekt/
[21] Optimism Withdrawal Period - https://docs.optimism.io/builders/app-developers/bridging/messaging
[22] Chainalysis Blockchain Analysis - https://www.chainalysis.com/
[23] OFAC Tornado Cash Sanctions - https://home.treasury.gov/news/press-releases/jy0916
[24] Aztec Network - https://aztec.network/
[25] Tenderly Transaction Simulator - https://tenderly.co/transaction-simulator
Last updated