Appendix F: SDK Type Definitions (@baseline/core)

This appendix defines the typed public interface for the Baseline SDK. All types are specified in TypeScript notation and correspond 1:1 with the protocol schemas defined in Sections 2-8. Any conforming SDK implementation (in any language) MUST expose equivalent types.

The reference implementation exports these types from @baseline/core.

F.1 Primitive Types

/** Keccak-256 hash, hex-encoded with 0x prefix */
type Hash = `0x${string}`;

/** Ed25519 or secp256k1 signature, hex-encoded */
type Signature = string;

/** ISO 8601 timestamp (e.g., "2026-02-01T00:00:00Z") */
type ISOTimestamp = string;

/** Semantic version string (e.g., "1.0.0") */
type SemVer = `${number}.${number}.${number}`;

/** Signed 64-bit integer with implicit scale factor (Section B.2) */
type FixedPoint64 = bigint;

/** Supported chains */
type ChainType = "solana" | "ethereum" | "base";

F.2 Claim Types (Section 2)

/** Subject type taxonomy (Section 2.2) */
type SubjectType = "TOKEN" | "ACCOUNT" | "CONTRACT" | "POOL" | "TX" | "COHORT";

/** Subject reference — exactly one field per SubjectType is non-null */
interface SubjectRef {
  mint?:           string;   // TOKEN
  programId?:      string;   // CONTRACT
  poolAddress?:    string;   // POOL
  txHash?:         string;   // TX
  accountAddress?: string;   // ACCOUNT
}

/** Observed subject (directly addressable on-chain) */
interface ObservedSubject {
  subjectId:    string;
  type:         SubjectType;
  chain:        ChainType;
  ref:          SubjectRef;
  displayName:  string;
}

/** Inferred subject (produced by inference method) */
interface InferredSubject extends ObservedSubject {
  inferenceMethod:  string;
  methodVersion:    SemVer;
  confidence:       number;   // 0-100
}

type Subject = ObservedSubject | InferredSubject;

/** Temporal and chain context (Section 2.3) */
interface Context {
  chain:      ChainType;
  blockFrom:  number;         // Inclusive start block/slot
  blockTo:    number;         // Inclusive end block/slot
  timeFrom?:  ISOTimestamp;   // ISO 8601 timestamp of blockFrom
  timeTo?:    ISOTimestamp;   // ISO 8601 timestamp of blockTo
}

/** Graph expansion constraints (Section 2.3) */
interface Scope {
  maxHops?:           number | null;    // Maximum graph expansion depth
  maxNodes?:          number | null;    // Maximum evidence graph node count
  maxEdges?:          number | null;    // Maximum evidence graph edge count
  maxExpansionOps?:   number | null;    // Maximum BFS expansion operations (default: 20,000)
  temporalLookback?:  number | null;    // Maximum blocks to look back from blockFrom
  evidenceAllowlist?: EvidenceSourceType[] | null;  // Permitted evidence source types
  notes?:             string | null;    // Free-text scope annotations
}

/** Predicate identifier — references the Predicate Registry (Section 2.4) */
type PredicateId = string;

/** Evaluation class */
type EvaluationClass = "DETERMINISTIC" | "INFERENTIAL";

/** Predicate status */
type PredicateStatus = "ACTIVE" | "DEPRECATED" | "RETIRED";

/** Predicate definition from the registry (Section 2.4) */
interface PredicateDefinition {
  predicateId:        PredicateId;
  version:            SemVer;              // Predicate semantic version (Section 2.5)
  name:               string;
  evaluationClass:    EvaluationClass;
  admissibleSubjects: SubjectType[];
  requiredEvidence:   EvidenceSourceType[];
  methods:            MethodReference[];
  description:        string;
  status:             PredicateStatus;
}

/** Predicate manifest entry — frozen mapping within an engine version (Section 2.5) */
interface PredicateManifestEntry {
  predicateId:  PredicateId;
  version:      SemVer;
}

interface MethodReference {
  name:     string;
  version:  SemVer;
}

F.2.1 Claim Submission

/** Input to POST /claims — claimId is computed by the engine, not the caller */
interface ClaimSubmission {
  schemaVersion:  SemVer;       // e.g., "1.0.0"
  predicate:      PredicateId;  // Must reference a registered predicate
  statement:      string;       // Human-readable claim statement
  subject:        Subject;
  context:        Context;
  scope?:         Scope;        // Optional; engine applies defaults if omitted
}

