Skip to main content

Diagnostics

Runtime diagnostics help identify issues with network connections, wallet state, and protocol parameters.

Overview

import { diagnose, isHealthy, quickBalance, checkNetwork, checkWallet } from 'cardano-devkit';

// Run full diagnostics
const diagnostics = await diagnose(devKit);
console.log(diagnostics);

// Quick health check
if (await isHealthy(devKit)) {
console.log('All systems operational');
}

// Quick balance check
const balance = await quickBalance(devKit);
console.log(`Balance: ${balance.ada} ADA`);

Full Diagnostics

diagnose(devKit)

Run comprehensive diagnostics on the DevKit instance.

import { diagnose, formatDiagnostics, printDiagnostics } from 'cardano-devkit';

const diagnostics = await diagnose(devKit);

// Format as string
console.log(formatDiagnostics(diagnostics));

// Or print directly
printDiagnostics(diagnostics);

Returns:

interface DiagnosticResult {
timestamp: Date;
network: NetworkDiagnostics;
wallet: WalletDiagnostics;
protocol: ProtocolDiagnostics;
overall: DiagnosticStatus;
suggestions: string[];
}

Diagnostic Status

StatusDescription
healthyEverything is working correctly
degradedSome issues but mostly functional
unhealthyCritical issues preventing operation
unknownUnable to determine status

Example Output

╔══════════════════════════════════════════════════════════════╗
║ DIAGNOSTICS REPORT ║
╠══════════════════════════════════════════════════════════════╣
║ Timestamp: 2024-01-15T10:30:00.000Z ║
║ Overall Status: HEALTHY ✓ ║
╠══════════════════════════════════════════════════════════════╣
║ NETWORK ║
║ Status: healthy ║
║ Network: Preprod ║
║ Provider: Koios ║
║ Tip Slot: 45678901 ║
║ Sync Progress: 100% ║
╠══════════════════════════════════════════════════════════════╣
║ WALLET ║
║ Status: healthy ║
║ Connected: true ║
║ Address: addr_test1qz... ║
║ Balance: 150.5 ADA ║
║ UTxO Count: 12 ║
╠══════════════════════════════════════════════════════════════╣
║ PROTOCOL ║
║ Status: healthy ║
║ Protocol Version: 9.0 ║
║ Min Fee A: 44 ║
║ Min Fee B: 155381 ║
║ Max Tx Size: 16384 ║
╚══════════════════════════════════════════════════════════════╝

Network Diagnostics

checkNetwork(devKit)

Check network connectivity and sync status.

import { checkNetwork } from 'cardano-devkit';

const network = await checkNetwork(devKit);

console.log('Status:', network.status);
console.log('Network:', network.network);
console.log('Provider:', network.provider);
console.log('Tip Slot:', network.tipSlot);
console.log('Sync Progress:', network.syncProgress);
console.log('Latency:', network.latencyMs, 'ms');

Returns:

interface NetworkDiagnostics {
status: DiagnosticStatus;
network: NetworkType;
provider: string;
tipSlot: number;
tipTime: Date;
syncProgress: number; // 0-100
latencyMs: number;
error?: string;
}

Common Network Issues

IssueStatusSuggestion
Provider unreachableunhealthyCheck internet connection or try different provider
High latency (>5s)degradedNetwork congestion or provider issues
Sync < 100%degradedNode is syncing, wait for completion
Old tip slotdegradedProvider may be behind, try refreshing

Wallet Diagnostics

checkWallet(devKit)

Check wallet connection and balance.

import { checkWallet } from 'cardano-devkit';

const wallet = await checkWallet(devKit);

console.log('Status:', wallet.status);
console.log('Connected:', wallet.connected);
console.log('Address:', wallet.address);
console.log('Balance:', wallet.balanceAda, 'ADA');
console.log('UTxO Count:', wallet.utxoCount);

Returns:

interface WalletDiagnostics {
status: DiagnosticStatus;
connected: boolean;
walletType?: string;
address?: string;
balanceLovelace: bigint;
balanceAda: number;
utxoCount: number;
hasCollateral: boolean;
error?: string;
}

Common Wallet Issues

IssueStatusSuggestion
Not connectedunhealthyConnect wallet with selectWallet()
Zero balancedegradedFund wallet from faucet or transfer funds
No UTxOsunhealthyWallet needs funds to create transactions
No collateraldegradedSet collateral for smart contract transactions

Quick Helpers

isHealthy(devKit)

Quick health check returning a boolean.

import { isHealthy } from 'cardano-devkit';

