Skip to content
Merged
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
170 changes: 44 additions & 126 deletions src/components/StellarReceive.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import {
TransactionBuilder,
Operation,
Expand All @@ -12,13 +12,11 @@ import {
import {
deriveStealthKeys,
encodeStealthMetaAddress,
scanAnnouncements,
signStellarTransaction,
bytesToHex,
STEALTH_SIGNING_MESSAGE,
SCHEME_ID,
} from '@wraith-protocol/sdk/chains/stellar';
import type { Announcement, MatchedAnnouncement } from '@wraith-protocol/sdk/chains/stellar';
import type { MatchedAnnouncement } from '@wraith-protocol/sdk/chains/stellar';
import { useStealthKeys } from '@/context/StealthKeysContext';
import { useStellarWallet } from '@/context/StellarWalletContext';
import { StellarMatchCard } from '@/components/StellarMatchCard';
Expand All @@ -28,115 +26,6 @@ import { STELLAR_NETWORK } from '@/config';
const ANNOUNCER_CONTRACT = 'CCJLJ2QRBJAAKIG6ELNQVXLLWMKKWVN5O2FKWUETHZGMPAD4MHK7WVWL';
const REGISTRY_CONTRACT = 'CC2LAUCXYOPJ4DV4CYXNXYAXRDVOTMAWFF76W4WFD5OVQBD6TN4PYYJ5';

async function fetchAnnouncementEvents(
rpcUrl: string,
contractId: string,
): Promise<Announcement[]> {
const all: Announcement[] = [];

try {
let startLedger = 1;
const probeRes = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 0,
method: 'getEvents',
params: {
startLedger: 1,
filters: [{ type: 'contract', contractIds: [contractId] }],
pagination: { limit: 1 },
},
}),
});
const probeData = await probeRes.json();

if (probeData.error?.message) {
const match = probeData.error.message.match(/range:\s*(\d+)\s*-\s*(\d+)/);
if (match) {
const oldest = parseInt(match[1], 10);
const latest = parseInt(match[2], 10);
startLedger = Math.max(oldest, latest - 5000);
} else {
return all;
}
}

let cursor: string | undefined;
let hasMore = true;

while (hasMore) {
const params: Record<string, unknown> = {
filters: [{ type: 'contract', contractIds: [contractId] }],
pagination: { limit: 1000 },
};

if (cursor) {
(params.pagination as Record<string, unknown>).cursor = cursor;
} else {
params.startLedger = startLedger;
}

const res = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'getEvents', params }),
});

const data = await res.json();
const events = data.result?.events ?? [];

for (const event of events) {
try {
const ann = parseAnnouncementEvent(event);
if (ann) all.push(ann);
} catch {
// Skip malformed
}
}

if (events.length < 1000) {
hasMore = false;
} else {
cursor = data.result?.cursor;
if (!cursor) hasMore = false;
}
}
} catch {
// Events API may not be available
}

return all;
}

function parseAnnouncementEvent(event: Record<string, unknown>): Announcement | null {
const topics = event.topic as string[];
if (!topics || topics.length < 3) return null;

const schemeIdScVal = xdr.ScVal.fromXDR(topics[1], 'base64');
const schemeId = schemeIdScVal.u32();

const stealthScVal = xdr.ScVal.fromXDR(topics[2], 'base64');
const stealthScAddress = stealthScVal.address();
const stealthAddress = Address.fromScAddress(stealthScAddress).toString();

const valueScVal = xdr.ScVal.fromXDR(event.value as string, 'base64');
const valueVec = valueScVal.vec();
if (!valueVec || valueVec.length < 3) return null;

const callerScAddress = valueVec[0].address();
const caller = Address.fromScAddress(callerScAddress).toString();

const ephBytes = valueVec[1].bytes();
const ephemeralPubKey = bytesToHex(new Uint8Array(ephBytes));

const metaBytes = valueVec[2].bytes();
const metadata = bytesToHex(new Uint8Array(metaBytes));

return { schemeId, stealthAddress, caller, ephemeralPubKey, metadata };
}

function StellarMatchCardContainer({
match,
onWithdrawn,
Expand Down Expand Up @@ -376,6 +265,15 @@ export function StellarReceive() {
const [isDerivingKeys, setIsDerivingKeys] = useState(false);
const [isScanning, setIsScanning] = useState(false);
const [matched, setMatched] = useState<MatchedAnnouncement[]>([]);
const workerRef = useRef<Worker | null>(null);

useEffect(() => {
return () => {
if (workerRef.current) {
workerRef.current.terminate();
}
};
}, []);
const [hasScanned, setHasScanned] = useState(false);
const [error, setError] = useState('');
const [isRegistering, setIsRegistering] = useState(false);
Expand Down Expand Up @@ -521,22 +419,42 @@ export function StellarReceive() {
if (!stellarKeys) return;
setIsScanning(true);
setError('');

try {
const announcements = await fetchAnnouncementEvents(
STELLAR_NETWORK.rpcUrl,
ANNOUNCER_CONTRACT,
);
const results = scanAnnouncements(
announcements,
stellarKeys.viewingKey,
stellarKeys.spendingPubKey,
stellarKeys.spendingScalar,
if (workerRef.current) {
workerRef.current.terminate();
}

workerRef.current = new Worker(
new URL('../workers/stellar-scanner.worker.ts', import.meta.url),
{ type: 'module' },
);
setMatched(results);
setHasScanned(true);

workerRef.current.onmessage = (e) => {
if (e.data.type === 'SUCCESS') {
setMatched(e.data.results);
setHasScanned(true);
setIsScanning(false);
} else if (e.data.type === 'ERROR') {
setError(e.data.error);
setIsScanning(false);
}
};

workerRef.current.onerror = () => {
setError('Worker crashed');
setIsScanning(false);
};

workerRef.current.postMessage({
rpcUrl: STELLAR_NETWORK.rpcUrl,
announcerContract: ANNOUNCER_CONTRACT,
viewingKey: stellarKeys.viewingKey,
spendingPubKey: stellarKeys.spendingPubKey,
spendingScalar: stellarKeys.spendingScalar,
});
} catch (err) {
setError(err instanceof Error ? err.message : 'Scan failed');
} finally {
setError(err instanceof Error ? err.message : 'Failed to start worker');
setIsScanning(false);
}
}, [stellarKeys]);
Expand Down
135 changes: 135 additions & 0 deletions src/workers/stellar-scanner.worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import {
scanAnnouncements,
bytesToHex,
} from '@wraith-protocol/sdk/chains/stellar';
import type { Announcement } from '@wraith-protocol/sdk/chains/stellar';
import { Address, xdr } from '@stellar/stellar-sdk';

async function fetchAnnouncementEvents(
rpcUrl: string,
contractId: string,
): Promise<Announcement[]> {
const all: Announcement[] = [];

try {
let startLedger = 1;
const probeRes = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 0,
method: 'getEvents',
params: {
startLedger: 1,
filters: [{ type: 'contract', contractIds: [contractId] }],
pagination: { limit: 1 },
},
}),
});
const probeData = await probeRes.json();

if (probeData.error?.message) {
const match = probeData.error.message.match(/range:\s*(\d+)\s*-\s*(\d+)/);
if (match) {
const oldest = parseInt(match[1], 10);
const latest = parseInt(match[2], 10);
startLedger = Math.max(oldest, latest - 5000);
} else {
return all;
}
}

let cursor: string | undefined;
let hasMore = true;

while (hasMore) {
const params: Record<string, unknown> = {
filters: [{ type: 'contract', contractIds: [contractId] }],
pagination: { limit: 1000 },
};

if (cursor) {
(params.pagination as Record<string, unknown>).cursor = cursor;
} else {
params.startLedger = startLedger;
}

const res = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'getEvents', params }),
});

const data = await res.json();
const events = data.result?.events ?? [];

for (const event of events) {
try {
const ann = parseAnnouncementEvent(event);
if (ann) all.push(ann);
} catch {
// Skip malformed
}
}

if (events.length < 1000) {
hasMore = false;
} else {
cursor = data.result?.cursor;
if (!cursor) hasMore = false;
}
}
} catch {
// Events API may not be available
}

return all;
}

function parseAnnouncementEvent(event: Record<string, unknown>): Announcement | null {
const topics = event.topic as string[];
if (!topics || topics.length < 3) return null;

const schemeIdScVal = xdr.ScVal.fromXDR(topics[1], 'base64');
const schemeId = schemeIdScVal.u32();

const stealthScVal = xdr.ScVal.fromXDR(topics[2], 'base64');
const stealthScAddress = stealthScVal.address();
const stealthAddress = Address.fromScAddress(stealthScAddress).toString();

const valueScVal = xdr.ScVal.fromXDR(event.value as string, 'base64');
const valueVec = valueScVal.vec();
if (!valueVec || valueVec.length < 3) return null;

const callerScAddress = valueVec[0].address();
const caller = Address.fromScAddress(callerScAddress).toString();

const ephBytes = valueVec[1].bytes();
const ephemeralPubKey = bytesToHex(new Uint8Array(ephBytes));

const metaBytes = valueVec[2].bytes();
const metadata = bytesToHex(new Uint8Array(metaBytes));

return { schemeId, stealthAddress, caller, ephemeralPubKey, metadata };
}

self.onmessage = async (e: MessageEvent) => {
const { rpcUrl, announcerContract, viewingKey, spendingPubKey, spendingScalar } = e.data;

try {
const announcements = await fetchAnnouncementEvents(rpcUrl, announcerContract);
const results = scanAnnouncements(
announcements,
viewingKey,
spendingPubKey,
spendingScalar,
);
self.postMessage({ type: 'SUCCESS', results });
} catch (err) {
self.postMessage({
type: 'ERROR',
error: err instanceof Error ? err.message : 'Scan failed in worker'
});
}
};