/** Full claim as stored — includes the content-addressed claimId */
interface Claim extends ClaimSubmission {
  claimId:  Hash;   // Keccak-256 of BCE_ENCODE(ClaimSubmission)
}

F.3 Evidence Types (Section 3)

/** Evidence source type taxonomy (Section 3.2) */
type EvidenceSourceType =
  | "ACCOUNT_BALANCE"
  | "TOKEN_SUPPLY"
  | "TOKEN_METADATA"
  | "TRANSFER_EVENT"
  | "POOL_RESERVES"
  | "PROGRAM_DATA"
  | "CONTRACT_CODE"
  | "TX_RECEIPT"
  | "SOCIAL_POST"
  | "SOCIAL_ENGAGEMENT"
  | "DEX_SCREENER_DATA";

/** Evidence verifiability classification (Section 7.2) */
type EvidenceVerifiabilityClass =
  | "ONCHAIN"             // Independently re-fetchable from archive RPC
  | "OFFCHAIN_PINNED"     // Hash-verifiable, source may have changed
  | "OFFCHAIN_EPHEMERAL"; // Stored snapshot only

/** Temporal anchor for an evidence unit */
interface EvidenceAnchor {
  block:  number;             // Block/slot number
  slot?:  number | null;      // Solana slot (if applicable)
  time:   ISOTimestamp;       // ISO 8601 timestamp
}

/** Integrity metadata */
interface EvidenceIntegrity {
  hash?:       Hash | null;       // Content hash of canonical form
  signature?:  Signature | null;  // Provider signature (if available)
}

/** Evidence unit — a single observation with provenance (Section 3.1) */
interface EvidenceUnit {
  evidenceId:       Hash;                         // Keccak-256 of canonicalForm
  type:             EvidenceSourceType;
  source:           string;                       // e.g., "solana-mainnet-rpc"
  retrievalMethod:  string;                       // How evidence was obtained
  anchor:           EvidenceAnchor;
  integrity:        EvidenceIntegrity;
  canonicalForm:    Uint8Array;                   // BCE-encoded content
  rawResponse?:     Uint8Array | null;            // Original provider response
  ref:              string;                       // URI for independent retrieval
}

/** Evidence reference (lightweight, used in VO) */
interface EvidenceReference {
  evidenceId:  Hash;
  type:        EvidenceSourceType;
  anchor:      EvidenceAnchor;
}

F.4 Evidence Graph Types (Section 4)

/** Graph node types */
type GraphNodeType = "ACCOUNT" | "TOKEN" | "POOL" | "CONTRACT" | "TX";

interface GraphNode {
  nodeId:   string;          // Unique within the graph
  type:     GraphNodeType;
  chain:    ChainType;
  address:  string;          // On-chain address
}

/** Graph edge types */
type GraphEdgeType = "TRANSFER" | "OWNS" | "FUNDED_BY" | "POOL_MEMBER" | "CREATED";

interface GraphEdge {
  edgeId:   string;
  type:     GraphEdgeType;
  from:     string;          // Source nodeId
  to:       string;          // Target nodeId
  weight?:  number;
  anchor:   EvidenceAnchor;
}

/** Graph construction metadata */
interface GraphMetadata {
  constructionTime:  ISOTimestamp;       // Informational only (not used in replay)
  nodeCount:         number;
  edgeCount:         number;
  expansionOps:      number;             // Total BFS expansion operations performed
  maxDepth:          number;             // Actual expansion depth reached
  scopeExhausted:    boolean;            // True if any deterministic scope limit was hit
  scopeConstraint:   "maxNodes" | "maxEdges" | "maxHops" | "maxExpansionOps" | null;
}

interface EvidenceGraph {
  graphId:   Hash;
  nodes:     GraphNode[];
  edges:     GraphEdge[];
  metadata:  GraphMetadata;
}

F.5 Verification Object Types (Section 6)

/** Qualification states (Section 6.2) */
type QualificationType =
  | "VERIFIED"
  | "INFERRED"
  | "OBSERVED"
  | "INCONCLUSIVE"
  | "UNQUALIFIED"
  | "CONSTRUCTION_FAILED"
  | "CONTESTED";

/** Line status — whether information is above or below The Line */
type LineStatus = "ABOVE" | "BELOW";

/** Anchoring status on FirmaChain (Section 6.1) */
type AnchoringStatus = "PRE_ANCHORING" | "PENDING" | "ANCHORED" | "FAILED";

/** Migration phase indicator (Section 8.8) — null in full production */
type AnchoringPhase = "SHADOW" | "TESTNET" | "MAINNET" | null;

