DocsIntroduction

Welcome to Aegis Documentation

Aegis is a decentralized trust layer for autonomous AI agents on Sui. It tracks onchain metrics - success rate, volume, uptime - and issues verifiable badges that control access permissions for protocols integrating AI agents.

Phase 2 Roadmap Available

Dynamic Trust, Autonomous Contingency & Cost-Efficient Monitoring

DocsQuickstart

Quickstart

Everything you need to integrate Aegis in your agent or protocol.

Prerequisites

  • Sui Wallet installed (Slipstream or Sui Wallet extension)
  • Node.js 18+ and pnpm/yarn
  • Environment variables configured (see .env.local.example)
  • Testnet SUI tokens - fund via faucet.testnet.sui.io

Step-by-step Setup

1Install the SDK
npm install @aegis/sdk
# or
pnpm add @aegis/sdk
2Configure wallet connection
import { SuiClient, getFullNodeUrl } from '@mysten/sui/client';
import { PACKAGE_ID, BADGE_REGISTRY_ID } from '@aegis/sdk';

const client = new SuiClient({ url: getFullNodeUrl('testnet') });
3Deploy your ReputationObject
import { registerAgent } from '@aegis/sdk';

// Simulates: sui client call --function register_agent
const { objectId } = await registerAgent(signer);
console.log('ReputationObject:', objectId);
4Record executions with error handling
import { recordExecution } from '@aegis/sdk';

try {
  await recordExecution(signer, objectId, true, 1_000_000_000, 50);
} catch (err) {
  if (err.code === 'BADGE_REVOKED') activateBackupAgent();
}
5Verify badge status on explorer
import { checkBadgeStatus } from '@aegis/sdk';

const { badge, isValid } = await checkBadgeStatus(agentId);
console.log(`Badge: ${badge}, Valid: ${isValid}`);
// Verify on: suiexplorer.com/testnet/object/${objectId}
DocsInstallation

Installation

Install the Aegis SDK via npm or pnpm.

bash
npm install @aegis/sdk

# or

pnpm add @aegis/sdk
DocsBasic Usage

Basic Usage

Import the client and fetch agent reputation.

typescript
import { createClient } from '@aegis/sdk';

const client = createClient({
  network: 'testnet'
});

// Fetch agent reputation
const agent = await client.getAgentReputation('0x...');
console.log(agent.badge); // 'bronze' | 'silver' | 'gold' | null

Key Concepts

Reputation System

Onchain metrics that track agent performance - executions, success rate, slippage, uptime

Badge Registry

Bronze (LVL 1), Silver (LVL 3), Gold (LVL 5) - access-level certifications issued onchain

Aegis Score

Multi-dimensional score: Performance 37% + Reliability 28% - Risk Penalty + Contribution 10%

Auto-Revocation

Onchain enforcement - >5 consecutive failures, <50% success rate, or >500 BPS slippage triggers instant credential revocation

MemWal Audit Trail

Encrypted private memory for agent reasoning; blob_id anchored in ReputationObject for full traceability

DocsAPI Reference

API Reference

Complete SDK function signatures. All functions are async and target Sui Testnet.

recordExecution(params)

Records an agent execution event onchain. Updates metrics and checks badge eligibility/revocation.

ParameterTypeRequiredDescriptionExample
`objectId``string`Address of the ReputationObject"0x4CD8BE..."
`success``boolean`Outcome of the executiontrue
`volume``number`Volume in MIST (1 SUI = 10⁹)1000000000
`slippage``number`Slippage in BPS (100 = 1%)50
`metadata``object`Extra data for audit trail{ pool: "SUI/USDC" }

Returns: Promise<ExecutionReceipt>

Errors: BadgeRevokedError, AccessLevelError, RateLimitError

typescript
try {
  await recordExecution({ objectId, success: true, volume: 1e9 });
} catch (err) {
  if (err instanceof BadgeRevokedError) {
    // Trigger fallback logic
    await activateBackupAgent();
  }
}

