Execution Flow for EVM DeFi Swaps via Uniswap V3 and 1inch in CloddsBot
CloddsBot processes EVM DeFi swaps through a structured pipeline that compares Uniswap V3 and 1inch quotes via compareDexRoutes, then executes the optimal route using executeUniswapSwap or executeOneInchSwap while handling token resolution and security validation automatically.
The CloddsBot repository provides a modular TypeScript framework for executing cross-chain DeFi operations. Understanding the execution flow for EVM DeFi swaps via Uniswap V3 and 1inch in CloddsBot reveals how the system intelligently routes transactions through the most cost-effective liquidity sources while maintaining robust safety checks across supported EVM networks.
Overview of the Swap Execution Architecture
The swap execution system follows a modular pipeline architecture that separates concerns between command parsing, price discovery, transaction construction, and security validation. At the core, src/skills/executor.ts serves as the primary entry point, while src/agents/index.ts coordinates the high-level dispatch logic. The system supports three operational modes: forced Uniswap V3 routing, forced 1inch routing, or automatic selection based on real-time quote comparison.
Step-by-Step Execution Flow
Command Entry via the Executor Skill
All swap requests originate in src/skills/executor.ts, which validates incoming payloads containing the target chain, input token, output token, amount, and optional DEX preference. The executor accepts a dex parameter that can be set to 'uniswap', '1inch', or 'auto'. When the parameter is omitted or set to 'auto', the system triggers the route comparison logic to determine the optimal execution path.
Route Comparison and DEX Selection
When operating in automatic mode, the executor imports the comparison utilities from src/evm/oneinch.ts and invokes compareDexRoutes. This function concurrently queries both liquidity sources by calling getUniswapQuote from src/evm/uniswap.ts and getOneInchQuote from src/evm/oneinch.ts. The comparison evaluates output amounts, gas costs, and slippage tolerances to select the best available route, logging the decision rationale before proceeding to execution.
Token Address Resolution
Before fetching quotes, both DEX modules normalize token symbols into contract addresses. The Uniswap implementation uses resolveToken in src/evm/uniswap.ts, while the 1inch module relies on resolveTokenAddress in src/evm/oneinch.ts. These helpers map common symbols like USDC, ETH, or DAI to their chain-specific contract addresses, falling back to raw address strings when provided directly by the caller.
Quote Retrieval Mechanisms
The system implements distinct quoting strategies for each DEX to ensure accurate price discovery:
-
Uniswap V3: The
getUniswapQuotefunction builds static calls to the Universal Router quoter for each standard fee tier (0.05%, 0.3%, and 1%). It selects the tier offering the highest output amount, calculates the slippage-adjusted minimum output based on user-defined basis points, and returns a structuredUniswapQuoteobject containing the optimal route parameters. -
1inch: The
getOneInchQuotefunction queries the 1inch Aggregation Protocol API at the/quoteendpoint. It passes the resolved token addresses and amount, processes the returned data to identify which liquidity sources contribute to the route, and computes the minimum acceptable output after applying the specified slippage tolerance.
Swap Execution Functions
Once the DEX selection is finalized, the executor delegates to the appropriate swap implementation:
-
executeUniswapSwap: Located insrc/evm/uniswap.ts, this function refreshes the quote to ensure price freshness, checks and approves token allowances for the Universal Router if necessary, assembles theexactInputSinglecalldata with a gas-limit buffer, submits the transaction to the network, and returns aUniswapSwapResultcontaining the transaction hash and executed output amount. -
executeOneInchSwap: Found insrc/evm/oneinch.ts, this routine first ensures token approval for the 1inch router via the/approve/spenderendpoint, then requests the full transaction data from the/swapendpoint. It forwards the constructed transaction to the wallet provider, monitors the submission, and returns aOneInchSwapResultwith transaction details and receipt confirmation.
Security Validation and Result Propagation
Before any transaction reaches the mempool, the system passes parameters through src/security/tx-validator.ts and src/security/shield.ts. These modules enforce gas-price caps, validate against known scam address databases, and inspect transaction calldata for suspicious patterns. After successful execution, the executor formats a response containing the transaction hash, routed DEX identifier, and actual output amount, propagating this result back to the originating chat interface or webhook.
Code Implementation Examples
The following examples demonstrate the practical implementation patterns for initiating swaps through the CloddsBot execution pipeline.
Automatic DEX Selection and Execution
// Implementation pattern from src/skills/executor.ts
const dex = args.dex ?? 'auto';
if (dex === 'auto') {
const { compareDexRoutes, executeUniswapSwap, executeOneInchSwap } = await import('../evm');
const comparison = await compareDexRoutes({
chain: args.chain,
fromToken: args.input,
toToken: args.output,
amount: args.amount,
});
if (comparison.best === 'uniswap') {
const result = await executeUniswapSwap({
chain: args.chain,
inputToken: args.input,
outputToken: args.output,
amount: args.amount,
});
return result;
} else {
const result = await executeOneInchSwap({
chain: args.chain,
fromToken: args.input,
toToken: args.output,
amount: args.amount,
});
return result;
}
}
Direct Uniswap V3 Swap Execution
import { executeUniswapSwap } from '../evm/uniswap';
const swapResult = await executeUniswapSwap({
chain: 'arbitrum',
inputToken: 'USDC',
outputToken: 'WETH',
amount: '1000',
slippageBps: 30,
});
console.log('Transaction hash:', swapResult.txHash);
console.log('Output received:', swapResult.outputAmount);
Direct 1inch Swap Execution
import { executeOneInchSwap } from '../evm/oneinch';
const result = await executeOneInchSwap({
chain: 'optimism',
fromToken: 'ETH',
toToken: 'DAI',
amount: '0.5',
slippageBps: 150,
});
console.log('Swap completed:', result.success);
console.log('Transaction hash:', result.txHash);
Summary
- Entry Point: Swap commands enter via
src/skills/executor.tswith optional DEX specification. - Auto-Routing: The
compareDexRoutesfunction insrc/evm/oneinch.tsevaluates both Uniswap V3 and 1inch quotes to determine optimal execution. - Token Handling: Symbol-to-address resolution occurs through
resolveToken(Uniswap) andresolveTokenAddress(1inch) before quoting. - Execution:
executeUniswapSwapandexecuteOneInchSwapmanage the complete transaction lifecycle, from approval to submission. - Security: All transactions pass through validation layers in
src/security/tx-validator.tsandsrc/security/shield.tsbefore broadcast.
Frequently Asked Questions
How does CloddsBot decide between Uniswap V3 and 1inch?
When the dex parameter is set to 'auto', the system invokes compareDexRoutes to fetch simultaneous quotes from both sources. It compares the expected output amounts after accounting for gas costs and slippage, selecting the DEX that provides the maximum net return for the user.
What happens if a token address is provided instead of a symbol?
Both resolveToken (Uniswap module) and resolveTokenAddress (1inch module) check whether the input matches a known symbol mapping. If the input is already a valid contract address (0x...), the functions bypass the symbol lookup and return the address directly, ensuring compatibility with any ERC-20 token.
Which file contains the high-level routing logic for agent operations?
The agent dispatch logic that coordinates between skills and execution modules resides in src/agents/index.ts. This file imports the executor functions and manages the flow between natural language parsing and the technical swap execution layer.
Are there built-in protections against malicious contracts?
Yes. Before executing any swap, the transaction data passes through src/security/tx-validator.ts for parameter validation and src/security/shield.ts for address reputation checks. These modules filter known scam addresses, enforce configurable gas limits, and validate calldata structure to prevent common attack vectors.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →