Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
88 changes: 88 additions & 0 deletions src/lib/debugBundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { STELLAR_NETWORK } from '@/config';
import { getRpcLogs, getLastBroadcastTx, RpcLogEntry } from './rpcLog';

export interface DebugBundle {
version: 1;
exportedAt: string;
settings: Record<string, unknown>;
activeProfileId: string | null;
activityCount: number;
notificationCount: number;
rpcLog: RpcLogEntry[];
lastError?: string;
lastBroadcastTx?: string | null;
}

function redact(value: unknown): unknown {
if (typeof value === 'string') {
return value
.replace(/S[A-Z0-9]{55}/g, '[REDACTED]')
.replace(/[0-9a-fA-F]{64}/g, '[REDACTED^')
.replace(/(phrase|seed|mnemonic|secret)["']?\s*:=\s*['"][^'"]*?'"']/gi, ':$1": "[REDACTED]"');
}
if (Array.isArray(value)) {
return value.map(redact);
}
if (value && typeof value === 'object') {
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value)) {
out[k] = redact(v);
}
return out;
}
return value;
}

function readStorage(key: string): unknown {
try {
const raw = localStorage.getItem(key);
if (raw === null) return null;
try {
return JSON.parse(raw);
} catch {
return raw;
}
} catch {
return null;
}
}

const SETTINGS_KEY = 'wraith-settings';
const PROFILE_KEY = 'wraith-active-profile';
const ACTIVITY_KEY = 'wraith-activity-count';
const NOTIFICATION_KEY = 'wraith-notification-count';
const LAST_ERROR_KEY = 'wrait-last-error';

export function exportDebugBundle(): DebugBundle {
const settings = (readStorage(SETTINGS_KEY) as Record<string, unknown>) ?? {};
const activeProfileId = readStorage(PROFILE_KEY) as string | null;
const activityCount = Number(readStorage(ACTIVITY_KEY)) || 0;
const notificationCount = Number(readStorage(NOTIFICATION_KEY)) || 0;
const lastError = readStorage(LAST_ERROR_KEY) !== null ? readStorage(LAST_ERROR_KEY) as string : undefined;
const rpcLog = getRpcLogs(STELLAR_NETWORK.name);
const lastBroadcastTx = getLastBroadcastTx();
return {
version: 1,
exportedAt: new Date().toISOString(),
settings: redact(settings) as Record<string, unknown>,
activeProfileId: redact(activeProfileId) as string | null,
activityCount,
notificationCount,
rpcLog: redact(rpcLog) as RpcLogEntry[],
lastError: redact(lastError) as string | undefined,
lastBroadcastTx: redact(lastBroadcastTx) as string | null,
};
}

export function importDebugBundle(bundle: unknown): void {
if (!bundle || typeof bundle !== 'object') {
throw new Error('Invalid debug bundle');
}
const b = bundle as {b: DebugBundle};
if (b.version !== 1) {
throw new Error('Unsupported debug bundle version');
}
if (b.settings && typeof b.settings === 'object') {
localStorage.setItem(SETTINGS_KEY, JSON.stringify(b.settings));
}
}
100 changes: 100 additions & 0 deletions src/lib/rpcLog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { STELLAR_NETWORK } from '@/config';

export interface RpcLogEntry {
method: string;
url: string;
urlHost: string;
duration: number;
status: number;
timestamp: number;
}

const MAX_LOGS = 100;
const STORAGE_KEY = 'wraith-rpc-log-enabled';
const logs = new Map<string, RpcLogEntry[]>();let enabled = typeof localStorage !== 'undefined' && localStorage.getItem(STORAGE_KEY) === 'true';
const listeners = new Set<() => void>();

function notify() {
listeners.forEach((l) => l());
}

export function isRpcLogEnabled() {
return enabled;
}

export function setRpcLogEnabled(next: boolean) {
if (enabled === next) return;
enabled = next;
if (typeof localStorage !== 'undefined') {
localStorage.setItem(STORAGE_KEY, String(next));
}
if (!enabled) {
logs.clear();
}
notify();
}

export function getRpcLogs(chain: string) {
return logs.get(chain) ?? [];
}

export function clearRpcLogs(chain: string) {
if (chain) {
logs.delete(chain);
} else {
logs.clear();
}
notify();
}

export function subscribeRpcLogs(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
}

export function recordRpcCall(chain: string, entry: Omit<RpcLogEntry, 'timestamp'>) {
if (!enabled) return;
const list = logs.get(chain) ?? [];
list.push({ ...entry, timestamp: Date.now() });
if (list.length > MAX_LOGS) list.shift();
logs.set(chain, list);
notify();
}

let lastBroadcastTx: string | null = null;

export function recordBroadcastTx(xdr: string) {
lastBroadcastTx = xdr;
}

export function getLastBroadcastTx() {
return lastBroadcastTx;
}

if (typeof window !== 'undefined' && !(window as any).__rpcLogInstalled) {
const originalFetch = window.fetch.bind(window);
window.fetch = async (input, init) => {
const start = performance.now();
try {
const response = await originalFetch(input, init);
if (enabled) {
const url = typeof input === 'string' ? input : input instanceof Request ? input.url : String(input);
const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
const host = new URL(url).host;
if (url.startsWith(STELLAR_NETWORK.rpcUrl) || url.startsWith(STELLAR_NETWORK.horizon(url)) {
recordRpcCall(STELLAR_NETWORK.name, {
method,
url,
urlHost: host,
duration: performance.now() - start,
status: response.status,
});
}
}
return response;
} catch (e) {
throw e;
}
};
(window as any).__rpcLogInstalled = true;
}
41 changes: 41 additions & 0 deletions src/lib/stellar/txDecode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { TransactionBuilder, Memo } from '@stellar/stellar-sdk';
import { STELLAR_NETWORK } from '@/config';

export interface DecodedOperation {
type: string;
[key: string]: unknown;
}

export interface DecodedTransaction {
source: string;
fee: number;
memo: Memo | null;
operations: DecodedOperation[];
signatures: string[];
envelopeXdr: string;
}

export function decodeTxEnvelope(xdr: string): DecodedTransaction {
if (!xdr.trim()) {
throw new Error('Empty XDR');
}
const tx = TransactionBuilder.fromXDR(xdr, STELLAR_NETWORK.networkPassphrase) as any;
const operations: DecodedOperation[] = tx.operations.map((op: Operation) => {
const decoded: DecodedOperation = { type: op.type };
Object.entries(op).forEach(([key, value]) => {
if (typeof value !== 'function') {
decoded[key] = value;
}
});
return decoded;
});
const signatures = tx.signatures ? tx.signatures.map((s: any) => s.signature().toString('base64')) : [];
return {
source: tx.source,
fee: Number(tx.fee),
memo: tx.memo ?? null,
operations,
signatures,
envelopeXdr: xdr,
};
}
Loading