/** * @module registries/fairscale * @description FairScale reputation aggregation registry. * * Wraps both FairScale REST APIs: * - **Agent & Credit API** (`agent-api.fairscale.xyz`) — agent trust score, * trust gate, batch scoring, composable score, agent profile, score * history, directory, leaderboard, credit assessment. * - **Human Score API** (`api.fairscale.xyz`) — human wallet fingerprint, * FairScore, on-chain features, badges. * * The killer feature is {@link FairScaleRegistry.aggregate}: it merges * SAP's **on-chain** reputation (`AgentAccount.reputationScore` + * feedback count + activity signals) with FairScale's **off-chain** * trust score into a single normalised, weight-tunable signal. Apps * therefore get a multi-source reputation rather than relying on either * registry alone. * * Zero runtime dependencies — uses native `fetch` (Node ≥18, browsers, * Edge runtimes). Auth via `fairkey` (or `X-Api-Key` for credit). * * @category Registries * @since v0.11.0 * * @example Standalone usage (just the FairScale wrapper) * ```ts * const fs = client.fairscale; * const score = await fs.score(agentWallet); * const allowed = await fs.trustGate(agentWallet, { minScore: 60 }); * const profile = await fs.agentProfile(agentWallet); * const human = await fs.human.score(userWallet); * ``` * * @example Aggregated reputation (SAP + FairScale) * ```ts * const merged = await client.fairscale.aggregate(agentWallet, { * weights: { sap: 0.4, fairscale: 0.6 }, * require: { sapMinFeedbacks: 1 }, * }); * console.log(merged.combined.score, merged.combined.tier); * ``` */ import type { PublicKey } from "@solana/web3.js"; import { SapError } from "../errors"; import type { SapProgram } from "../modules/base"; /** * @name FairScaleError * @description Thrown for any non-2xx response from a FairScale endpoint * or for client-side validation failures (missing API key, invalid * weights, etc.). * @category Errors * @since v0.11.0 * @extends SapError */ export declare class FairScaleError extends SapError { /** HTTP status from FairScale (0 for client-side errors). */ readonly status: number; /** FairScale error code from the response body, if any. */ readonly upstreamCode?: string; constructor(message: string, status: number, upstreamCode?: string); } /** * @name FAIRSCALE * @description Public, documented constants for the FairScale platform. * Verified against the docs at https://docs.fairscale.xyz on 2026-04-17. * Use these instead of hard-coding strings — guarantees consistency across * the SDK and any consumer code. * @category Registries * @since v0.11.0 */ export declare const FAIRSCALE: Readonly<{ /** Agent & Credit API host. */ readonly AGENT_API: "https://agent-api.fairscale.xyz"; /** Human Score API host. */ readonly HUMAN_API: "https://api.fairscale.xyz"; /** Default request timeout matching the official SDK (10s). */ readonly DEFAULT_TIMEOUT_MS: 10000; /** Server-side cache TTL on every endpoint (15 min). */ readonly CACHE_TTL_SECONDS: number; /** Max wallets per `POST /v1/score/batch` request. */ readonly BATCH_MAX_WALLETS: 25; /** API key prefix. */ readonly API_KEY_PREFIX: "zpka_"; /** Default `min_score` for `/v1/trust-gate`. */ readonly DEFAULT_TRUST_GATE_MIN_SCORE: 40; /** x402 micropayment metadata (Solana mainnet). */ readonly X402: Readonly<{ /** USDC mint on Solana mainnet. */ USDC_MINT: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; /** Wallet receiving x402 payments. */ PAY_TO: "fairAUEuR1SCcHL254Vb3F3XpUWLruJ2a11f6QfANEN"; /** Solana mainnet x402 network slug. */ NETWORK: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"; /** Facilitator host. */ FACILITATOR: "https://x402.dexter.cash"; /** Price in USDC base units (micro-USDC) per agent / trust call. */ PRICE_AGENT_USDC_BASE: 5000; /** Price in USDC base units (micro-USDC) per credit assessment. */ PRICE_CREDIT_USDC_BASE: 500000; /** Default x402 settlement timeout (seconds). */ MAX_TIMEOUT_SECONDS: 60; }>; /** Documented agent-tier ranges (inclusive). */ readonly AGENT_TIER_RANGES: Readonly<{ readonly bronze: readonly [0, 39]; readonly silver: readonly [40, 54]; readonly gold: readonly [55, 69]; readonly platinum: readonly [70, 84]; readonly diamond: readonly [85, 100]; }>; /** Documented credit `risk_band` ranges (inclusive). */ readonly RISK_BAND_RANGES: Readonly<{ readonly decline: readonly [0, 24]; readonly deep_subprime: readonly [25, 44]; readonly subprime: readonly [45, 59]; readonly near_prime: readonly [60, 74]; readonly prime: readonly [75, 100]; }>; /** Plan tiers — daily request quota / per-minute rate limit. */ readonly PLAN_QUOTAS: Readonly<{ readonly free: { readonly dailyRequests: 1000; readonly rpm: 10; }; readonly builder: { readonly dailyRequests: 20000; readonly rpm: 100; }; readonly scale: { readonly dailyRequests: 50000; readonly rpm: 300; }; readonly pro: { readonly dailyRequests: 100000; readonly rpm: 600; }; }>; /** Pillar weights for `/v1/score/ai` presets, exactly as documented. */ readonly PRESET_WEIGHTS: Readonly<{ readonly default: { readonly verification: 0.3; readonly wallet_history: 0.25; readonly work_history: 0.1; readonly network_quality: 0.25; readonly peer_reputation: 0.1; }; readonly trust_focused: { readonly verification: 0.5; readonly wallet_history: 0.2; readonly work_history: 0.1; readonly network_quality: 0.1; readonly peer_reputation: 0.1; }; readonly work_focused: { readonly verification: 0.2; readonly wallet_history: 0.15; readonly work_history: 0.4; readonly network_quality: 0.15; readonly peer_reputation: 0.1; }; readonly defi: { readonly verification: 0.25; readonly wallet_history: 0.3; readonly work_history: 0.1; readonly network_quality: 0.25; readonly peer_reputation: 0.1; }; readonly hiring: { readonly verification: 0.35; readonly wallet_history: 0.15; readonly work_history: 0.25; readonly network_quality: 0.15; readonly peer_reputation: 0.1; }; }>; /** Allowed sort fields for `/v1/directory` and `/v1/leaderboard`. */ readonly DIRECTORY_SORT_FIELDS: readonly ["agent_fairscore", "verification", "wallet_history", "work_history", "network_quality", "peer_reputation", "reliability", "track_record", "economic_stake", "ecosystem"]; /** Documented machine-readable error codes. */ readonly ERROR_CODES: readonly ["missing_wallet", "invalid_wallet", "invalid_preset", "weights_must_sum_to_1", "missing_weights", "too_many_wallets", "daily_limit_exceeded", "upstream_error"]; }>; /** * Agent / Human tier — documented ranges: * `bronze 0–39 · silver 40–54 · gold 55–69 · platinum 70–84 · diamond 85–100`. */ export type FairScaleTier = "bronze" | "silver" | "gold" | "platinum" | "diamond"; /** Built-in weight presets for `GET /v1/score/ai`. */ export type FairScalePreset = keyof typeof FAIRSCALE.PRESET_WEIGHTS; /** Task profiles accepted by `/v1/score` and `/v1/trust-gate`. */ export type FairScaleTask = "defi_execution" | "trust_focused" | "work_focused" | "hiring"; /** * `recommendation` block returned by `/v1/score` — qualitative tier * with a label and color hint for UI rendering. */ export type FairScaleRecommendationTier = "trusted" | "caution" | "high_risk" | "unverified"; /** Sort fields accepted by `/v1/directory` and `/v1/leaderboard`. */ export type FairScaleDirectorySort = (typeof FAIRSCALE.DIRECTORY_SORT_FIELDS)[number]; /** Five agent-scoring pillars (0–100 each). */ export interface FairScalePillars { readonly verification: number; readonly wallet_history: number; readonly work_history: number; readonly network_quality: number; readonly peer_reputation: number; } /** Behavioural badge emitted by both agent and human endpoints. */ export interface FairScaleBadge { readonly id: string; readonly label: string; readonly description?: string; readonly tier?: "bronze" | "silver" | "gold" | "platinum"; } /** Recommended action returned by the human `/score` endpoint. */ export interface FairScaleAction { readonly id: string; readonly label: string; readonly description: string; readonly priority: "high" | "medium" | "low"; readonly cta: string; } /** Verification flags returned in `score.signals`. */ export interface FairScaleSignals { readonly fairscore_base?: number; readonly said_score?: number; readonly said_trust_tier?: FairScaleTier; readonly attestations?: number; readonly is_registered?: boolean; readonly is_verified?: boolean; readonly is_said_agent?: boolean; readonly is_erc8004?: boolean; readonly [k: string]: unknown; } /** Description-alignment block in `/v1/score` response. */ export interface FairScaleDescriptionAlignment { readonly bonus: number; readonly label: "verified" | "partial" | "unverified" | string; readonly matched: ReadonlyArray; readonly claimed: ReadonlyArray; } /** Red flag returned in `/v1/score` response. */ export interface FairScaleRedFlag { readonly type: string; readonly reason: string; readonly severity?: "critical" | "warning" | "info"; } /** Verifications block in `/v1/score` response. */ export interface FairScaleVerifications { readonly said_onchain?: boolean; readonly erc8004?: boolean; readonly sati?: boolean; readonly liveness?: boolean; readonly x402?: boolean; readonly [k: string]: boolean | undefined; } /** Standard response meta envelope. */ export interface FairScaleMeta { readonly scored_at?: string; readonly from_cache?: boolean; readonly cached?: boolean; readonly provider: string; readonly version?: string; readonly layer?: string; readonly latency_ms?: number; readonly amount_assessed?: number; } /** Response of `GET /v1/score`. */ export interface AgentScoreResult { readonly wallet: string; readonly score: number; readonly tier: FairScaleTier; readonly recommendation?: { readonly tier: FairScaleRecommendationTier; readonly label: string; readonly color: "green" | "yellow" | "red" | "gray" | string; }; readonly pillars: FairScalePillars; readonly signals?: FairScaleSignals; readonly red_flags?: ReadonlyArray; readonly badges?: ReadonlyArray; readonly description_alignment?: FairScaleDescriptionAlignment; readonly work_history_sources?: ReadonlyArray; readonly verifications?: FairScaleVerifications; readonly meta?: FairScaleMeta; /** Present only on per-wallet entries inside a batch response. */ readonly error?: string; } /** Response of `GET /v1/trust-gate`. */ export interface TrustGateResult { readonly wallet: string; readonly allowed: boolean; readonly score: number; readonly reason: "score_above_threshold" | "score_below_threshold" | "missing_verification" | string; readonly meta?: FairScaleMeta; } /** Response of `POST /v1/score/batch`. */ export interface BatchScoreResult { readonly total: number; readonly scored: number; readonly results: ReadonlyArray; readonly meta?: FairScaleMeta; } export interface ScoreOptions { /** Apply a built-in scoring profile. */ readonly task?: FairScaleTask; /** Override the API key for this call. */ readonly apiKey?: string; /** Per-call timeout (ms). Defaults to client default. */ readonly timeoutMs?: number; /** AbortSignal for cancellation. */ readonly signal?: AbortSignal; } export interface TrustGateOptions extends ScoreOptions { /** Minimum score to pass (0–100). Default 40. */ readonly minScore?: number; /** Require at least one registry verification. */ readonly requireVerification?: boolean; } export interface ScoreAiOptions extends ScoreOptions { /** Use a built-in preset. Mutually exclusive with `weights`. */ readonly preset?: FairScalePreset; /** Custom pillar weights — must sum to 1.0 ± 0.02. */ readonly weights?: FairScalePillars; } export interface DirectoryOptions extends ScoreOptions { readonly page?: number; /** Default 25, max 100. */ readonly limit?: number; readonly sort?: FairScaleDirectorySort; readonly minScore?: number; readonly verifiedOnly?: boolean; readonly recommendation?: FairScaleRecommendationTier; readonly source?: "said" | "erc8004" | "sati"; readonly search?: string; readonly hasAttestations?: boolean; } /** Single entry returned by `/v1/directory.results[]`. */ export interface DirectoryEntry { readonly wallet: string; readonly name?: string; readonly description?: string; readonly score: number; readonly tier: FairScaleTier; readonly pillars?: FairScalePillars; readonly recommendation?: AgentScoreResult["recommendation"]; readonly verifications?: FairScaleVerifications; readonly source?: "said" | "erc8004" | "sati"; readonly [k: string]: unknown; } /** Response of `GET /v1/directory`. */ export interface DirectoryResult { readonly total: number; readonly page: number; readonly limit: number; readonly results: ReadonlyArray; readonly meta?: FairScaleMeta; } /** Response of `GET /v1/leaderboard`. */ export interface LeaderboardResult { readonly metric: string; readonly limit: number; readonly results: ReadonlyArray; readonly meta?: FairScaleMeta; } /** Response of `GET /v1/score-history`. */ export interface ScoreHistoryResult { readonly wallet: string; readonly history: ReadonlyArray<{ readonly scored_at: string; readonly score: number; readonly tier?: FairScaleTier; }>; readonly meta?: FairScaleMeta; } export interface CreditOptions extends ScoreOptions { /** Loan amount in USD. Default 1000. */ readonly amount?: number; /** Bypass 15-min cache. SDK accepts boolean — wire-format is `0|1`. */ readonly nocache?: boolean; /** Optional social-proof header forwarded as `x-social-identity`. */ readonly socialIdentity?: string; } /** Lending terms inside the credit underwriting block. */ export interface CreditLendingTerms { readonly recommendation: string; readonly suggested_apr_range: { readonly low: number; readonly high: number; }; readonly collateral_ratio: number; readonly collateral_note: string; readonly max_credit_line: number; readonly max_term_days: number; readonly identity_level: "kyc" | "strong" | "said" | "matrica" | "partial" | "none"; readonly identity_enhanced: boolean; } /** Risk flag inside credit underwriting. */ export interface CreditRiskFlag { readonly type: "critical" | "warning" | "positive"; readonly signal: string; readonly detail: string; } /** Underwriting block. */ export interface CreditUnderwriting { readonly opinion: string; readonly lending_terms: CreditLendingTerms; readonly risk_flags: ReadonlyArray; readonly data_confidence?: Record; } /** Confidence block. */ export interface CreditConfidence { readonly score: number; readonly level: "high" | "medium" | "low"; readonly summary: string; readonly limitations: ReadonlyArray; } /** Five credit pillars. */ export interface CreditPillars { readonly financial_position: { readonly score: number; }; readonly credit_history: { readonly score: number; }; readonly income_capacity: { readonly score: number; }; readonly behavioural: { readonly score: number; }; readonly identity_trust: { readonly score: number; }; } /** Attestation envelope (HMAC-SHA256 signed proof). */ export interface CreditAttestation { readonly type: "signed_response" | string; readonly payload_hash: string; readonly payload_fields: string; readonly note?: string; } /** Response of `GET /v1/credit`. */ export interface CreditResult { readonly wallet: string; readonly fairscore: number; readonly fairscore_tier: FairScaleTier | "unverified"; readonly credit_score: number; readonly risk_band: "prime" | "near_prime" | "subprime" | "deep_subprime" | "decline"; readonly confidence: CreditConfidence; readonly underwriting: CreditUnderwriting; readonly credit_pillars: CreditPillars; readonly affordability?: Record; readonly trust_pillars?: Record; readonly credit_data?: Record; readonly flags?: Record; readonly attestation: CreditAttestation; readonly meta?: FairScaleMeta; } /** * 15 on-chain features returned by `/score`. Field names and units match * https://docs.fairscale.xyz/docs/api-score#features exactly. */ export interface HumanScoreFeatures { readonly native_sol_percentile: number; readonly major_percentile_score: number; readonly stable_percentile_score: number; readonly lst_percentile_score: number; readonly net_sol_flow_30d: number; readonly median_hold_days: number; readonly conviction_ratio: number; readonly no_instant_dumps: 0 | 1; readonly tx_count: number; readonly active_days: number; readonly median_gap_hours: number; readonly tempo_cv: number; readonly burst_ratio: number; readonly platform_diversity: number; readonly wallet_age_score: number; } /** Response of `GET /score` (Human Score API). */ export interface HumanScoreResult { readonly wallet: string; /** Final blended score (0–100) — `0.50·base + 0.20·social + 0.30·peer`. */ readonly fairscore: number; /** Raw on-chain neural-network score (features only). */ readonly fairscore_base: number; /** Social reputation (0 if no X handle linked). */ readonly social_score: number; /** Peer-vouch score (0 if no vouches received). */ readonly peer_score: number; readonly verified_human: boolean; readonly tier: FairScaleTier; readonly badges: ReadonlyArray; readonly actions: ReadonlyArray; readonly features: HumanScoreFeatures; /** Present only on cache-hit responses. */ readonly cached?: boolean; readonly timestamp: string; } export interface AggregatedReputation { /** Agent wallet. */ readonly wallet: string; /** SAP on-chain reputation snapshot (null if agent not registered). */ readonly sap: { readonly registered: boolean; /** 0–100 SAP `reputationScore` (null if no feedback yet). */ readonly score: number | null; readonly totalFeedbacks: number; readonly totalCallsServed: string; readonly isActive: boolean; }; /** FairScale snapshot (null if FairScale lookup failed). */ readonly fairscale: AgentScoreResult | null; /** Final blended signal. */ readonly combined: { /** 0–100 weighted score. */ readonly score: number; /** Bucket derived from `score`: low <40, medium <60, high <80, elite ≥80. */ readonly tier: "low" | "medium" | "high" | "elite"; /** * Confidence in the blended signal (0–1). Penalises: * - Missing source (only one of the two responded) * - Low SAP feedback count * - FairScale `from_cache: true` */ readonly confidence: number; /** Effective weights actually applied (after missing-source rebalance). */ readonly weights: { sap: number; fairscale: number; }; /** Reasons that affected the score (red flags, gates, etc.). */ readonly notes: ReadonlyArray; }; readonly meta: { readonly provider: "SAP+FairScale"; readonly computedAt: string; }; } export interface AggregateOptions extends ScoreOptions { /** * Weights applied to each source. Defaults to `{ sap: 0.5, fairscale: 0.5 }`. * Must sum to 1.0 ± 0.01. If one source is missing, the present source's * weight is renormalised to 1.0 (and `confidence` is reduced). */ readonly weights?: { sap: number; fairscale: number; }; /** Minimum SAP feedbacks required for SAP to count (else SAP weight → 0). */ readonly require?: { sapMinFeedbacks?: number; }; /** * If true, throws when both sources are unavailable. Default `false` * (returns `combined.score = 0`, `confidence = 0`). */ readonly strict?: boolean; } export interface FairScaleConfig { /** API key (or read from env `FAIRSCALE_API_KEY`). */ readonly apiKey?: string; /** Override agent-api base URL. */ readonly baseUrl?: string; /** Override human-api base URL. */ readonly humanBaseUrl?: string; /** Default request timeout (ms). Default 10_000. */ readonly timeoutMs?: number; /** Custom fetch implementation (for tests / Edge proxies). */ readonly fetch?: typeof fetch; } /** * @name FairScaleRegistry * @description High-level FairScale client + SAP reputation aggregator. * Exposed lazily as `client.fairscale`. * @category Registries * @since v0.11.0 */ export declare class FairScaleRegistry { #private; constructor(program: SapProgram, config?: FairScaleConfig); /** Human Score API namespace (`client.fairscale.human.*`). */ get human(): HumanScoreNamespace; /** * @description `GET /v1/score` — composite trust score. */ score(agent: PublicKey | string, opts?: ScoreOptions): Promise; /** * @description `GET /v1/trust-gate` — binary allow/deny. */ trustGate(agent: PublicKey | string, opts?: TrustGateOptions): Promise; /** * @description `POST /v1/score/batch` — up to 25 wallets per call. * Splits larger inputs into chunks of 25 and merges results. */ scoreBatch(agents: ReadonlyArray, opts?: ScoreOptions): Promise; /** * @description `GET /v1/score/ai` — composable score with preset or custom weights. */ scoreAI(agent: PublicKey | string, opts: ScoreAiOptions): Promise; /** * @description `GET /v1/agent` — full agent profile (registry details + scoring data). */ agentProfile(agent: PublicKey | string, opts?: ScoreOptions): Promise; }>; /** * @description `GET /v1/score-history` — score trend over time. */ scoreHistory(agent: PublicKey | string, opts?: ScoreOptions): Promise; /** * @description `GET /v1/directory` — query the indexed agent directory. */ directory(opts?: DirectoryOptions): Promise; /** * @description `GET /v1/leaderboard` — top-scoring agents by metric. */ leaderboard(opts?: { metric?: FairScaleDirectorySort; limit?: number; apiKey?: string; timeoutMs?: number; signal?: AbortSignal; }): Promise; /** * @description `GET /v1/credit` — full credit assessment ($0.50 USDC per call). * Uses `X-Api-Key` header instead of `fairkey`. Wire-format for `nocache` * is `0|1` per the docs; the SDK accepts a boolean and converts it. */ credit(agent: PublicKey | string, opts?: CreditOptions): Promise; /** * @description Merge SAP on-chain reputation with FairScale into a single * weighted signal. Falls back gracefully if either source is unavailable. * * @param agentWallet - The agent's owner wallet (NOT the agent PDA). * @param opts - Weights, gating rules, and per-call overrides. * @returns {Promise} * * @example * ```ts * const r = await client.fairscale.aggregate(agentWallet, { * weights: { sap: 0.4, fairscale: 0.6 }, * require: { sapMinFeedbacks: 2 }, * }); * if (r.combined.tier === "high" || r.combined.tier === "elite") accept(); * ``` */ aggregate(agentWallet: PublicKey, opts?: AggregateOptions): Promise; } /** * @name HumanScoreNamespace * @description Wraps `api.fairscale.xyz` (Human Score API). Accessed via * `client.fairscale.human`. * @category Registries * @since v0.11.0 */ export declare class HumanScoreNamespace { #private; constructor(baseUrl: string, apiKey: string | undefined, timeoutMs: number, fetchImpl: typeof fetch); /** * @description `GET /score` — full human wallet analysis. */ score(wallet: PublicKey | string, opts?: { twitter?: string; nocache?: boolean; } & ScoreOptions): Promise; /** `GET /fairScore` — blended 0–1000 integer. */ fairScoreOnly(wallet: PublicKey | string, opts?: ScoreOptions): Promise<{ fair_score: number; }>; /** `GET /walletScore` — on-chain only 0–1000 integer. */ walletScoreOnly(wallet: PublicKey | string, opts?: ScoreOptions): Promise<{ wallet_score: number; }>; /** `GET /socialScore` — social only 0–1000 integer. */ socialScoreOnly(wallet: PublicKey | string, opts?: { twitter?: string; } & ScoreOptions): Promise<{ social_score: number; }>; } //# sourceMappingURL=fairscale.d.ts.map