Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,240 changes: 1,217 additions & 23 deletions package-lock.json

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@
"version": "0.1.2",
"description": "The missing operations layer for deployed Soroban smart contracts",
"main": "dist/index.js",
"files": ["dist", "README.md", "LICENSE", "CONTRIBUTING.md"],
"files": [
"dist",
"README.md",
"LICENSE",
"CONTRIBUTING.md"
],
"bin": {
"sorokeep": "dist/index.js"
"sorokeep": "dist/index.js",
"sorokeep-mcp": "dist/mcp/index.js"
},
"scripts": {
"build": "tsc && node -e \"require('fs').copyFileSync('src/db/schema.sql', 'dist/db/schema.sql')\"",
"dev": "tsx src/index.ts",
"mcp": "tsx src/mcp/index.ts",
"lint": "eslint src/",
"test": "vitest run",
"test:watch": "vitest"
Expand All @@ -30,14 +37,16 @@
"url": "https://github.com/AbdulmalikAlayande/sorokeep.git"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"@stellar/stellar-sdk": "^15.1.0",
"better-sqlite3": "^12.9.0",
"chalk": "^5.6.2",
"commander": "^14.0.3",
"ora": "^9.4.0",
"pino": "^10.3.1",
"pino-pretty": "^13.1.3",
"yaml": "^2.8.4"
"yaml": "^2.8.4",
"zod": "^4.4.3"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
Expand Down
59 changes: 21 additions & 38 deletions src/commands/status.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Command } from "commander";
import chalk from "chalk";
import { getDatabase } from "../db/database.js";
import { getContract, getEntriesForContract } from "../db/repositories.js";
import { getContractStatus, ContractNotFoundError } from "../core/status.js";
import {
classifyTTL,
statusIndicator,
formatTimeToCloseLedger,
formatContractID,
} from "../utils/formatting.js";

