Swap API Functionality
The architecture, data structures, and usage of the Swap API within the United non-custodial ecosystem. The Swap API facilitates token exchanges by aggregating liquidity from various DEXs via serverless endpoints.
1. Dependencies
The Swap API relies on a distributed serverless infrastructure to ensure low latency and high availability, optimized for mobile NFC interactions.
- Blockchain Interaction: Multi-chain RPC Infrastructure.
- Liquidity Sources: Integrated DEX Aggregators (Web3 Services Layer).
- Frontend Integration: React Native / Web (via NFC Tap flows).
2. Data Structures
The API primarily deals with Quotes and Transaction payloads.
SwapQuoteRequest
Parameters required to fetch a potential trade.
chainId: ID of the blockchain (e.g., 1 for Ethereum).tokenIn: Address of the token to sell.tokenOut: Address of the token to buy.amount: Amount oftokenInin wei/atomic units.slippage: Max acceptable slippage percentage.
SwapQuoteResponse
The estimated result of a trade.
quoteId: Unique identifier for the quote (valid for a limited duration).amountOut: Estimated amount oftokenOutto receive.priceImpact: Estimated price impact of the trade.route: Array of hops/pools used for the swap.gasEstimate: Estimated network fee.
SwapTransaction
The constructed transaction data ready for signing.
to: The router/aggregator contract address.data: Calldata for the swap execution.value: Native token value (if applicable).gasLimit: Recommended gas limit.
3. Functions
These functions represent the core API endpoints exposed via Cloudflare Workers.
getQuote(request: SwapQuoteRequest): Promise<SwapQuoteResponse>
Aggregates prices from multiple DEXs and returns the best execution path.
- Input:
SwapQuoteRequest - Output:
SwapQuoteResponse - Implementation: Queries connected DEX aggregators in parallel and filters for the best output amount after fees.
buildTransaction(quoteId: string, userAddress: string): Promise<SwapTransaction>
Generates the executable transaction data for a selected quote.
- Input:
quoteId(fromgetQuote),userAddress(sender). - Output:
SwapTransaction - Implementation: Fetches the calldata from the selected aggregator API, validating parameters against the original quote to prevent front-running/slippage anomalies.
4. Implementation Details
The Swap API is designed as a non-custodial layer. It does not hold user funds.
- Serverless Proxy: Cloudflare Workers act as a secure proxy between the client and Web3 providers, hiding API keys and managing rate limits.
- Global CDN: Content delivery is optimized via Cloudflare's global network to reduce latency during the "tap-to-swap" NFC flow.
- Security:
- Transaction Validation: The API validates transaction parameters before sending them to the client to ensure they match the user's intent.
- Non-Custodial: The API only constructs unsigned transactions. Signing is performed strictly on the client side (via NFC hardware).
5. Usage Example
The following example demonstrates how to fetch a quote and execute a swap using the Swap API and the NFC Interaction handler.
import { getQuote, buildTransaction } from './api/swap';
import { nfcHandlerWindow } from './ui/nfcHandler';
async function performSwap(tokenIn, tokenOut, amount, userAddress, userPin) {
// 1. Get a Quote
const quote = await getQuote({
chainId: 1,
tokenIn: tokenIn.address,
tokenOut: tokenOut.address,
amount: amount,
slippage: 0.5
});
// 2. Build the Transaction
const swapTx = await buildTransaction(quote.quoteId, userAddress);
// 3. Execute via NFC (Signing)
// The nfcHandlerWindow manages the chunking and card communication
// See NFC_INTERACTION.md for details on the request object structure
await nfcHandlerWindow.nfcProgressChunksHandler(swapTx, userPin, true);
}