iToverDose/Software· 21 MAY 2026 · 08:06

How a constitutional AI agent can enforce strict trading rules

A new DeFi agent built on ElizaOS v2 and Nosana's GPU network enforces hard limits on trades through a programmable constitution, earning top marks in a global challenge for its trust-first approach.

DEV Community4 min read0 Comments

What if every trade your AI agent attempted had to pass a rule written in plain language—one that it could not bypass, no matter how advanced its algorithms became?

This isn’t about risk sliders or preference settings. It’s about a hard, synchronous block: if the rule isn’t in the constitution, the trade doesn’t happen. That principle guided the design of Nostra, a constitutional DeFi agent built on ElizaOS v2 and deployed across Nosana’s decentralized GPU network. In Nosana’s Fourth Builders’ Challenge—spanning 32 countries and 105 submissions—Nostra ranked sixth, with judges noting its "thoughtful approach to trust, compliance, and agent responsibility." After two weeks of debugging, that validation felt earned.

Let’s break down how the agent enforces constraints, where the architecture prioritizes safety, and why a hard rulebook matters more than ever in autonomous finance.

A Constitution for Every Trade

Most AI agents are defined by what they can do. Nostra is defined by what it cannot do.

During onboarding, users write a constitution: a structured document that becomes a set of typed rules. These rules are parsed into ConstitutionRule objects and stored in SQLite:

// src/types/constitution.ts
export interface ConstitutionRule {
  id: number;
  type: 'allocation_limit' | 'yield_threshold' | 'action_gate' | 'compute_budget' | 'custom';
  description: string;
  condition: {
    metric: string; // e.g., "sol_concentration", "yield_delta"
    operator: '<' | '>' | '<=' | '>=' | '==' | '!=';
    value: number;
    unit: string; // e.g., "percent", "apy_points"
  };
  action: 'block' | 'alert' | 'require_approval' | 'reduce_frequency';
}

The key detail: the rule’s description field is written verbatim to the Solana blockchain when triggered. No translation, no paraphrasing. What you write is what gets logged—immutably—on-chain. This transparency is critical for auditability and trust.

Three Gates Stand Between Your Agent and Execution

Nostra doesn’t let any action near your funds without passing three layers of compliance. All gates are enforced in a single higher-order function called withComplianceGate, which wraps only execution actions:

// src/index.ts — action registration
actions: [
  HandleStartCommand,
  ParseConstitutionAction,
  LogDecisionOnChain,
  withComplianceGate(ExecuteRotation), // Gate only applies to execution
  TriggerCrisisProtocol,
  AmendConstitution,
  // ...18+ total actions
],

Informational commands, constitution updates, and crisis responses remain outside the gate—ensuring you can always communicate with your agent, even when it’s frozen.

Here’s how the gate works (abridged):

// src/gates/with-compliance-gate.ts
function withComplianceGateHandler(handler: ActionHandler): ActionHandler {
  return async (runtime, message, state, options, callback) => {
    const agentState = AgentStateService.getState();

    // Gate 1: Crisis Protocol — block if frozen or resolving
    if (agentState.crisisStatus !== 'active') {
      await sendCallback(callback, `All actions are frozen. Crisis Protocol status: ${agentState.crisisStatus}.`);
      return;
    }

    // Gate 2: Constitutional compliance — live DB read every time
    const constitution = ConstitutionService.getActive(db);
    if (constitution && constitution.rules.length > 0) {
      const proposed = extractProposedAction(message);
      if (proposed) {
        const result = checkConstitutionalCompliance(constitution.rules, proposed);
        if (!result.passed) {
          // Write a NON_ACTION memo to Solana — even the block is recorded
          const memoText = buildMemoText({
            actionDescription: `NON_ACTION: ${result.violation}`,
            ruleReference: `Rule #${result.ruleRef}`,
            complianceStatus: 'Constitutional compliance: BLOCKED.',
          });
          await WalletService.writeMemo(memoText);
          await sendCallback(callback, `Action blocked: ${result.violation}`);
          return;
        }
      }
    }

    // Gate 3: Trust Ladder — block if still in Advisor Mode
    if (agentState.trustLadder === 'advisor') {
      await sendCallback(callback, `Advisory Mode. Current accuracy: ${agentState.accuracyScore.toFixed(1)}%`);
      return;
    }

    return handler(runtime, message, state, options, callback);
  };
}

One deliberate choice: ConstitutionService.getActive(db) performs a fresh database read on every action. No caching. The goal is immediate responsiveness—if you update your constitution mid-session, the next proposed action reflects the change instantly. Eventual consistency isn’t a philosophy Nostra endorses.

From Advisor to Executor: Earning the Right to Trade

Even with a perfect constitution, Nostra doesn’t start executing trades on day one. It begins in Advisor Mode, where it observes, analyzes, and suggests trades—but never acts. Every suggestion is sent to you for grading: thumbs up or down.

A TrustLadderEvaluator tracks your feedback:

// src/evaluators/trust-ladder-evaluator.ts
const MIN_SAMPLE_FOR_PROMOTION = 5; // Need ≥80% accuracy across ≥5 graded entries

if (accuracyScore >= 80 && total >= MIN_SAMPLE_FOR_PROMOTION) {
  const state = AgentStateService.getState();
  if (!state.promotionPending) {
    update['promotionPending'] = true; // Triggers promotion flow
  }
}

Once the agent hits 80% accuracy across at least five graded suggestions, it flags for promotion. You review and approve the upgrade to Executor Mode—the point at which it gains access to your actual funds. This calibration period wasn’t just a design afterthought; in practice, it became the core of the system, ensuring you’ve seen the agent’s decision-making style before trusting it with capital.

The future of autonomous finance isn’t just about smarter algorithms—it’s about enforceable constraints. Nostra’s approach shows that when rules are programmable, verifiable, and immutable, trust isn’t assumed—it’s earned. And in a space where mistakes are costly, that distinction may be the most valuable feature of all.

AI summary

Yapay zeka destekli DeFi ajanlarını anayasalarıyla donatmanın yolları. Nostra projesi, kurallarla sınırlandırılmış ve şeffaf bir sistemin nasıl tasarlanabileceğini gösteriyor.

Comments

00
LEAVE A COMMENT
ID #JKBAVH

0 / 1200 CHARACTERS

Human check

3 + 8 = ?

Will appear after editor review

Moderation · Spam protection active

No approved comments yet. Be first.