Expand All @@ -15,62 +13,47 @@ export function registerStatusCommand(program: Command): void {
.description("Show TTL and storage health for a watched contract")
.action((contractId: string) => {
const db = getDatabase();
const contract = getContract(db, contractId);

if (!contract) {
console.log(chalk.red(`Contract ${formatContractID(contractId)} is not registered.`));
console.log(chalk.dim("Run 'sorokeep watch <contractId>' first."));
process.exit(1);
let status;
try {
status = getContractStatus(db, contractId);
} catch (error) {
if (error instanceof ContractNotFoundError) {
console.log(chalk.red(`Contract ${formatContractID(contractId)} is not registered.`));
console.log(chalk.dim("Run 'sorokeep watch <contractId>' first."));
process.exit(1);
}
throw error;
}

const entries = getEntriesForContract(db, contractId);
const displayName = contract.name ?? formatContractID(contractId);
const lastChecked = contract.last_checked_ledger ?? null;
const displayName = status.name ?? formatContractID(contractId);

console.log();
console.log(chalk.bold(` ${displayName}`) + chalk.dim(` (${formatContractID(contractId)})`));
console.log(` Network: ${chalk.cyan(contract.network)}`);
if (lastChecked != null) {
console.log(chalk.dim(` Last checked: ledger ${lastChecked.toLocaleString()}`));
console.log(` Network: ${chalk.cyan(status.network)}`);
if (status.lastCheckedLedger != null) {
console.log(chalk.dim(` Last checked: ledger ${status.lastCheckedLedger.toLocaleString()}`));
}
console.log();

if (entries.length === 0) {
if (status.entries.length === 0) {
console.log(chalk.yellow(" No entries tracked for this contract."));
console.log();
return;
}

// Build labels for each entry — used for display and alignment
const labels: string[] = entries.map((e) => {
if (e.entry_type === "instance") return "Instance";
if (e.entry_type === "wasm") return "WASM Code";
return e.label ?? e.entry_type;
});

const maxLabelLen = Math.max(...labels.map((l) => l.length));

for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
const label = labels[i];
const maxLabelLen = Math.max(...status.entries.map((entry) => entry.label.length));

// Safety: entries and labels are built from the same source array,
// but noUncheckedIndexedAccess is enabled, so we guard explicitly.
if (!entry || !label) continue;
for (const entry of status.entries) {
const paddedLabel = entry.label.padEnd(maxLabelLen);

const paddedLabel = label.padEnd(maxLabelLen);

if (entry.live_until_ledger == null || lastChecked == null) {
if (entry.status === "unknown") {
console.log(` ${paddedLabel} TTL: ${chalk.dim("unknown")}`);
continue;
}

const remainingTTL = entry.live_until_ledger - lastChecked;
const status = classifyTTL(remainingTTL);
const timeStr = formatTimeToCloseLedger(remainingTTL);

console.log(
` ${paddedLabel} TTL: ${remainingTTL.toLocaleString().padStart(9)} ledgers (${timeStr}) ${statusIndicator(status)}`,
` ${paddedLabel} TTL: ${entry.remainingTTL!.toLocaleString().padStart(9)} ledgers (${entry.approximateTimeRemaining}) ${statusIndicator(entry.status)}`,
);
}

Expand Down
95 changes: 95 additions & 0 deletions src/core/status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import type Database from "better-sqlite3";
import { getContract, getEntriesForContract } from "../db/repositories.js";
import type { ContractEntry } from "../db/repositories.js";
import {
classifyTTL,
formatTimeToCloseLedger,
type TTLStatus,
} from "../utils/formatting.js";

export type EntryTTLStatus = TTLStatus | "unknown";

export type ContractStatusEntry = {
label: string;
entryType: string;
entryKeyXdr: string;
liveUntilLedger: number | null;
remainingTTL: number | null;
approximateTimeRemaining: string | null;
status: EntryTTLStatus;
};

export type ContractStatus = {
contractId: string;
name: string | null;
network: string;
lastCheckedLedger: number | null;
entries: ContractStatusEntry[];
};

export class ContractNotFoundError extends Error {
constructor(contractId: string) {
super(`Contract ${contractId} is not registered.`);
this.name = "ContractNotFoundError";
}
}

function getEntryLabel(entry: ContractEntry): string {
if (entry.entry_type === "instance") return "Instance";
if (entry.entry_type === "wasm") return "WASM Code";
return entry.label ?? entry.entry_type;
}

function mapEntryStatus(
entry: ContractEntry,
lastCheckedLedger: number | null,
): ContractStatusEntry {
const label = getEntryLabel(entry);
const liveUntilLedger = entry.live_until_ledger ?? null;

if (liveUntilLedger == null || lastCheckedLedger == null) {
return {
label,
entryType: entry.entry_type,
entryKeyXdr: entry.entry_key_xdr,
liveUntilLedger,
remainingTTL: null,
approximateTimeRemaining: null,
status: "unknown",
};
}
Comment thread
bigjoe-io marked this conversation as resolved.
Resolved

const remainingTTL = liveUntilLedger - lastCheckedLedger;
const status = classifyTTL(remainingTTL);

return {
label,
entryType: entry.entry_type,
entryKeyXdr: entry.entry_key_xdr,
liveUntilLedger,
remainingTTL,
approximateTimeRemaining: formatTimeToCloseLedger(remainingTTL),
status,
};
}

export function getContractStatus(db: Database.Database, contractId: string): ContractStatus {
const contract = getContract(db, contractId);

if (!contract) {
throw new ContractNotFoundError(contractId);
}

const lastCheckedLedger = contract.last_checked_ledger ?? null;
const entries = getEntriesForContract(db, contractId).map((entry) =>
mapEntryStatus(entry, lastCheckedLedger),
);

return {
contractId: contract.id,
name: contract.name,
network: contract.network,
lastCheckedLedger,
entries,
};
}
15 changes: 15 additions & 0 deletions src/mcp/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { getDatabase } from "../db/database.js";
import { createMcpServer } from "./server.js";

async function main(): Promise<void> {
const server = createMcpServer(() => getDatabase());
const transport = new StdioServerTransport();
await server.connect(transport);
}

main().catch((error: unknown) => {
console.error("MCP server error:", error);
process.exit(1);
});
Comment thread
bigjoe-io marked this conversation as resolved.
Resolved
14 changes: 14 additions & 0 deletions src/mcp/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type Database from "better-sqlite3";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { registerGetContractStatusTool } from "./tools/get_contract_status.js";

export function createMcpServer(getDb: () => Database.Database): McpServer {
const server = new McpServer({
name: "sorokeep",
version: "0.1.2",
});

registerGetContractStatusTool(server, getDb);

return server;
}
Comment thread
bigjoe-io marked this conversation as resolved.
Resolved
52 changes: 52 additions & 0 deletions src/mcp/tools/get_contract_status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type Database from "better-sqlite3";
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import * as z from "zod/v4";
import {
ContractNotFoundError,
getContractStatus,
type ContractStatus,
} from "../../core/status.js";

export async function invokeGetContractStatus(
db: Database.Database,
contractId: string,
): Promise<CallToolResult> {
try {
const status = getContractStatus(db, contractId);
return formatContractStatusResult(status);
} catch (error) {
if (error instanceof ContractNotFoundError) {
return {
content: [{ type: "text", text: error.message }],
isError: true,
};
}
throw error;
}
}

export function formatContractStatusResult(status: ContractStatus): CallToolResult {
return {
content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
structuredContent: { ...status },
};
}

export function registerGetContractStatusTool(
server: McpServer,
getDb: () => Database.Database,
): void {
server.registerTool(
"get_contract_status",
{
title: "Get Contract Status",
description:
"Query TTL health metrics for a watched Soroban contract, including per-entry remaining lifespans.",
inputSchema: {
contractId: z.string().describe("Stellar contract address (C... format)"),
},
},
async ({ contractId }) => invokeGetContractStatus(getDb(), contractId),
);
}
Comment thread
bigjoe-io marked this conversation as resolved.
Resolved
Loading