/** Confidence bounds for inferential results */
interface ConfidenceBounds {
  low:   number | null;
  high:  number | null;
}

/** Evaluation result */
interface EvaluationResult {
  qualification:  QualificationType;
  confidence:     number;              // 0-100 (100 = fully deterministic)
  bounds:         ConfidenceBounds;
  verdictText:    string;              // Human-readable summary
  reasons:        string[];            // Supporting/undermining factors
}

/** Attestation signature */
interface AttestationSignature {
  validatorId:  string;
  sig:          Signature;             // Ed25519 over (voId || validatorId || replayedAt)
}

/** Attestation summary (embedded in VO) */
interface AttestationSummary {
  count:        number;
  validatorIds: string[];
  signatures:   AttestationSignature[];
}

/** On-chain anchoring metadata (Section 6.1, 8.8) */
interface AnchoringMetadata {
  anchoringStatus:  AnchoringStatus;
  txHash?:          string | null;     // FirmaChain transaction hash
  anchoredAt?:      ISOTimestamp | null;
  anchoringPhase?:  AnchoringPhase;    // Migration phase; null in full production
}

/**
 * Trust transparency helper — consumers SHOULD use this logic
 * to determine what level of trust a VO carries (Section 10.6).
 *
 * PRE_ANCHORING: operator-asserted only, no independent verification
 * PENDING/FAILED: anchoring infra operational, awaiting confirmation
 * ANCHORED: independently verifiable via on-chain Merkle proof
 */

/** Verification Object — the atomic output of Baseline (Section 6.1) */
interface VerificationObject {
  voId:           Hash;
  lineStatus:     LineStatus;
  claim:          Claim;
  engine:         { version: SemVer };
  predicate:      PredicateManifestEntry;  // Predicate version used (from engine manifest)
  methods:        MethodReference[];
  result:         EvaluationResult;
  evidence:       EvidenceReference[];
  evidenceGraph:  {
    graphId:     Hash;
    summary:     string;
    previewUrl?: string | null;
  };
  attestations:   AttestationSummary;
  baselineChain:  AnchoringMetadata;
  timestamps:     {
    createdAt:  ISOTimestamp;
    updatedAt:  ISOTimestamp;
  };
}

F.6 Attestation Types (Section 7)

/** Full attestation record (Section 7.3) */
interface Attestation {
  attestationId:   string;
  voId:            Hash;
  validatorId:     string;                     // Validator public key
  engineVersion:   SemVer;
  methodVersions:  Record<string, SemVer>;     // Method name -> version
  replayedAt:      ISOTimestamp;
  replayDuration:  number;                     // Milliseconds
  sig:             Signature;
}

/** Validator registration (Section 7.4-7.5) */
interface ValidatorInfo {
  validatorId:         string;
  publicKey:           string;                 // Ed25519 public key (hex)
  stake:               bigint;                 // LINE tokens staked
  archiveAccess:       boolean;                // Has independent archive RPC
  registeredAt:        ISOTimestamp;
  reputationMultiplier: number;                // 0.5-2.0 (Section 7.5.3)
  validatorWeight:     number;                 // Composite weight
}

F.7 API Request/Response Types (Section 10)

F.7.1 Pagination

All list endpoints support cursor-based pagination:

/** Pagination parameters (query string) */
interface PaginationParams {
  cursor?:  string;   // Opaque cursor from previous response
  limit?:   number;   // Items per page (default: 20, max: 100)
}

/** Paginated response wrapper */
interface PaginatedResponse<T> {
  data:        T[];
  pagination:  {
    cursor:    string | null;   // null = no more pages
    hasMore:   boolean;
    total?:    number;          // Total count (included when economical to compute)
  };
}

F.7.2 Claim Endpoints

/** POST /claims — submit a claim for verification */
interface SubmitClaimRequest {
  body: ClaimSubmission;
}
interface SubmitClaimResponse {
  claimId:  Hash;           // Content-addressed claim identifier
  voId?:    Hash | null;    // If evaluation is synchronous; null if queued
  status:   "EVALUATING" | "QUEUED" | "COMPLETED";
}

/** GET /claims/{claimId} */
interface GetClaimResponse {
  claim:          Claim;
  evaluationIds:  Hash[];   // voIds of evaluations for this claim
}

F.7.3 Verification Object Endpoints