registerAgent(signer)

Deploys a new ReputationObject onchain. Called once per agent identity.

typescript
const { objectId, digest } = await registerAgent(signer);
// objectId = your permanent onchain identity
// digest = transaction hash for verification

computeAegisScore(data)

Client-side scoring function. Returns multi-dimensional score without any additional RPC calls.

typescript
import { computeAegisScore, getAgentReputation } from '@aegis/sdk';

const rep = await getAgentReputation(objectId);
const result = computeAegisScore(rep);

console.log(result.score);            // e.g. 98.4
console.log(result.tier);             // 'Platinum' | 'Gold' | 'Silver' | 'Bronze' | 'Unranked'
console.log(result.status);           // 'Active' | 'Supervised' | 'Under Review' | 'Quarantined'
console.log(result.breakdown);        // { performance, reliability, riskPenalty, contribution }

getBadgeEligibility(objectId)

Returns which badges the agent qualifies for based on current onchain metrics.

typescript
const { bronze, silver, gold } = await getBadgeEligibility(objectId);
// bronze: 10+ execs, 80%+ success
// silver: 50+ execs, 90%+ success
// gold:   200+ execs, 95%+ success, $1M+ volume
DocsIntegration Guides

Integration Guides by Use Case

How real protocols integrate Aegis across different agent architectures.

Agentic Trading Bot

Bot Developers

  • Register agent before first trade
  • Record each trade with success + volume + slippage
  • Auto-revoke on >5 consecutive losses
  • Use computeAegisScore() to optimize strategy

Yield Aggregator

DeFi Protocols

  • Whitelist only Gold/Silver agents per vault
  • Implement hybrid fallback via find_best_backup()
  • Circuit breakers: cap loss per epoch at 5%
  • Monitor BadgeRevokedEvent for instant swap

Oracle Network

Infrastructure

  • Track uptime score as primary KPI
  • Record execution for every price feed update
  • Slashing conditions tied to slippage BPS
  • Leaderboard exposes oracle ranking

GameFi Agent

Game Developers

  • Session-based reputation per game match
  • Player-agent interaction logged onchain
  • Bronze badge = entry level, Gold = pro tier
  • Integrate badges into in-game UI via SDK
DocsTesting

Local Development & Testing

Run a full local environment before deploying to testnet.

Testnet Configuration

bash
# Switch to Sui Testnet
sui client switch --env testnet

# Fund your wallet (faucet)
curl https://faucet.testnet.sui.io/gas?address=0xYOUR_ADDRESS

# Verify balance
sui client balance

Mocking Aegis for Unit Tests

typescript
import { mockAegisProvider } from '@aegis/sdk/testing';

const mock = mockAegisProvider({
  defaultBadge: 'gold',
  autoRevoke: false,
  simulatedLatency: 200,
});

test('agent executes with gold badge', async () => {
  const agent = await mock.registerAgent();
  expect(await agent.getBadge()).toBe('gold');
});

Running Integration Tests

bash
# Run against live testnet
pnpm test:integration --network=testnet --agent=mock

# Simulate revocation flow
pnpm test:revocation --scenario=consecutive-failures

# Stress test (volume spike)
pnpm test:stress --duration=60s --rps=100

MemWal Integration

Aegis works seamlessly with MemWal for private agent memory:

  • Private rationale - Agent's reasoning stays encrypted in Walrus
  • Public metrics - Success/slippage verified onchain by Aegis
  • Linked audit trail - MemWal blob_id anchored in ReputationObject
typescript
import { logExecution } from '@aegis/sdk';
import { memwalService } from '@aegis/sdk';

// 1. Store decision rationale in MemWal (private)
await memwalService.storeRationale({
  agentId: '0x...',
  reasoning: 'Market conditions favorable',
  decision: 'Execute with conservative slippage'
});

// 2. Record execution publicly on Aegis (onchain)
await recordExecution(signer, objectId, true, 1_000_000_000, 50);
// blob_id is automatically anchored in the ReputationObject
DocsTroubleshooting

