DeFi 1inch Commander video demo

DeFi 1inch Commander

DeFi 1inch Commander: A next-gen DeFi dashboard for portfolio, swaps, and risk, using 1inch APIs.

DeFi 1inch Commander

Created At

Unite Defi

Project Description

DeFi 1inch Commander is a next-generation decentralized finance (DeFi) dashboard that provides a comprehensive suite of tools for portfolio management, token swapping, and risk analysis, all powered by the 1inch Network APIs, Moralis API, and generative AI.

What it Does This DApp empowers users to take command of their DeFi assets with a unified and intuitive interface. Key features include:

Comprehensive Portfolio Aggregation: Connect your crypto wallet to see an aggregated view of your DeFi portfolio positions across the Ethereum network. The dashboard displays both your native ETH balance and all your ERC20 tokens, powered by the Moralis API. Balance & PnL Display: Get a clear overview of your portfolio's total value, individual asset balances, and real-time prices, including 24-hour percentage changes. AI-Powered Risk Assessment: Leverage the power of Google's Gemini through Genkit to analyze your portfolio's risk exposure. Receive a detailed summary and actionable recommendations to mitigate risks. Token Swapping: Seamlessly swap tokens directly from the dashboard, leveraging the 1inch Aggregation Protocol to ensure the best possible rates. API Transparency: For developers and curious users, the dashboard displays the raw JSON responses from the Moralis API, showing exactly what data is being used to populate the portfolio and price information. Why We Built It The DeFi landscape is fragmented and can be intimidated for both new and experienced users. Managing assets across different protocols, finding the best swap rates, and understanding portfolio risk requires juggling multiple tools and a high level of expertise.

We built DeFi 1inch Commander to solve these problems by:

Simplifying Complexity: Offering a single, elegant dashboard for all key DeFi activities. Enhancing Decision-Making: Providing AI-driven insights that demystify risk and help users make more informed decisions. Maximizing Efficiency: Integrating 1inch's powerful APIs for swapping and Moralis for portfolio data to guarantee efficient trading and data aggregation. Our goal is to create a powerful yet user-friendly command center for anyone interacting with the world of decentralized finance.

Technical Architecture The DApp is built on a modern, robust, and scalable tech stack, designed for a great developer and user experience.