/** GET /verification-objects query filters */
interface ListVOsParams extends PaginationParams {
  predicate?:       PredicateId;
  subject?:         string;          // Subject address or identifier
  chain?:           ChainType;
  qualification?:   QualificationType;
  blockFrom?:       number;
  blockTo?:         number;
  createdAfter?:    ISOTimestamp;
  createdBefore?:   ISOTimestamp;
}

/** GET /verification-objects */
type ListVOsResponse = PaginatedResponse<VerificationObject>;

/** GET /verification-objects/{voId} */
type GetVOResponse = VerificationObject;

/** GET /verification-objects/{voId}/attestations */
type ListAttestationsResponse = PaginatedResponse<Attestation>;

F.7.4 Engine and Predicate Endpoints

/** GET /engine/versions */
interface EngineVersion {
  version:            SemVer;
  status:             "CURRENT" | "SUPPORTED" | "DEPRECATED";
  releasedAt:         ISOTimestamp;
  deprecatedAt?:      ISOTimestamp | null;
  changelog:          string;
  predicateManifest:  PredicateManifestEntry[];   // Frozen predicate versions (Section 2.5)
}
type ListEngineVersionsResponse = PaginatedResponse<EngineVersion>;

/** GET /predicates — returns all versions of all predicates */
type ListPredicatesResponse = PaginatedResponse<PredicateDefinition>;

/** GET /predicates/{predicateId} — returns the ACTIVE version by default */
type GetPredicateResponse = PredicateDefinition;

/** GET /predicates/{predicateId}/versions — all versions of a specific predicate */
type ListPredicateVersionsResponse = PaginatedResponse<PredicateDefinition>;

F.7.5 WebSocket Event Types (Section 10.4)

/** Discriminated union for WebSocket messages */
type WebSocketMessage =
  | { type: "event";       data: TradeEvent }
  | { type: "ml_score";    data: MLScore }
  | { type: "token_meta";  data: TokenMetadata }
  | { type: "stats";       data: GlobalStats }
  | { type: "feed_update"; data: BaselineFeedItem };

interface TradeEvent {
  signature:       string;
  dex:             string;
  pairAddress:     string;
  tokenMint:       string;
  side:            "BUY" | "SELL";
  solAmount:       bigint;           // lamports
  tokenAmount:     bigint;           // raw token units
  traderAddress:   string;
  slot:            number;
  timestamp:       ISOTimestamp;
}

interface MLScore {
  tokenMint:       string;
  modelType:       string;
  prediction:      number;           // 0.0-1.0
  threshold:       number;
  label:           "POSITIVE" | "NEGATIVE";
  features:        Record<string, FixedPoint64>;
  computedAt:      ISOTimestamp;
}

interface TokenMetadata {
  mint:            string;
  name:            string;
  symbol:          string;
  uri:             string;
  createdAt:       ISOTimestamp;
  createdSlot:     number;
}

interface GlobalStats {
  totalTokens:     number;
  totalTrades:     number;
  totalVolumeSol:  bigint;
  activePairs:     number;
  timestamp:       ISOTimestamp;
}

interface BaselineFeedItem {
  feedId:          string;
  coinId:          string;
  ticker:          string;
  insightType:     string;
  content:         string;
  supportingVOs:   Hash[];
  publishedAt:     ISOTimestamp;
}

F.8 Error Types

All API errors follow a consistent structure:

/** Standard error response */
interface BaselineError {
  error: {
    code:     ErrorCode;
    message:  string;            // Human-readable description
    details?: Record<string, unknown>;  // Machine-readable context
  };
  requestId:  string;            // For support/debugging
}

/** Error codes */
type ErrorCode =
  // 4xx Client Errors
  | "INVALID_CLAIM"              // Claim fails schema validation
  | "INVALID_PREDICATE"          // Predicate not registered or incompatible with subject type
  | "INVALID_SUBJECT"            // Subject type does not match predicate's admissible types
  | "INVALID_CONTEXT"            // Block range empty, non-finalized, or malformed
  | "INVALID_SCOPE"              // Scope parameters out of range
  | "CLAIM_NOT_FOUND"            // claimId does not exist
  | "VO_NOT_FOUND"               // voId does not exist
  | "PREDICATE_NOT_FOUND"        // predicateId does not exist
  | "PREDICATE_VERSION_MISMATCH" // Requested predicate version not in engine manifest
  | "UNAUTHORIZED"               // Missing or invalid authentication
  | "FORBIDDEN"                  // Authenticated but lacks permission
  | "RATE_LIMITED"               // Too many requests
  | "INVALID_CURSOR"             // Pagination cursor expired or malformed
  // 5xx Server Errors
  | "EVALUATION_FAILED"          // Engine error during evaluation
  | "EVIDENCE_RETRIEVAL_FAILED"  // Could not retrieve required evidence
  | "CONSTRUCTION_TIMEOUT"       // Graph construction exceeded operational timeout
  | "INTERNAL_ERROR"             // Unexpected server error
  | "SERVICE_UNAVAILABLE";       // Temporary outage

