Developer & protocol docs

Mentra Agentic DeFi OS

Conversational execution on Base — adapters, trust, builder identity, oracles, and non-custodial signing. Same engine the product runs.

Agentic DeFi OS

What is Mentra?

Mentra is the first Conversational DeFi Operating System on Base. You describe an intent in natural language — open a perp, swap a token, supply a vault, inspect trust — and Mentra maps that utterance onto a typed on-chain action without taking custody of funds.

The OS sits above protocol adapters (Avantis, Aerodrome, Morpho) and intelligence engines (trust, reputation, builder score). Agents execute through the same confirmation cards a human trader sees. Nothing is signed until you approve it in your wallet.

Conversational pipeline
Chat utteranceIntent parserAdapter simWallet sign

The fragmentation problem

Core problem solved: fragmented DeFi UIs. Instead of hopping across DEX frontends, perp terminals, and lending dashboards, you chat once. Mentra classifies the intent, runs pre-flight checks (min size, max leverage, slippage, oracle freshness), then presents a two-step confirmation card.

Next: Action Engine

Chat-to-trade & swap

Conversational Action Engine

The Conversational Action Engine is Mentra’s chat-to-execution path. Natural language is parsed into a typed ActionPayload (open, close, update TP/SL, swap, supply, borrow). Protocol adapters then simulate, quote, and — only after you confirm — submit via the connected wallet.

Intent classification

Intent classification maps natural-language prompts onto a closed set of typed on-chain actions. Unknown markets, sub-minimum collateral, or leverage above pairMaxLeverage fail in prose before a wallet popup appears. Last-referenced market is remembered across turns so “close 50%” resolves to the pair you just discussed.

intent → typed action

// Utterance
"Long ETH with 5x on $100 USDC, SL 2% below mark"

// Classified payload (shape)
{
  kind: "open_position",
  protocol: "avantis",
  marketId: "eth-usd",
  side: "long",
  collateralUsdc: 100,
  leverage: 5,
  slPercent: 2
}

// Runtime path
AvantisAdapter.simulate → ActionTradeCard → approve USDC → sign tx

Avantis Protocol Integration

Conversational perpetual leverage on Avantis: open and close longs/shorts, set dynamic take-profit / stop-loss, and surface liquidation distance from mark, leverage, and maintenance math. Execution fees are quoted from live Pyth Hermes VAAs plus AvantisAdapter.getExecutionFee() so the overlay matches what the contract will charge.

  • Markets: ETH-USD, BTC-USD, SOL-USD, DOGE-USD and the live Avantis catalog.
  • Pre-flight: minimum $10 USDC collateral and pair max leverage from pairStorage.
  • Oracle: Hermes latest + VAA bytes for updatePriceFeeds; bilingual EN/FA revert decoding on failure.
  • After fill: mentra:trade-executed event refreshes portfolio positions.

Aerodrome Protocol Integration

Conversational token swaps on Base via universal routers. Mentra quotes the route, applies pre-flight slippage bounds, and will not submit a swap that exceeds the user’s stated tolerance. The same confirmation card pattern applies: review quote → approve token if needed → sign.

Morpho Protocol Integration

Yield optimization and conversational lending/borrowing vaults. Supply, withdraw, borrow, and repay are expressed as chat intents, then bound to Morpho market params and asset amounts in base units. The agent never guesses a vault that is not on the connected Base deployment.

Action Confirmation Cards

Two-step confirmation
1 · USDC allowance2 · Atomic protocol execution

Confirmation cards implement a two-step security model. Step 1: USDC (or token) allowance approval to the protocol spender, exact amount when possible. Step 2: atomic contract execution (open market order, swap, or Morpho market call). Mentra never batches those two signatures into a single opaque “approve all” flow.

allowance then execute

const needed = neededUsdcAllowance(collateralUsdc)
const { allowanceRaw } = await readUsdcAllowance(account)

if (!hasSufficientUsdcAllowance(allowanceRaw, collateralUsdc)) {
  await sendUsdcApprove(needed) // step 1 — wallet popup
}

await openMarketOrder(params)  // step 2 — atomic Avantis call

Next: Trust & Risk

0–100 algorithmic shield

Mentra Trust Score

Mentra Trust Score is a 0–100 algorithmic assessment of a Base project’s on-chain hygiene. It is stored intelligence — never a vibes overlay. The quant risk matrix folds LP lock duration, ownership renounce status, whale concentration, and contract upgradeability into a single shield used by project cards, share copy, and agent warnings.

Quant risk matrix
LP lockOwnershipWhale shareUpgradeabilityTrust Score 0–100

Score inputs

  • LP lock duration — longer, verifiable locks raise trust; unlocked liquidity is a penalty.
  • Ownership renounce — ownerless or timelocked admin is healthier than an EOA with mint rights.
  • Whale concentration — top-holder share and clustered funding wallets increase sybil / dump risk.
  • Upgradeability — proxy admins and open implementation slots are scored as change-risk, not as a ban.

