hackquest logo

Sapient

Sapient is an autonomous AI agent that manages a decentralized finance portfolio on the Base network. You connect your wallet, delegate specific permissions via MetaMask Smart Accounts (EIP-7702), and

비디오

기술 스택

Web3
Solidity

설명

Sapient: Autonomous AI DeFi Agent

Agentic Wallets & Economy Hackathon 2026

BaseMetaMaskVenice AI

What is Sapient?

Sapient is an autonomous AI agent that manages a decentralized finance portfolio on the Base network. You connect your wallet, delegate specific permissions via MetaMask Smart Accounts (EIP-7702), and chat with the agent in natural language. It executes token swaps and yield farming strategies on your behalf while enforcing hardcoded risk guardrails and publishing every decision to IPFS as a permanent, immutable audit trail.

Example interaction:

"Sapient, the markets are looking good. Swap 50 USDC for WETH and deposit the rest into the lending pool."

Sapient will:

  1. Analyze your prompt and determine the optimal sequence of actions.

  2. Use Venice AI (paid autonomously via x402 micropayments) for deeper market reasoning if the strategy requires it.

  3. Execute the token swap and lending deposit on Base Sepolia using its delegated authority.

  4. Hash its internal rationale, pin it to IPFS, and maintain a permanent audit log.

  5. Return the transaction hashes with direct block explorer links to the user interface.


Architecture Overview

+----------------------------------------------------------------------+
|                          USER EXPERIENCE                             |
|                                                                      |
|  +-------------+     +-------------------+     +-----------------+   |
|  |  MetaMask   |     |   Chat Interface  |     |   Dashboard     |   |
|  |  Connect    |     |   "Swap 100 USDC  |     |   Portfolio     |   |
|  |  Delegate   |     |    for WETH"      |     |   Positions     |   |
|  +------+------+     +--------+----------+     +--------+--------+   |
|         |                     |                         |            |
+---------+---------------------+-------------------------+------------+
          |                     |                         |
          v                     v                         v
+---------------------------------------------------------------------+
|                        NEXT.JS 14 APP ROUTER                        |
|                                                                     |
|  /api/chat          /api/status         /api/delegation             |
|  +--------------+   +--------------+    +--------------+            |
|  | Tool Registry|   | Wallet       |    | Intent       |            |
|  | streamText() |   | Agent State  |    | EIP-7702     |            |
|  | Groq LLM     |   | Positions    |    | Management   |            |
|  +------+-------+   +--------------+    +--------------+            |
+---------+-----------------------------------------------------------+
          |
          v
+----------------------------------------------------------------------+
|                        AI AGENT CORE                                 |
|                                                                      |
|  +----------------+  +--------------+  +--------------------------+  |
|  | System Prompt  |  |  Guardrails  |  |     Self-Auditor         |  |
|  | * Personality  |  |  * Hard      |  |  * SHA-256 rationale     |  |
|  | * Capabilities |  |  * Soft      |  |  * Pinata IPFS pinning   |  |
|  | * Risk-aware   |  |  * Circuit   |  |                          |  |
|  +----------------+  +--------------+  +--------------------------+  |
|                                                                      |
|  +--------------------------------------------------------------+    |
|  |                    TOOL REGISTRY                             |    |
|  |                                                              |    |
|  |  READ:   Portfolio, Yields, Audit Trail                      |    |
|  |                                                              |    |
|  |  WRITE:  swapTokens, manageLending, withdrawFunds,           |    |
|  |          selfAudit, setGuardrails, killSwitch, askVeniceAI   |    |
|  +--------------------------------------------------------------+    |
+----------------------+-----------------------------------------------+
                       |
        +--------------+--------------+
        v              v              v
   +---------+  +-----------+  +--------------+
   | Base    |  | MetaMask  |  | Venice AI    |
   | RPC     |  | Smart Acc |  | x402 Payment |
   +----+----+  +-----+-----+  +------+-------+
        |             |               |
        v             v               v
+--------------+ +--------------+ +--------------+
| MockSwap     | | MockLending  | | USDC Mainnet |
| Router       | | Pool         | | Transfer     |
+--------------+ +--------------+ +--------------+

Key Design Decisions

Decision

Rationale

MetaMask Smart Account Delegation

The user retains ultimate control. The agent executes transactions using session keys and scoped permissions (EIP-7702), ensuring the agent never holds user funds directly.

x402 Venice AI Micropayments

The agent pays for its own deeper inference calls autonomously using USDC on Base mainnet via header-based x402 micropayments. No central API key bottlenecks.

Groq via Vercel AI SDK v6

Streaming tool-calling with Zod schema validation. The base agent uses fast, free-tier inference to route requests and determine execution paths.

Self-audit to IPFS

Every trade leaves a permanent, verifiable paper trail. The execution rationale is hashed and pinned to IPFS. It cannot be deleted or altered by the agent or the developer.

Foundry Smart Contracts

High-performance Rust-based testing and deployment framework for the mock decentralized exchange and lending pool contracts on Base Sepolia.


Security and Delegation

EIP-7702 Delegation

Sapient relies on the emerging EIP-7702 standard for externally owned account (EOA) delegation. When a user connects their wallet to the dashboard, they are prompted to authorize the agent.

The authorization grants scoped permissions:

  • Token Swaps (DEX routing on Base)

  • Lending Deposits (Supply/withdraw from pools)

  • IPFS Audit Trail (Automatic pinning)

  • Venice AI Payments (Autonomous x402 spending)

