/** * @module postgres/adapter * @description PostgreSQL adapter for SAP v2 — syncs on-chain accounts * to a relational database for off-chain querying and analytics. * * The adapter uses `pg` (node-postgres) as the database driver. * It is database-driver agnostic at the interface level — you can * substitute any client that implements the `PgClient` interface. * * @category Postgres * @since v0.1.0 * * @example * ```ts * import { SapPostgres } from "@synapse-sap/sdk/postgres"; * import { Pool } from "pg"; * * const pool = new Pool({ connectionString: process.env.DATABASE_URL }); * const pg = new SapPostgres(pool, sapClient); * * // Run schema migration * await pg.migrate(); * * // Sync all agents to PostgreSQL * await pg.syncAgents(); * * // Full sync (all account types) * await pg.syncAll(); * * // Query off-chain * const agents = await pg.query("SELECT * FROM sap_agents WHERE is_active = true"); * ``` */ import type { SapClient } from "../core/client"; import type { SyncOptions, SyncCursorRow, SapAccountType } from "./types"; /** * @interface PgClient * @description Minimal PostgreSQL client interface. * Compatible with `pg.Pool`, `pg.Client`, or any wrapper * that provides `query()`. * @category Postgres * @since v0.1.0 */ export interface PgClient { query(text: string, values?: unknown[]): Promise<{ rows: unknown[]; rowCount: number; }>; } /** * @name SapPostgres * @description PostgreSQL off-chain mirror for SAP v2 on-chain data. * * Connects to a PostgreSQL database and synchronizes all 22 on-chain * account types into relational tables. Supports incremental sync, * event logging, and cursor-based pagination. * * @category Postgres * @since v0.1.0 * * @example * ```ts * import { SapPostgres } from "@synapse-sap/sdk/postgres"; * import { Pool } from "pg"; * import { SapClient } from "@synapse-sap/sdk"; * * const pool = new Pool({ connectionString: process.env.DATABASE_URL }); * const sap = SapClient.from(provider); * const pg = new SapPostgres(pool, sap); * * await pg.migrate(); // Create tables * await pg.syncAll(); // Mirror on-chain state * * // Read from PostgreSQL * const { rows } = await pg.query( * "SELECT * FROM sap_agents WHERE is_active = true ORDER BY reputation_score DESC" * ); * ``` */ export declare class SapPostgres { private readonly db; private readonly client; private readonly debug; constructor(db: PgClient, client: SapClient, debug?: boolean); /** * @name migrate * @description Run the SQL schema migration to create all SAP tables, * indexes, views, and enum types. Safe to call multiple times * (uses `CREATE IF NOT EXISTS`). * @returns {Promise} * @since v0.1.0 */ migrate(): Promise; /** * @name migrateWithSQL * @description Run migration with a custom SQL string. * Useful when the schema.sql file is bundled differently. * @param sql - The full SQL schema to execute. * @since v0.1.0 */ migrateWithSQL(sql: string): Promise; /** * @name query * @description Execute a raw SQL query against the database. * @param text - SQL query string. * @param values - Parameterized values. * @returns Query result with rows and rowCount. * @since v0.1.0 */ query(text: string, values?: unknown[]): Promise<{ rows: T[]; rowCount: number; }>; /** * @name upsert * @description Insert or update a row in the specified table. * Uses `ON CONFLICT (pda) DO UPDATE` for idempotent writes. * @param table - Target table name. * @param row - Key-value record to insert. * @since v0.1.0 */ upsert(table: string, row: Record): Promise; /** * @name upsertBatch * @description Upsert multiple rows in a single transaction. * @param table - Target table name. * @param rows - Array of key-value records. * @since v0.1.0 */ upsertBatch(table: string, rows: Record[]): Promise; /** * @name getCursor * @description Get the sync cursor for a given account type. * @param accountType - The account type to check. * @since v0.1.0 */ getCursor(accountType: SapAccountType): Promise; /** * @name updateCursor * @description Update the sync cursor after a successful sync. * @param accountType - The account type synced. * @param slot - The last synced slot. * @param signature - Optional last TX signature. * @since v0.1.0 */ updateCursor(accountType: SapAccountType | string, slot: number, signature?: string): Promise; /** * @name syncGlobal * @description Sync the GlobalRegistry singleton to PostgreSQL. * @since v0.1.0 */ syncGlobal(): Promise; /** * @name syncAgents * @description Sync all AgentAccount PDAs to PostgreSQL. * @since v0.1.0 */ syncAgents(): Promise; /** * @name syncAgentStats * @description Sync all AgentStats PDAs to PostgreSQL. * @since v0.1.0 */ syncAgentStats(): Promise; /** * @name syncFeedbacks * @description Sync all FeedbackAccount PDAs to PostgreSQL. * @since v0.1.0 */ syncFeedbacks(): Promise; /** * @name syncTools * @description Sync all ToolDescriptor PDAs to PostgreSQL. * @since v0.1.0 */ syncTools(): Promise; /** * @name syncEscrows * @description Sync all EscrowAccountV2 PDAs to PostgreSQL. * @since v0.1.0 */ syncEscrows(): Promise; /** * @name syncAttestations * @description Sync all AgentAttestation PDAs to PostgreSQL. * @since v0.1.0 */ syncAttestations(): Promise; /** * @name syncVaults * @description Sync all MemoryVault PDAs to PostgreSQL. * @since v0.1.0 */ syncVaults(): Promise; /** * @name syncSessions * @description Sync all SessionLedger PDAs to PostgreSQL. * @since v0.1.0 */ syncSessions(): Promise; /** * @name syncLedgers * @description Sync all MemoryLedger PDAs to PostgreSQL. * @since v0.1.0 */ syncLedgers(): Promise; /** * @name syncLedgerPages * @description Sync all LedgerPage PDAs to PostgreSQL. * @since v0.1.0 */ syncLedgerPages(): Promise; /** * @name syncCapabilityIndexes * @description Sync all CapabilityIndex PDAs to PostgreSQL. * @since v0.1.0 */ syncCapabilityIndexes(): Promise; /** * @name syncProtocolIndexes * @description Sync all ProtocolIndex PDAs to PostgreSQL. * @since v0.1.0 */ syncProtocolIndexes(): Promise; /** * @name syncToolCategoryIndexes * @description Sync all ToolCategoryIndex PDAs to PostgreSQL. * @since v0.1.0 */ syncToolCategoryIndexes(): Promise; /** * @name syncEpochPages * @description Sync all EpochPage PDAs to PostgreSQL. * @since v0.1.0 */ syncEpochPages(): Promise; /** * @name syncDelegates * @description Sync all VaultDelegate PDAs to PostgreSQL. * @since v0.1.0 */ syncDelegates(): Promise; /** * @name syncCheckpoints * @description Sync all SessionCheckpoint PDAs to PostgreSQL. * @since v0.1.0 */ syncCheckpoints(): Promise; /** * @name syncAll * @description Sync all on-chain account types to PostgreSQL. * * Fetches every account via `program.account.*.all()` and * upserts into the corresponding table. Reports progress * via the `onProgress` callback. * * @param options - Optional sync configuration. * @returns Summary of synced account counts. * @since v0.1.0 * * @example * ```ts * const result = await pg.syncAll({ * onProgress: (synced, total, type) => { * console.log(`[${type}] ${synced}/${total}`); * }, * }); * console.log("Total synced:", result.totalRecords); * ``` */ syncAll(options?: SyncOptions): Promise; /** * @name syncEvent * @description Store a parsed SAP event in the events log table. * @param eventName - The event name (e.g. "RegisteredEvent"). * @param txSignature - The transaction signature. * @param slot - The Solana slot. * @param data - The parsed event data. * @param agentPda - Optional agent PDA for indexing. * @param wallet - Optional wallet for indexing. * @since v0.1.0 */ syncEvent(eventName: string, txSignature: string, slot: number, data: Record, agentPda?: string, wallet?: string): Promise; /** * @name getAgent * @description Fetch a single agent by PDA or wallet. * @param pdaOrWallet - Agent PDA (base58) or owner wallet. * @since v0.1.0 */ getAgent(pdaOrWallet: string): Promise; /** * @name getActiveAgents * @description Fetch all active agents, ordered by reputation. * @param limit - Max agents to return (default: 100). * @since v0.1.0 */ getActiveAgents(limit?: number): Promise; /** * @name getEscrowBalance * @description Fetch escrow balance for a specific agent/depositor pair. * @param agentPda - Agent PDA (base58). * @param depositor - Depositor wallet (base58). * @since v0.1.0 */ getEscrowBalance(agentPda: string, depositor: string): Promise; /** * @name getAgentTools * @description Fetch all active tools for a given agent. * @param agentPda - Agent PDA (base58). * @since v0.1.0 */ getAgentTools(agentPda: string): Promise; /** * @name getRecentEvents * @description Fetch the most recent events. * @param limit - Max events to return (default: 50). * @param eventName - Optional filter by event name. * @since v0.1.0 */ getRecentEvents(limit?: number, eventName?: string): Promise; /** * @name getSyncStatus * @description Get the sync status for all account types. * @since v0.1.0 */ getSyncStatus(): Promise; private log; } /** * @interface SyncAllResult * @description Result of a full sync operation. * @category Postgres * @since v0.1.0 */ export interface SyncAllResult { agents: number; agentStats: number; feedbacks: number; tools: number; escrows: number; attestations: number; vaults: number; sessions: number; epochPages: number; delegates: number; checkpoints: number; ledgers: number; ledgerPages: number; capabilityIndexes: number; protocolIndexes: number; toolCategoryIndexes: number; totalRecords: number; durationMs: number; } //# sourceMappingURL=adapter.d.ts.map