Troubleshooting & Error Codes

Common errors returned by the SDK and how to resolve them.

Error CodeHTTPLikely CauseSolution
BADGE_REVOKED403Agent lost certification after metric dropActivate backup agent or rebuild metrics (100+ consecutive successes)
ACCESS_LEVEL_INSUFFICIENT403Operation requires LVL 5 but agent holds Silver (LVL 3)Upgrade agent badge or reduce the permission requirement
RATE_LIMIT_EXCEEDED429>100 recordExecution calls/min per agentImplement exponential backoff with jitter
INVALID_SIGNATURE401Wallet not authorized to sign this transactionVerify connected wallet owns the ReputationObject
OBJECT_NOT_FOUND404ReputationObject ID is wrong or prunedRe-fetch objectId from registerAgent() or sui_getObject
DocsSecurity

Security & Contract Audit

Full validation matrix for Aegis API, Move contracts, and integration patterns.

API Security Layer

EndpointRate Limit TierWindowValidation
GET /api/agentsRelaxed100 req/minsort enum allowlist · minExecutions ≥ 0 · trust sanitized
GET /api/agents/[id]Moderate30 req/min0x hex format · length 10–100 chars · rejects demo/SIM IDs
GET /api/agents/demoRelaxed100 req/minobjectId ≤ 100 chars · badge enum ∈ {none,bronze,silver,gold}
POST /api/agents/demoModerate30 req/minall ints validated · isFlagged bool-coerced · name ≤ 60 chars
DELETE /api/agents/demoStrict10 req/minno body accepted
POST /api/agents/registerStrict10 req/minname sanitized ≤ 50 chars · private key from env only
POST /api/chatModerate30 req/minmessages array · role ∈ {user,assistant,system} · content ≤ 2000 chars
Rate limit behaviour: IP extracted from X-Forwarded-For header (first value). Graceful 429 with Retry-After header. Keys stored in process memory per tier window — no external dependency.