If the agent misbehaves or the user wishes to revoke access, they simply cancel the delegation from their MetaMask wallet.


The AI Agent

Tool Registry

Sapient utilizes the Vercel AI SDK v6 tool API with strict Zod-validated input schemas. The language model chooses which tool to call, and the application layer enforces the execution constraints.

Read Tools

Tool

Description

getPortfolio

Full portfolio overview including agent wallet balances and active lending positions.

getYields

Retrieves mock APY data from the lending pool.

getAuditTrail

Fetches IPFS CIDs and action logs from past agent decisions.

Write Tools (Guardrailed)

Tool

Guardrails

swapTokens

Token whitelist check, maximum trade size limit, automatic IPFS audit.

manageLending

Token whitelist check, maximum deposit limit, automatic IPFS audit.

askVeniceAI

Autonomously signs an EIP-712 transfer to pay $0.001 USDC per call via x402.

withdrawFunds

Sends funds from the agent wallet back to the user's connected address.

selfAudit

Manual trigger to pin current state to IPFS.

setGuardrails

Can only tighten limits; cannot loosen limits beyond hardcoded safety defaults.

killSwitch

Emergency pause on all trading activity.

Guardrail Engine

  1. Hard Guardrails (Immediate Block):

    • Kill switch engaged

    • Circuit breaker tripped (consecutive losses)

    • Token not whitelisted

    • Trade exceeds absolute maximum size

    • Gas anomaly detected

  2. Soft Guardrails (Require User Approval):

    • Trade exceeds soft limit

    • Lending deposit exceeds soft limit

  3. Circuit Breakers (Post-execution):

    • Consecutive failed transactions triggers auto-pause

    • Slippage anomaly triggers warning

Self-Audit Trail

Every successful action is permanently recorded:

  1. Build rationale JSON containing the action, parameters, reasoning, guardrail checks, and results.

  2. Hash the data with SHA-256.

  3. Pin the file to IPFS via Pinata.


Smart Contracts

The project includes custom smart contracts deployed to Base Sepolia using Foundry to simulate a real decentralized finance ecosystem for the agent to interact with.

MockERC20.sol

ERC-20 test tokens (USDC, WETH, cbBTC, USDT) with a public minting function for testing purposes.

MockSwapRouter.sol

A Uniswap V2-compatible mock decentralized exchange. It burns the input token and mints the output token based on hardcoded USD prices, applying a 0.3% fee to simulate real trading conditions.

MockLendingPool.sol

An Aave V2-compatible mock lending pool. It tracks user deposits, allows withdrawals, and returns mock Annual Percentage Yield (APY) data.


Quick Start Guide

Prerequisites

  • Node.js 18+

  • MetaMask browser extension

  • Base Sepolia ETH (from a public faucet)

  • Groq API key (for base agent reasoning)

  • Foundry (for compiling and deploying contracts)

Setup Instructions

  1. Install Dependencies

  2. Configure Environment Copy the .env.example file to .env and fill in your private keys and API credentials.

    cp .env.example .env
  3. Deploy Contracts (Optional) If you wish to deploy your own instance of the mock contracts to Base Sepolia:

    cd contracts
    forge build
    forge script script/Deploy.s.sol --rpc-url https://sepolia.base.org --broadcast --private-key YOUR_PRIVATE_KEY

    Update the contract addresses in your .env file after deployment.

  4. Run the Development Server

    npm run dev
  5. Interact Navigate to http://localhost:3000 in your browser. Connect your MetaMask wallet, view the dashboard, and start chatting with Sapient to execute trades.


Project Structure

src/
|-- agent/
|   |-- config.ts              # Network and contract configurations
|   |-- system-prompt.ts       # Core agent persona and instructions
|   |-- guardrails.ts          # Risk management enforcement logic
|   |-- auditor.ts             # IPFS pinning and hashing logic
|   |-- memory.ts              # SQLite database integration for context
|   |-- wallet.ts              # EOA wallet execution setup
|-- app/
|   |-- api/
|       |-- chat/route.ts      # Vercel AI SDK integration and tool definitions
|       |-- status/route.ts    # Dashboard analytics endpoint
|       |-- delegation/route.ts# MetaMask EIP-7702 intent endpoint
|       |-- withdraw/route.ts  # Funds recovery endpoint
|   |-- chat/page.tsx          # Chat user interface
|   |-- dashboard/page.tsx     # Portfolio and system status user interface
|   |-- page.tsx               # Application landing page
|-- components/                # Reusable React user interface components
|-- lib/                       # Utility functions, ABIs, and types
contracts/
|-- src/                       # Mock decentralized finance Solidity contracts
|-- script/                    # Foundry deployment scripts

Tech Stack

  • Frontend: Next.js 14 (App Router), React 18, Tailwind CSS

  • AI Integration: Vercel AI SDK v6, Groq, Venice AI (via custom x402 client)

  • Smart Contracts: Solidity 0.8.20, Foundry

  • Blockchain Interaction: viem

  • Storage: better-sqlite3 (local memory), Pinata (IPFS audit trail)


License

MIT

해커톤 진행 상황

The entire project was built in the duration of the hackathon.

자금 모금 상태

Open to funding!

팀 리더
SShreshth Sharma
프로젝트 링크
배포 생태계
Base Sepolia TestnetBase Sepolia Testnet
부문
DeFiAI