Pre-trade risk

On the trading path, Mentra adds liquidation proximity alerts and margin health calculators. For Avantis perps this is computed from mark (Pyth), position size, leverage, and maintenance margin — not from a guessed “safe” buffer. If mark is stale or Hermes is unavailable, the engine refuses to invent a price.

trust band (illustrative)

function trustBand(score: number): "high" | "mid" | "low" {
  if (score >= 85) return "high"
  if (score >= 60) return "mid"
  return "low"
}

// Project Intelligence Card uses stored trustScore 0–100.
// Share copy: "Mentra Trust Score: 93/100"

Next: Builder Identity

Composite 40 / 60

Builder reputation

Builder identity binds a Base wallet to a GitHub account (Privy OAuth). Mentra then scores the pair with a deterministic composite: 40% Code Velocity and 60% On-Chain Traction. Metrics are fetched — never invented. Missing GitHub or on-chain data simply zeros that component.

Builder composite
40% Code Velocity60% On-chain Traction

Composite scoring algorithm

  • 40% Code Velocity — GitHub commit consistency (90d), active public repos, merged PRs via Privy-linked OAuth.
  • 60% On-Chain Traction — contract deployments on Base, unique user interactions, processed volume (USD).
  • Log-normalized so a single whale deploy does not dominate a consistent public builder.

src/domains/builder/builderScoringEngine.ts

export const WEIGHTS = {
  velocity: 0.4,
  traction: 0.6,
  velocityBreakdown: {
    commits90d: 0.5,
    activeRepos: 0.25,
    mergedPRs: 0.25,
  },
  tractionBreakdown: {
    deployments: 0.3,
    uniqueUsers: 0.4,
    volumeUsd: 0.3,
  },
} as const

const raw = velocityScore * 0.4 + tractionScore * 0.6
const score = Math.round(clamp(raw * 10, 0, 1000)) // 0–1000

Rank tiers & badges

Rank tiers are cut from that 0–1000 score: Top 1% Base Architect (≥900), Top 5% Ecosystem Builder (≥700), Active Base Developer otherwise. Dynamic social badges and the Intelligence Card share flow (X / Telegram / Warpcast) stamp rank + Mentra Trust without fabricating volume.

Next: Infrastructure

Pyth + RPC fallback

Real-time infrastructure

Execution quality depends on fresh marks. Mentra integrates Pyth Network Hermes for sub-second price updates and automated execution-fee quotes. The browser talks to a same-origin POST /api/pyth/latest proxy so PYTH_API_KEY never ships in the client bundle. Feed ids stay in the JSON body — not in multi-kilobyte GET query strings.

Oracle & RPC layers
Pyth HermesPOST proxyAvantis feeBase RPCDexScreenerInternal cache

Pyth Hermes

  • Hermes latest + stream for marks; VAA bytes (hex) feed Pyth updatePriceFeeds on Avantis opens.
  • Server chunks Hermes at 40 ids; client POSTs up to 200 unique 32-byte feed ids.
  • AvantisAdapter.getExecutionFee() is overlaid on the trade card so users see oracle cost before signing.

POST /api/pyth/latest

await fetch("/api/pyth/latest", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({
    ids: [
      "0xff61491a931112ddf1bd8147cd1b641375f79f5825126d665480874634fd0ace", // ETH/USD
    ],
  }),
})

RPC fallback

Triple-layer fallback for reads: Base Mainnet RPC (primary, plus public Base endpoints) → DexScreener-style market metadata when a pair catalog is needed → internal cache (indexed positions, last-good marks). If every layer fails, Mentra surfaces an error — it does not hallucinate a last price.

Next: Security

Keys never leave the wallet

Non-custodial architecture

User funds remain 100% in user custody at all times. Mentra is a conversation layer and a transaction assembler. USDC, collateral, and vault shares sit in the connected address. There is no Mentra hot wallet, no deposit contract for “chat balance,” and no server-side signer.

Custody boundary
Mentra UI / agentsUnsigned txWallet

Client-side signing

  • Client-side transaction signing via Wagmi / Viem on Base (chain id 8453).
  • Zero private key retention — no keys in localStorage, cookies, or API logs.
  • Session (Privy / NextAuth) identifies the builder; it cannot move funds without a wallet popup.
  • Allowances are per-spender and preferably exact-amount; revoke anytime from your wallet.

signing boundary

// Browser — unsigned call data only
const hash = await writeContract(wagmiConfig, {
  address: trading,
  abi: tradingAbi,
  functionName: "openTrade",
  args: [tradeTuple],
  value: executionFeeWei,
})

// Mentra servers never receive the private key.
// They may store public tx hashes after you broadcast.

Next: You are at the end of this hub.