/** Claim validation error — returned when code is INVALID_CLAIM */
interface ClaimValidationError extends BaselineError {
  error: BaselineError["error"] & {
    code: "INVALID_CLAIM";
    details: {
      violations: Array<{
        field:    string;     // JSONPath to the invalid field (e.g., "subject.ref.mint")
        rule:     string;     // Validation rule that failed
        message:  string;     // Human-readable explanation
      }>;
    };
  };
}

F.9 Client Interface

The @baseline/core package exports a typed client:

interface BaselineClientConfig {
  baseUrl?:  string;                // Default: "https://api.baseline.io/v1"
  apiKey?:   string;                // For server-to-server auth
  token?:    string;                // JWT for end-user auth
  timeout?:  number;                // Request timeout in ms (default: 30000)
}

interface BaselineClient {
  // Claims
  submitClaim(claim: ClaimSubmission):        Promise<SubmitClaimResponse>;
  getClaim(claimId: Hash):                    Promise<GetClaimResponse>;

  // Verification Objects
  listVOs(params?: ListVOsParams):            Promise<ListVOsResponse>;
  getVO(voId: Hash):                          Promise<GetVOResponse>;
  listAttestations(voId: Hash, params?: PaginationParams):
                                              Promise<ListAttestationsResponse>;

  // Engine
  listEngineVersions(params?: PaginationParams):
                                              Promise<ListEngineVersionsResponse>;
  getEngineVersion(version: SemVer):          Promise<EngineVersion>;

  // Predicates
  listPredicates(params?: PaginationParams):  Promise<ListPredicatesResponse>;
  getPredicate(predicateId: PredicateId):     Promise<GetPredicateResponse>;
  listPredicateVersions(predicateId: PredicateId, params?: PaginationParams):
                                              Promise<ListPredicateVersionsResponse>;

  // WebSocket
  subscribe(endpoint: "events" | "scores" | "feed",
            handler: (msg: WebSocketMessage) => void): WebSocketSubscription;
}

interface WebSocketSubscription {
  unsubscribe(): void;
  readonly connected: boolean;
}

/** Factory function */
declare function createBaselineClient(config: BaselineClientConfig): BaselineClient;

F.10 Usage Example

import { createBaselineClient } from "@baseline/core";
import type { ClaimSubmission, VerificationObject } from "@baseline/core";

const client = createBaselineClient({
  apiKey: process.env.BASELINE_API_KEY,
});

// Submit a supply concentration claim
const claim: ClaimSubmission = {
  schemaVersion: "1.0.0",
  predicate:     "supply_concentration",
  statement:     "The top 10 holders of token XYZ control more than 50% of supply.",
  subject: {
    subjectId:    "xyz-token",
    type:         "TOKEN",
    chain:        "solana",
    ref:          { mint: "XYZ_MINT_ADDRESS" },
    displayName:  "Token XYZ",
  },
  context: {
    chain:      "solana",
    blockFrom:  285000000,
    blockTo:    285172800,
    timeFrom:   "2026-02-01T00:00:00Z",
    timeTo:     "2026-02-02T00:00:00Z",
  },
};

const { claimId, voId, status } = await client.submitClaim(claim);
console.log(`Claim ${claimId} — status: ${status}`);

// Retrieve the Verification Object once evaluation completes
if (voId) {
  const vo: VerificationObject = await client.getVO(voId);
  console.log(`Qualification: ${vo.result.qualification}`);
  console.log(`Confidence:    ${vo.result.confidence}`);
  console.log(`Verdict:       ${vo.result.verdictText}`);
}

// List all attestations for a VO
const attestations = await client.listAttestations(voId!, { limit: 50 });
for (const att of attestations.data) {
  console.log(`Attested by ${att.validatorId} at ${att.replayedAt}`);
}

// Subscribe to real-time trade events
const sub = client.subscribe("events", (msg) => {
  if (msg.type === "event") {
    console.log(`Trade: ${msg.data.side} ${msg.data.tokenMint}`);
  }
});

Baseline Technical Specification (Yellow Paper) v0.1 — Draft

results matching ""

    No results matching ""