Frontend Framework: Next.js with the App Router for a performant, server-first architecture. Programming Language: TypeScript for type safety and improved code quality. UI Components: ShadCN UI and Tailwind CSS for a beautiful, responsive, and customizable design system. AI Integration: Genkit (running Google's Gemini model) for the AI Risk Assessment feature. This allows for powerful, structured AI interactions directly from server components. Blockchain Connectivity: Wagmi and Viem provide robust hooks and utilities for interacting with the Ethereum blockchain. Wallet Integration: WalletConnect (Web3Modal) for seamless and secure connection to a wide range of crypto wallets. DeFi Data APIs: Moralis API: Used for fetching native balance, ERC20 token balances, and token prices for portfolio aggregation. 1inch API: Used for fetching a comprehensive list of swappable tokens and for executing swaps.

How it's Made

Core Architecture Philosophy The project is built on a modern, server-centric frontend architecture using Next.js. The guiding principle was to keep the client-side as lean as possible, delegating all data fetching, API interactions, and AI processing to the server. This is achieved through Next.js Server Actions, which act as a secure and efficient bridge between the user's browser and our backend logic.

This approach offers several advantages:

Security: API keys (for 1inch, Gemini) are never exposed to the client. Performance: The client bundle remains small, as heavy data processing logic resides on the server. Simplicity: It eliminates the need for a separate backend server or complex state management libraries for data fetching (like React Query or SWR), as Next.js handles the client-server data flow transparently.

Technology Stack The application is a carefully curated stack of modern web and blockchain technologies:

Framework: Next.js 14+ (App Router) is the foundation. We leverage server components for UI rendering and Server Actions for all backend operations. Language: TypeScript is used throughout for type safety, reducing runtime errors and improving developer experience. Styling: Tailwind CSS provides the utility-first styling framework, and ShadCN UI serves as the component library for building the user interface. This combination allows for rapid development of a clean, consistent, and professional-looking UI. Blockchain Connectivity: We use the WAGMI library (with Viem) to handle Ethereum interactions. Web3Modal (from WalletConnect) provides the beautiful and seamless wallet connection UI. These are set up in src/components/providers/web3-provider.tsx. AI Integration: Genkit (Google's generative AI framework) is used to orchestrate calls to the Gemini LLM. The AI logic is encapsulated in a "flow" (src/ai/flows/analyze-portfolio-risk.ts), which defines the prompt, input/output schemas, and interaction with the model. DeFi Data: 1inch Network APIs are the exclusive source of all DeFi data, from token lists and balances to swap quotes and transaction history.

How The Pieces Fit Together User Connects Wallet: The user journey begins at the Header component, which contains the <w3m-button /> from Web3Modal. This handles the entire wallet connection process. Address Propagation: Once connected, WAGMI hooks provide the user's address to the main page (src/app/page.tsx). Server Actions Take Over: This address is passed from the UI components to Server Actions defined in src/app/actions.ts. For example, getPortfolioAction(address) is called to fetch the user's assets. 1inch Service Layer: The Server Actions do not call the 1inch API directly. Instead, they call functions in a dedicated service layer (src/services/1inch.ts). This file contains reusable functions (getPortfolio, getQuote, getTokens, etc.) that handle the actual fetch calls, authorization, and error handling for every 1inch API endpoint. Data Flow for UI: The PortfolioOverview component is populated by the getPortfolioAction. The TokenSwap component uses getTokensAction to populate its dropdowns and getQuoteAction to fetch real-time swap estimates. Data Flow for AI: When the user clicks "Analyze Portfolio Risk" in the RiskAssessment component, a server action named prepareComprehensiveRiskAnalysis is called. This single action orchestrates multiple calls to the 1inch.ts service layer, fetching the user's full portfolio, transaction history, available liquidity sources, and network presets. This aggregated data is then sent to the Genkit flow (analyzePortfolioRisk) as a single, comprehensive context object. The AI's response (risk summary and recommendations) is then passed back to the UI for display.

How 1inch APIs Benefited the Project The 1inch API suite was not just a data source; it was the enabling technology for the entire application. It provided a unified, consistent, and powerful toolkit that allowed us to build a feature-rich "Commander" dashboard from a single integration point.

Backbone of the Portfolio: The /balance API is the cornerstone of the portfolio feature. Instead of manually querying contracts for dozens of tokens, a single API call returns a comprehensive list of all of a user's assets recognized by 1inch, complete with balances. We then cross-reference this with the /price API to get real-time USD values. Powering the Swap: The /swap/v6.1/quote endpoint provides the core functionality for the Token Swap feature. It abstracts away the immense complexity of decentralized exchange routing, providing a simple, direct, and executable quote. This allowed us to build a powerful trading tool without needing to implement any complex routing logic ourselves. Creating Rich AI Context: This is where 1inch truly shines as a partner technology. The AI Risk Assessment is only as good as the data it's given. By combining multiple 1inch endpoints, we created an incredibly rich context for the AI: /balance tells the AI what the user holds. /history tells the AI how the user trades. /liquidity-sources and /presets tell the AI about the current market conditions and environment. This multi-faceted context allows the Gemini model to go beyond generic advice and provide personalized, actionable insights that are directly relevant to the user's specific situation and the current state of the DeFi market, as seen by 1inch.

Notable Hacks & Development Journey Initial API Struggles & Correction: The development process involved significant learning and iteration, particularly around the 1inch APIs. We initially used an incorrect endpoint for fetching balances which led to missing native ETH and "Unknown Token" errors. We corrected this by switching to the balance/v1.2 endpoint and implementing a more robust process: fetch all balances, then fetch a comprehensive list of all known tokens on the chain to ensure every asset could be correctly identified. Evolving the AI Prompt: The AI prompt went through a major refactoring. Initially, the prompt template was defined directly in the "use server" file, which caused build errors with Next.js. The solution was to move the user-facing display of the prompt into a server action (actions.ts) while keeping the core AI prompt logic within the Genkit flow file. We also significantly improved the prompt's clarity by adding descriptive headers to each block of JSON data, which drastically improved the quality and reliability of the AI's analysis. Simulated Swaps: For the purpose of this hackathon and to create a safe user experience, the final "swap" action is simulated. The handleExecuteSwap function in the TokenSwap component generates a fake transaction hash and displays a success dialog. This demonstrates the complete UI flow without requiring the user to sign a real, on-chain transaction.

background image mobile

Join the mailing list

Get the latest news and updates