# Vigil integration guide

Vigil rates every Blend pool (V2 and v2.1) and DeFindex strategy on Stellar mainnet from 0 to 100 (higher is safer), grades it A to E, and says whether deposits should be allowed. Ratings are recomputed every 30 minutes, served as JSON, and signed into an on-chain registry that a smart-account policy (RiskGate) can enforce.

This file is for an AI coding assistant integrating Vigil into another project, and for the person briefing it. The interactive version, which writes a brief for your choices, is https://yieldpilot.org/integrate.

## Rules that hold on every path

- A deposit is allowed when the pool is rated, Vigil allows deposits (`eligibleForDeposit`) and its score is at least your minimum. The default minimum is 60.
- Grades: A is 80 and up, B 65 to 79, C 50 to 64, D 35 to 49, E under 35.
- Fail closed: a missing, unreadable or stale rating means no deposit. Withdrawals are never blocked by a rating.
- Do not use a minimum of 0: the registry signs 0 for pools Vigil holds back, so a minimum of 0 lets them through.
- There is no published SDK. The code below uses `@stellar/stellar-sdk` (checked with 15.1) or `soroban-sdk` (checked with 28) directly.

## Choose a path

| Path | What it is | Works on | Stops a bad deposit on-chain |
|---|---|---|---|
| 1. Show ratings | Read the JSON API | Mainnet pools, today. | No |
| 2. Check before depositing | Read the on-chain registry | Testnet registry; backend reads work for mainnet pools | Only where your code calls it |
| 3. Enforce on the wallet | Install RiskGate | Testnet only | Yes, for every signer |

## Addresses