API Key Handling

  • GROQ_API_KEY stored in server-side environment variable only — never exposed to client bundle
  • DEMO_WALLET_PRIVATE_KEY loaded from .env.local — falls back to ephemeral keypair + faucet if absent
  • NEXT_PUBLIC_CONVEX_SITE_URL is public-safe (no secrets) — prefixed correctly per Next.js convention
  • No hard-coded keys found in any source file across /api/* and /lib/*
  • X-Forwarded-For header is trusted without CIDR validation — behind a proxy, consider allowlisting trusted proxy IPs

Move Contract Audit — reputation.move · badge_registry.move

PASSInput bounds — volume

assert!(volume < 1_000_000_000_000, E_INVALID_VOLUME) — caps volume at 1T MIST per execution.

PASSInput bounds — slippage

assert!(slippage < 100_000, E_INVALID_SLIPPAGE) — rejects values ≥ 1000% slippage.

PASSEpoch-based rate limiting

assert!(current_epoch >= rep.last_update + 1, E_RATE_LIMITED) — enforces minimum 1 epoch between executions per object.

PASSAuto-flag: low success rate

Flagged when success_rate < 50% and total_executions > 0. Emits AgentFlagged event onchain.

PASSAuto-flag: consecutive failures

Flagged after 5+ consecutive failures. consecutive_failures resets to 0 on any successful execution.

PASSAuto-flag: high slippage

Flagged when single execution slippage ≥ 500 BPS (5%). Checked on every record_execution call.

PASSBadge eligibility double-check (badge_registry)

auto_check verifies reputation eligibility onchain before granting. Asserts no duplicate or higher badge (E_ALREADY_HAS_BADGE, E_HAS_HIGHER_BADGE). Badge type validated ∈ {1,2,3}.

PASSRevocation criteria enforced onchain

check_and_revoke_invalid re-validates all badge thresholds on each call. Revoked entries emit BadgeRevoked event.

WARNRecovery logic uses wrong field

check_and_unflag checks consecutive_failures >= 100, but this counter resets to 0 on success — so a flagged agent can never meet this condition through normal operation. The contract lacks a consecutive_successes counter. Recovery is effectively disabled until this is patched.

WARNGold badge volume threshold (badge_registry vs reputation)

badge_registry uses GOLD_MIN_VOLUME = 1_000_000 MIST (0.001 SUI). reputation.is_eligible_for_badge uses the same value. Both should be 1_000_000_000_000 MIST (1M SUI) to match the documented $1M volume requirement.

Component Architecture — Separation of Concerns

The following pages mix data fetching with presentation. Recommended refactor: extract data access into custom hooks or a container component, leaving the JSX as pure presentational output.

/pages/agents/index.tsx

getAllAgents() defined inline — move to useAgents() hook. Agent card JSX duplicated for demo and real agents — extract to AgentListCard component.

/pages/leaderboard/index.tsx

getLeaderboard() defined inline with 200+ lines of data-merge logic. Extract to useLeaderboard() hook. Row rendering is a candidate for LeaderboardRow component.

/pages/agent/[address].tsx

fetchReputation() called directly in useEffect — move to useReputation(address) hook. buildChartData() and generateActivity() are pure functions that belong in /lib/.

/components/AgentCard.tsx

getAgentReputation() fetches RPC directly inside a presentational component. This violates container/presentation separation — AgentCard should receive ReputationData as a prop.

Protocol Integrator Checklist

  • Always validate agent via contract_address - never trust display name alone
  • Implement circuit breakers for losses >X% per epoch
  • Maintain whitelist of pre-approved backup agents (Gold/Silver only)
  • Sign all critical transactions with multi-sig
  • Monitor BadgeRevokedEvent in real-time and trigger fallback automatically
  • Test fallback flow in staging environment before deploying to production

Common Pitfalls

  • Do NOT use agent name as unique identifier - use contract address + Badge ID
  • Do NOT ignore "Score Drop" alerts - they often precede revocation within hours
  • Do NOT hardcode agent addresses - use dynamic registry lookup at runtime
DocsRoadmap

Aegis Protocol - Phase 2 Roadmap

Theme: Dynamic Trust, Autonomous Contingency & Cost-Efficient Monitoring

Phase 1 - Baseline (Functional)

Agent registration with static badges (Gold/Silver/Bronze)
Contract address + display name identification
Manual or semi-automatic revocation
Simple onchain event logging
External monitoring via static dashboard

Phase 2 Objective

Transform Aegis from a static certification system into a dynamic trust layer, enabling DeFi protocols to operate with automatic fallback, continuous onchain evaluation, and cost-optimized monitoring.

Delivery Modules

1.

Dynamic Badge Registry & Auto-Revocation

Onboarding TextInstitutional explanation (max 10 lines) covering continuous evaluation, access tiers, and auto-revocation triggers.
Revocation PipelineDetection → Onchain Invalidation → LVL 0 Downgrade → Quarantine → Audit Log → Notification → Conditional Reinstatement.
Canonical IdentityContract Address + Badge ID = unique identity. Display name is UX only - never use for validation.
Onchain EvaluatorsPluggable contracts evaluating: Success Rate, Volume, Uptime, Slippage, Security Flags.
2.

Dynamic Leaderboard & Aegis Score Classifier

Score FormulaAegis Score = Performance (37%) + Reliability (28%) - Risk Penalty + Contribution (10%)
Dynamic TiersPlatinum (95–100), Gold (85–94), Silver (70–84), Bronze (50–69), Unranked (<50)
Adjustment TriggersReal-time updates on: success rate drop, 5+ consecutive failures, slippage >500 BPS, security flag.
Frontend ColumnsRank, Agent, Badge, Aegis Score, Success %, Volume, Uptime, Status, Trend (7D).
3.

Contingency & Fallback for DeFi Protocols

Hybrid LogicAuto-Swap for technical failures. Supervised/Paused mode for security anomalies.
Dynamic Selectionfind_best_backup() queries Aegis Registry and promotes highest-score whitelisted agent.
Circuit BreakersLoss caps per epoch, slippage caps, time-locks for lower tiers, grace periods for temp oscillations.
Weighted AllocationCapital proportional to Aegis Score: allocation[i] = (score[i] / Σscores) * TVL
4.

Smart Alert System (Cost-Optimized)

Info (🔵)Score -10% → Discord/Telegram webhook. $0 cost. Continuous monitoring.
Warn (🟡)Timeout/Inoperative → Slack/PagerDuty. $0–$25/mo. Prepare intervention.
Critical (🔴)Auto-Swap Executed → Email + Onchain Event. ~$0. Validate takeover.
Emergency (🛑)No valid backup → SMS/Voice (Twilio). ~$0.50–$1.50/alert. Immediate human response.
5.

Integration SDK & Developer Tools

Smart Contract TemplatesReady-to-use modules: AgentManager, FallbackRouter, CircuitBreaker.
Event SchemaAgentRevokedEvent, FallbackActivatedEvent, ScoreChangeEvent - standard across protocols.
Developer DocsIntegration guides, hybrid fallback examples, security best practices.
Testnet & Stress TestsSimulated revocation, auto-swap, backup failure, volume spikes.

Suggested Timeline (10 Weeks)

Week 1–2
Core Scoring
Aegis Score engine, onchain evaluators, dynamic tier thresholds
Week 3–4
Auto-Revocation
Complete revocation flow, identity clarification, audit logging
Week 5–6
Leaderboard
Score visualization, trend indicators, real-time updates
Week 7–8
Fallback & Breakers
Hybrid swap logic, dynamic backup selector, safety limits
Week 9–10
Alerts & SDK Release
Off-chain indexer, debounce, tiered routing, docs, audit

Success KPIs (Phase 2)

  • 100% of badges and scores updated onchain in real-time
  • MTTR (Mean Time to Recovery) < 5 minutes for critical failures
  • Zero false emergency alerts after debounce logic is applied
  • 3+ protocols integrated with active hybrid fallback
  • Monitoring OPEX ≤ $15/month in normal operation
DocsSustainability
Sustainability

Sustainability & Incentives

Business Model

Aegis is designed to be self-sustaining: the better agents perform, the more value the ecosystem creates - for everyone.

During the hackathon and testnet phase, all Aegis services are 100% free. Economic mechanisms will be introduced gradually with community governance.

How Value Flows

Protocols

Pay small fee

Aegis Treasury

Collects & routes

Agent Rewards

High performers

Gold Agents

Maintain badges

Better Protocols

Reliable agents

Revenue Sources

SourceDescriptionStage
Protocol Integration Fee
Small % on verified executions - waived during hackathon/testnetPost-Mainnet
Premium Analytics
Advanced dashboards & alerting for enterprise usersRoadmap Q3
Grant-Funded Development
Ecosystem grants from Sui Foundation & ecosystem partnersActive

Agent Incentives

Gold Badge Agents

Gold Badge Agents

Priority access to high-value protocols + potential reward sharing from Aegis Treasury

Performance-Based

Fees and rewards scale with Aegis Score - bad actors earn nothing and face auto-revocation

No Pay-to-Play

Badges cannot be bought. Only earned via verifiable onchain performance - no shortcuts

Transparency Commitment

  • All fee structures and treasury movements are onchain and fully auditable by anyone
  • Governance proposals required for any changes to economic parameters - no unilateral updates
  • Public dashboard showing fee collection and distribution - coming Q2

Revenue alignment: The model is deliberately designed so that Aegis only earns when agents perform well and protocols benefit - charging for revocations or bad outcomes would misalign incentives.

Need Help?

© 2026 Aegis. Built for Sui Overflow Hackathon.

Not audited. Use at your own risk.