if (await isHealthy(devKit)) {
// Safe to proceed with transactions
await sendPayment();
} else {
// Run full diagnostics to identify issues
const diagnostics = await diagnose(devKit);
console.log(diagnostics.suggestions);
}

quickBalance(devKit)

Get wallet balance quickly.

import { quickBalance } from 'cardano-devkit';

const balance = await quickBalance(devKit);

console.log(`Balance: ${balance.ada} ADA (${balance.lovelace} lovelace)`);
console.log(`UTxOs: ${balance.utxoCount}`);

if (balance.ada < 5) {
console.warn('Low balance! Consider funding from faucet.');
}

Returns:

interface QuickBalance {
lovelace: bigint;
ada: number;
utxoCount: number;
hasCollateral: boolean;
}

Protocol Diagnostics

checkProtocol(devKit)

Check protocol parameters.

import { checkProtocol } from 'cardano-devkit';

const protocol = await checkProtocol(devKit);

console.log('Protocol Version:', protocol.protocolVersion);
console.log('Min Fee A:', protocol.minFeeA);
console.log('Min Fee B:', protocol.minFeeB);
console.log('Max Tx Size:', protocol.maxTxSize);
console.log('Coins Per UTxO:', protocol.coinsPerUtxoByte);

Returns:

interface ProtocolDiagnostics {
status: DiagnosticStatus;
protocolVersion: string;
minFeeA: number;
minFeeB: number;
maxTxSize: number;
maxTxExUnits: { cpu: bigint; mem: bigint };
coinsPerUtxoByte: bigint;
error?: string;
}

Integration Examples

Pre-Transaction Check

import { diagnose, isHealthy } from 'cardano-devkit';

async function sendPaymentSafe(recipient: string, amount: bigint) {
// Quick health check
if (!await isHealthy(devKit)) {
const diag = await diagnose(devKit);
throw new Error(`System unhealthy: ${diag.suggestions.join(', ')}`);
}

// Proceed with transaction
const lucid = devKit.getLucid();
const tx = await lucid.newTx()
.pay.ToAddress(recipient, { lovelace: amount })
.complete();

return await tx.sign.withWallet().complete().then(s => s.submit());
}

Application Startup

import { diagnose, printDiagnostics } from 'cardano-devkit';

async function initializeApp() {
const devKit = createDevKit({ network: 'Preprod' });
await devKit.init();

// Run diagnostics
const diagnostics = await diagnose(devKit);

// Show status
printDiagnostics(diagnostics);

// Handle issues
if (diagnostics.overall === 'unhealthy') {
throw new Error('Cannot start: ' + diagnostics.suggestions[0]);
}

if (diagnostics.overall === 'degraded') {
console.warn('Warning:', diagnostics.suggestions.join('\n'));
}

return devKit;
}

Monitoring Health

import { isHealthy, diagnose } from 'cardano-devkit';

// Periodic health check
setInterval(async () => {
if (!await isHealthy(devKit)) {
const diag = await diagnose(devKit);

// Send alert
notifyAdmin({
status: diag.overall,
network: diag.network.status,
wallet: diag.wallet.status,
suggestions: diag.suggestions,
});
}
}, 60000); // Check every minute

CLI Integration

The diagnostics are integrated into the CLI:

# Run full diagnostics
cardano-devkit diagnose

# Quick health check
cardano-devkit health

# Check specific component
cardano-devkit diagnose --network
cardano-devkit diagnose --wallet
cardano-devkit diagnose --protocol

Namespace Import

All diagnostic utilities are available via the main exports:

import {
diagnose,
checkNetwork,
checkWallet,
checkProtocol,
isHealthy,
quickBalance,
formatDiagnostics,
printDiagnostics,
} from 'cardano-devkit';

TypeScript Types

import type {
DiagnosticResult,
DiagnosticStatus,
NetworkDiagnostics,
WalletDiagnostics,
ProtocolDiagnostics,
QuickBalance,
} from 'cardano-devkit';

Best Practices

1. Check Before Critical Operations

Always verify health before important transactions:

if (!await isHealthy(devKit)) {
const diag = await diagnose(devKit);
logger.error('Health check failed', { suggestions: diag.suggestions });
return;
}

2. Use Quick Methods for Frequent Checks

For performance, use isHealthy() and quickBalance() for frequent checks, and diagnose() only when issues are detected.

3. Act on Suggestions

The diagnostic result includes actionable suggestions:

const diag = await diagnose(devKit);
for (const suggestion of diag.suggestions) {
console.log('Action needed:', suggestion);
}

4. Monitor in Production

Set up periodic health monitoring:

async function healthMonitor() {
const healthy = await isHealthy(devKit);
if (!healthy) {
// Alert, log, or take corrective action
}
}