| What | Value |
|---|---|
| Ratings API | `https://yieldpilot.org/api/ratings` |
| Run archive | `https://yieldpilot.org/api/ratings/runs` |
| RiskRegistry (testnet) | `CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6` |
| RiskGate (testnet) | `CD6BDS7R5K3IUCQSJUZUWAGLTR47EZOYEVCO5MPT7YGNBNQRHSNY5VMS` |
| Rated testnet demo pool (YieldPilot's) | `CBI7WAUQ4NPQFZW4C3MDSVFAZJWV3RCLZSTTMA5OZ6BTPEQMOZZNSZ3Z` |
| RPC | `https://soroban-testnet.stellar.org` |
| Network passphrase | `Test SDF Network ; September 2015` |

## 1. Show ratings

- **Gives:** Every Blend pool and DeFindex strategy on mainnet with its grade, score, reasons and whether Vigil allows deposits. Use it to label pools in your app or to drop weak ones before your backend picks one.
- **Does not:** Nothing on-chain stops a deposit. If your backend has a bug or its key is stolen, money can still reach a weak pool.
- **Effort:** Hours. One HTTP call, no keys, open to browsers (CORS).
- **Works on:** Mainnet pools, today.
- **You trust:** yieldpilot.org's server. Every run's inputs are archived, so anyone can recompute a rating and check it.

- `GET https://yieldpilot.org/api/ratings`: no key, CORS open. Top level: `engineVersion`, `computedAt` (unix seconds), `stale` (true when the last refresh failed), `ratings[]`.
- Each rating: `poolId`, `name`, `protocol` (blend | defindex), `grade` (A to E, or NR for not rated), `score` (0 to 100, higher is safer, null when NR), `eligibleForDeposit`, `reasons[]`, `hardRules[]`, `tvlUsd`, `yields[]`.
- A deposit is allowed when the pool is rated, `eligibleForDeposit` is true and `score` is at least the minimum. This is the same rule RiskGate enforces on-chain.
- Every run's inputs are archived for 90 days at `https://yieldpilot.org/api/ratings/runs`, so a rating can be recomputed and checked.

File: vigil.ts (server or browser)

```ts
// Vigil pool ratings from the public API. Cache the response for 5 minutes or more:
// ratings are recomputed every 30 minutes.
export type VigilRating = {
  poolId: string;               // Blend pool or DeFindex strategy contract id (mainnet)
  name: string;
  grade: "A" | "B" | "C" | "D" | "E" | "NR";
  score: number | null;         // 0..100, higher is safer; null when not rated
  eligibleForDeposit: boolean;  // false when a hard rule holds the pool back
  reasons: string[];
  hardRules: string[];
};

export const MIN_SCORE = 60;
export const MAX_AGE_SECS = 7200;

export async function fetchVigilRatings(): Promise<{ computedAt: number; ratings: Map<string, VigilRating> }> {
  const res = await fetch("https://yieldpilot.org/api/ratings");
  if (!res.ok) throw new Error(`Vigil API HTTP ${res.status}`);
  const body = (await res.json()) as { computedAt: number; ratings: VigilRating[] };
  return { computedAt: body.computedAt, ratings: new Map(body.ratings.map((r) => [r.poolId, r])) };
}

// The same rule RiskGate enforces on-chain. Anything unknown, unrated, held back,
// under the minimum or too old is refused: fail closed.
export function depositAllowed(r: VigilRating | undefined, computedAt: number, nowSecs = Date.now() / 1000): boolean {
  if (!r || r.score === null || !r.eligibleForDeposit) return false;
  if (nowSecs - computedAt > MAX_AGE_SECS) return false;
  return r.score >= MIN_SCORE;
}
```

## 2. Check before depositing

- **Gives:** The signed score your deposit code checks before it moves money: read from the RiskRegistry contract, either by your backend over RPC or by your own Soroban contract.
- **Does not:** It guards only the code paths that call it; a deposit sent another way is not checked. The registry is on testnet, so a mainnet contract cannot call it yet.
- **Effort:** A day or two, tests included.
- **Works on:** Registry on testnet. It holds the scores of the mainnet pools, so a backend can read them today; contract-to-contract checks work on testnet only.
- **You trust:** The registered publishers' signatures (one today, M-of-N by design).

- RiskRegistry: `CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6` on Stellar testnet (RPC https://soroban-testnet.stellar.org, passphrase "Test SDF Network ; September 2015").
- `get_rating(pool: Address) -> Option<Rating>`, with `Rating { score: u32, publishers: u32, timestamp: u64 }`: the median of the fresh publisher submissions, and the oldest of their timestamps.
- Today: 1 publisher, threshold 1; a submission counts for 7200 s and a new one is signed every 30 minutes. If publishing stops, ratings go stale and checks fail closed.
- The registry holds a pool's score when Vigil allows deposits, 0 when a hard rule holds the pool back, and nothing (None) for a pool it does not rate.
- Pools are keyed by their mainnet contract ids, plus YieldPilot's testnet demo pool `CBI7WAUQ4NPQFZW4C3MDSVFAZJWV3RCLZSTTMA5OZ6BTPEQMOZZNSZ3Z`, which carries the rating of the mainnet pool YieldPilot holds.
- A Soroban contract can call the registry only on the same network: testnet today. A mainnet contract cannot call it yet; until a mainnet registry exists, check from the backend for mainnet.

### From a backend (TypeScript)

File: vigil-registry.ts (server; checked with @stellar/stellar-sdk 15.1)

```ts
import { Account, Address, BASE_FEE, Contract, Keypair, Networks, TransactionBuilder, rpc, scValToNative } from "@stellar/stellar-sdk";

const RPC_URL = "https://soroban-testnet.stellar.org";
const REGISTRY = "CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6"; // Vigil RiskRegistry (testnet)
export const MIN_SCORE = 60;
export const MAX_AGE_SECS = 7200;

const server = new rpc.Server(RPC_URL);

export type Rating = { score: number; publishers: number; timestamp: bigint };

// get_rating is a read: the transaction is simulated, never sent, so any
// account (even an unfunded random one) works as the source.
export async function getRating(pool: string): Promise<Rating | null> {
  const source = new Account(Keypair.random().publicKey(), "0");
  const tx = new TransactionBuilder(source, { fee: BASE_FEE, networkPassphrase: Networks.TESTNET })
    .addOperation(new Contract(REGISTRY).call("get_rating", new Address(pool).toScVal()))
    .setTimeout(30)
    .build();
  const sim = await server.simulateTransaction(tx);
  if (rpc.Api.isSimulationError(sim)) throw new Error(`get_rating failed: ${sim.error}`);
  const v = sim.result?.retval ? scValToNative(sim.result.retval) : null;
  return v ? { score: Number(v.score), publishers: Number(v.publishers), timestamp: BigInt(v.timestamp) } : null;
}

// RiskGate's rule, in order: a rating exists (4114), it is fresh (4116), it meets
// the minimum (4115). Call it before every deposit; a thrown error means no deposit.
export async function depositAllowed(pool: string, nowSecs = BigInt(Math.floor(Date.now() / 1000))): Promise<{ allowed: boolean; reason: string }> {
  const r = await getRating(pool);
  if (!r) return { allowed: false, reason: "no rating (4114)" };
  if (r.timestamp > nowSecs || nowSecs - r.timestamp > BigInt(MAX_AGE_SECS)) return { allowed: false, reason: "rating too old (4116)" };
  if (r.score < MIN_SCORE) return { allowed: false, reason: `score ${r.score} < ${MIN_SCORE} (4115)` };
  return { allowed: true, reason: `score ${r.score}` };
}
```

### From your own Soroban contract (Rust)

File: src/vigil.rs (your Soroban contract; checked with soroban-sdk 28)

```rust
use soroban_sdk::{contractclient, contracterror, contracttype, panic_with_error, Address, Env};

/// Vigil RiskRegistry (testnet): CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6
/// Store it in your contract's config rather than hard-coding it.

/// Copied from Vigil's vigil-interface crate. Field names and types must match exactly.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Rating {
    pub score: u32,      // median of the fresh submissions, 0..=100, higher is safer
    pub publishers: u32, // how many publishers' submissions were counted
    pub timestamp: u64,  // the oldest counted submission, unix seconds
}

#[contractclient(name = "RiskRegistryClient")]
pub trait RiskRegistry {
    fn get_rating(env: Env, pool: Address) -> Option<Rating>;
}

#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum RiskError {
    RatingUnavailable = 1,
    RatingStale = 2,
    ScoreTooLow = 3,
}

pub const MIN_SCORE: u32 = 60;
pub const MAX_AGE_SECS: u64 = 7200;

/// Call before your contract moves funds into `pool`; withdrawals should not call it.
/// A failed registry call reverts the deposit too: fail closed.
pub fn require_rated(env: &Env, registry: &Address, pool: &Address) {
    let rating = RiskRegistryClient::new(env, registry)
        .get_rating(pool)
        .unwrap_or_else(|| panic_with_error!(env, RiskError::RatingUnavailable));
    let now = env.ledger().timestamp();
    if rating.timestamp > now || now - rating.timestamp > MAX_AGE_SECS {
        panic_with_error!(env, RiskError::RatingStale);
    }
    if rating.score < MIN_SCORE {
        panic_with_error!(env, RiskError::ScoreTooLow);
    }
}
```

## 3. Enforce on the wallet

- **Gives:** A policy on your users' OpenZeppelin smart accounts. A deposit into a pool under your minimum fails on-chain, whoever signs it: your agent, a bug, or a stolen key. Withdrawals always work.
- **Does not:** It needs OpenZeppelin smart accounts, and each account's owner has to sign the install. It knows Blend's pool calls (submit, claim) and token transfers and refuses every other function on the rule it guards, so it fits Blend pool rules, not DeFindex vaults.
- **Effort:** A few days, plus one signature from each user.
- **Works on:** Testnet only. The one rated testnet pool is YieldPilot's demo pool; a deposit into any other testnet pool fails closed (no rating, #4114).
- **You trust:** The same publishers as the registry, enforced by the account itself.

- RiskGate: `CD6BDS7R5K3IUCQSJUZUWAGLTR47EZOYEVCO5MPT7YGNBNQRHSNY5VMS` on testnet, an OpenZeppelin smart-account policy shared by every account; no admin, no upgrade.
- Install with `add_policy(context_rule_id, RISKGATE, params)` on the smart account (the owner authorizes), or pass it in the policies map of `add_context_rule`.
- On a pool rule it allows only `submit` / `submit_with_allowance` with from = spender = to = the smart account and request types 0 to 3, and `claim` to the account itself. Any request of type 0 (Supply) or 2 (SupplyCollateral) needs a fresh rating at or above `min_score`; withdrawals are never rating-gated.
- On a token rule it allows only `transfer` from the smart account to an address in `allowed_recipients`.
- Every other function on the guarded rule is refused (#4107), so RiskGate fits Blend pool rules; it does not know DeFindex vault calls.
- RiskRegistry: `CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6` on Stellar testnet (RPC https://soroban-testnet.stellar.org, passphrase "Test SDF Network ; September 2015").
- `get_rating(pool: Address) -> Option<Rating>`, with `Rating { score: u32, publishers: u32, timestamp: u64 }`: the median of the fresh publisher submissions, and the oldest of their timestamps.
- Today: 1 publisher, threshold 1; a submission counts for 7200 s and a new one is signed every 30 minutes. If publishing stops, ratings go stale and checks fail closed.
- The registry holds a pool's score when Vigil allows deposits, 0 when a hard rule holds the pool back, and nothing (None) for a pool it does not rate.
- Pools are keyed by their mainnet contract ids, plus YieldPilot's testnet demo pool `CBI7WAUQ4NPQFZW4C3MDSVFAZJWV3RCLZSTTMA5OZ6BTPEQMOZZNSZ3Z`, which carries the rating of the mainnet pool YieldPilot holds.
- On testnet, the only rated pool you can call is YieldPilot's demo pool `CBI7WAUQ4NPQFZW4C3MDSVFAZJWV3RCLZSTTMA5OZ6BTPEQMOZZNSZ3Z`; a deposit into any other testnet pool fails with #4114.
- Built on stellar-accounts 0.8 and tested against the OpenZeppelin smart account 0.7 wasm.

File: riskgate.ts (where you build smart-account transactions; checked with @stellar/stellar-sdk 15.1)

```ts
import { Address, Contract, xdr } from "@stellar/stellar-sdk";

const RISKGATE = "CD6BDS7R5K3IUCQSJUZUWAGLTR47EZOYEVCO5MPT7YGNBNQRHSNY5VMS"; // Vigil RiskGate policy (testnet), shared, no admin
const REGISTRY = "CB4LXLCCD7YDND5FBVXPKPHUQMF7JFSDRVXHG7ZZTWWNPJ6WDCXDNDF6"; // Vigil RiskRegistry (testnet)
export const MIN_SCORE = 60;
export const MAX_AGE_SECS = 7200;

const entry = (key: string, val: xdr.ScVal) => new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val });
const u64 = (n: number) => xdr.ScVal.scvU64(xdr.Uint64.fromString(String(n)));

// RiskGateParams is a contract struct: an ScMap whose keys MUST stay in this sorted order.
// Pool rule (CallContract(pool)): deposits need a fresh rating >= MIN_SCORE.
export function poolRuleParams(): xdr.ScVal {
  return xdr.ScVal.scvMap([
    entry("allowed_recipients", xdr.ScVal.scvVec([])),
    entry("max_age_secs", u64(MAX_AGE_SECS)),
    entry("min_score", xdr.ScVal.scvU32(MIN_SCORE)),
    entry("registry", new Address(REGISTRY).toScVal()),
  ]);
}

// Token rule (CallContract(USDC)): transfer may only pay these contracts, e.g. your pools.
export function tokenRuleParams(allowedRecipients: string[]): xdr.ScVal {
  return xdr.ScVal.scvMap([
    entry("allowed_recipients", xdr.ScVal.scvVec(allowedRecipients.map((a) => new Address(a).toScVal()))),
    entry("max_age_secs", u64(0)),
    entry("min_score", xdr.ScVal.scvU32(0)),
    entry("registry", xdr.ScVal.scvVoid()),
  ]);
}

// add_policy(context_rule_id, policy, install_param) on the user's OpenZeppelin smart account.
// contextRuleId is the rule your agent signs under. The account's owner must authorize this call.
export function installRiskGateOp(smartAccount: string, contextRuleId: number, params: xdr.ScVal): xdr.Operation {
  return new Contract(smartAccount).call("add_policy", xdr.ScVal.scvU32(contextRuleId), new Address(RISKGATE).toScVal(), params);
}

// Find a RiskGate refusal in a simulation or submit error, e.g. "Error(Contract, #4115)".
export function riskGateError(message: string): number | null {
  const m = message.match(/Error\(Contract, #(41\d\d)\)/);
  return m ? Number(m[1]) : null;
}
```

### RiskGate errors

A refused call fails with `Error(Contract, #code)`.

| Code | Name | Meaning |
|---|---|---|
| 4100 | NotInstalled | no RiskGate params for this smart account and rule |
| 4101 | AlreadyInstalled | RiskGate is already on this rule |
| 4102 | InvalidParams | min_score over 100, a minimum without a registry, or a registry with max_age_secs 0 |
| 4103 | OnlyCallContract | RiskGate attaches only to CallContract rules |
| 4104 | NoSigners | not every signer of the rule authenticated |
| 4105 | ContextNotAllowed | contract creation is refused |
| 4106 | WrongContract | the called contract is not the rule's target |
| 4107 | FunctionNotAllowed | only submit, submit_with_allowance, claim and transfer pass |
| 4108 | BadArgs | the arguments do not decode as Blend's or the token's |
| 4109 | AccountMismatch | from, spender and to must all be the smart account |
| 4110 | EmptyRequests | submit with no requests |
| 4111 | RequestTypeNotAllowed | only supply and withdraw (request types 0 to 3) |
| 4112 | NegativeAmount | a negative amount |
| 4113 | RecipientNotAllowed | a transfer to an address not in allowed_recipients |
| 4114 | RatingUnavailable | the registry has no rating for the pool |
| 4115 | ScoreTooLow | the pool's rating is under the account's minimum |
| 4116 | RatingStale | the pool's rating is older than max_age_secs |

## Limits today

- The registry and RiskGate are on testnet. A mainnet contract cannot call them yet; on mainnet, read the API or the testnet registry from your backend.
- One publisher signs the ratings (threshold 1). The registry takes up to 16 and returns their median.
- Ratings depend on Vigil's engine version; a change of method is announced in the methodology's version history.

## Check a rating yourself

- The method: https://github.com/Goguzgungor/yieldpilot/blob/feat/yieldseeker-mvp/docs/vigil/methodology.md
- Contract reference (every function, event and encoding): https://github.com/Goguzgungor/yieldpilot/blob/feat/yieldseeker-mvp/contracts/README.md
- Each run's full input is at `https://yieldpilot.org/api/ratings/runs?at=<computedAt>`; `scripts/vigil-verify.ts` in the repository recomputes every hash and re-rates every pool from it.
