SkateSpots/RELATR_INTEGRATION.md
shakespeare.diy 27e14994b5 Import files from skate-spots project
Co-authored-by: shakespeare.diy <assistant@shakespeare.diy>
2026-06-15 20:04:15 +07:00

300 lines
8.9 KiB
Markdown

# Relatr Integration Guide
## Overview
**Relatr** ([https://www.relatr.xyz/](https://www.relatr.xyz/)) is a decentralized Web of Trust service for Nostr that provides global trust scores based on social graph analysis and profile validation.
**GitHub**: [https://github.com/ContextVM/relatr](https://github.com/ContextVM/relatr)
## ✅ Integration Method: NIP-85 (Trusted Assertions)
Relatr publishes trust scores as **Nostr events** using **NIP-85** (kind 30382). This is the Nostr-native approach - no external API needed!
## Current Status
### ✅ What's Implemented
SkateSpots currently uses a **local Web of Trust (WoT)** implementation:
- **Algorithm**: Client-side social graph analysis
- **Data source**: User's follow list (kind 3) + friends' follows
- **Scoring**:
- 100 = Self
- 90 = Direct follow
- 60 = Friend-of-friend (2 hops)
- 30 = NIP-05 verified
- 0 = Unknown
- **Performance**: Fast, works offline, privacy-preserving
- **Limitation**: Only knows about your social graph (not global)
### 🔮 Relatr Integration (Planned)
Relatr provides **global trust scores** computed server-side using:
- Social graph distances (multiple hops)
- NIP-05 validation
- Lightning address verification
- Reciprocity checking
- Configurable weighting schemes
## Integration Architecture
### Hybrid Approach (Recommended)
Combine local WoT with Relatr for best results:
```typescript
async function getTrustScore(source: string, target: string): Promise<number> {
// 1. Try local WoT first (instant, offline-capable)
const localScore = await calculateLocalWoT(source, target);
// 2. Fetch Relatr score in background (global perspective)
const relatrScore = await relatrClient.getScore(source, target);
// 3. Blend scores or use Relatr as fallback
if (localScore >= 90) {
return localScore; // Trust your direct follows
}
if (relatrScore && relatrScore.score > localScore) {
return relatrScore.score; // Relatr found stronger trust signal
}
return localScore; // Use local score
}
```
### Integration Options
#### Option 1: Fallback Only
- Use local WoT by default
- Query Relatr only when local score is 0
- **Pros**: Fast, minimal API calls
- **Cons**: Misses global trust signals
#### Option 2: Blended Scoring
- Calculate both local and Relatr scores
- Take the maximum or weighted average
- **Pros**: Best of both worlds
- **Cons**: Requires API calls for every pubkey
#### Option 3: Relatr Primary
- Query Relatr first
- Fall back to local WoT if unavailable
- **Pros**: Global perspective
- **Cons**: Slower, requires internet
## Implementation Steps
### 1. Determine Relatr API Structure
Relatr is documented as an **MCP Server** (Model Context Protocol), not a traditional REST API. This requires:
**Option A: MCP Client Integration**
```bash
npm install @modelcontextprotocol/sdk
```
**Option B: REST API (if available)**
- Endpoint discovery needed
- Authentication requirements
- Rate limits
**Option C: Nostr Events**
- Relatr may publish trust scores as Nostr events
- Query via existing Nostr infrastructure
### 2. Test Relatr Service
```bash
# Test if REST API exists
curl https://api.relatr.xyz/v1/health
# Test MCP server
# (requires MCP client setup)
# Check for Nostr event-based scores
# (query kind 10050 or similar Trusted Assertion events)
```
### 3. Update Code
**Files to modify:**
1. **`src/lib/relatr.ts`** - Implement actual API client
2. **`src/hooks/useTrustScore.ts`** - Add Relatr fallback
3. **`src/hooks/useBatchTrustScores.ts`** - Add Relatr batch support
4. **`src/pages/CommunityStatsPage.tsx`** - Show Relatr vs local comparison
### 4. Configuration
Add settings for Relatr integration:
```typescript
// src/lib/config.ts
export const RELATR_CONFIG = {
enabled: false, // Toggle in settings
apiUrl: 'https://api.relatr.xyz',
mcpServerUrl: 'https://www.relatr.xyz',
fallbackToLocal: true, // Use local WoT if Relatr fails
blendScores: true, // Combine local + Relatr scores
timeout: 10000, // API timeout (ms)
};
```
## Relatr Features to Leverage
Based on [Relatr's README](https://github.com/ContextVM/relatr):
### Key Capabilities
1. **Social Graph Analysis** - Uses `nostr-social-duck` for graph distances
2. **Profile Validation** - Validates NIP-05, Lightning addresses
3. **Reciprocity Checking** - Mutual follow relationships
4. **Configurable Scoring** - Weighted trust factors
5. **Trusted Assertions (TA)** - NIP-85 trust rank publishing
### Integration Benefits
- 🌍 **Global perspective** - Not limited to your social graph
- 📊 **Deeper analysis** - Multi-hop traversal beyond 2 hops
- ✅ **Profile validation** - NIP-05 + Lightning address checks
- 🔄 **Reciprocity** - Identifies mutual trust relationships
- 📈 **Better spam detection** - More sophisticated scoring
## Example Integration
### Modified `useTrustScore` Hook
```typescript
import { RELATR_ENABLED, relatrClient, normalizeRelatrScore } from '@/lib/relatr';
export function useTrustScore(targetPubkey: string | undefined) {
const { nostr } = useNostr();
const { user } = useCurrentUser();
return useQuery({
queryKey: ['trust-score', targetPubkey, user?.pubkey, RELATR_ENABLED],
queryFn: async (c) => {
if (!targetPubkey) return undefined;
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const sourcePubkey = user?.pubkey || '20e7c953...';
// Try Relatr first if enabled
if (RELATR_ENABLED) {
try {
const relatrScore = await relatrClient.getScore(sourcePubkey, targetPubkey);
if (relatrScore) {
const normalized = normalizeRelatrScore(relatrScore.score);
console.log(`[Relatr] Score for ${targetPubkey.slice(0,8)}: ${normalized}`);
return normalized;
}
} catch (error) {
console.warn('[Relatr] API failed, falling back to local WoT:', error);
}
}
// Fallback: Local WoT calculation
return await calculateLocalWoT(nostr, sourcePubkey, targetPubkey, signal);
},
// ... rest of config
});
}
```
## Testing Plan
### Phase 1: API Discovery
- [ ] Determine actual Relatr API structure (REST vs MCP vs Nostr events)
- [ ] Test API endpoints with sample requests
- [ ] Document authentication requirements
- [ ] Measure response times and rate limits
### Phase 2: Integration
- [ ] Implement Relatr client in `src/lib/relatr.ts`
- [ ] Add feature flag in settings
- [ ] Update `useTrustScore` with fallback logic
- [ ] Update `useBatchTrustScores` for batch requests
### Phase 3: Testing
- [ ] Test with various pubkeys (followed, friends-of-friends, unknown)
- [ ] Verify score normalization
- [ ] Test offline behavior (should fall back gracefully)
- [ ] Performance testing (ensure < 1s response times)
### Phase 4: Analytics
- [ ] Add "Powered by Relatr" badge to stats page
- [ ] Show comparison: Local WoT vs Relatr scores
- [ ] Display Relatr metadata (distance, NIP-05, LUD16 status)
## How It Works (NIP-85)
### Event Format
Relatr publishes kind 30382 events (User Trust Assertions):
```json
{
"kind": 30382,
"pubkey": "<relatr-service-pubkey>",
"tags": [
["d", "<target-user-pubkey>"],
["rank", "85"], // Trust score 0-100
["followers", "1234"], // Follower count
["post_cnt", "567"], // Number of posts
["zap_amt_recd", "50000"], // Sats received
// ... other metrics
],
"content": ""
}
```
### Integration Steps
**Step 1**: Find Relatr's Service Pubkey
- Visit https://www.relatr.xyz/about
- Look for their npub or hex pubkey
- OR query Nostr: `kinds: [0], search: "relatr"`
**Step 2**: Enable in Settings
- Go to Settings → Advanced → Relatr Integration
- Enter service pubkey (or click Auto-Discover)
- Click "Enable Relatr"
**Step 3**: Query Trust Scores
```typescript
import { useRelatrScore } from '@/hooks/useRelatrScore';
// Query Relatr's NIP-85 assertion for a user
const { data: relatrScore } = useRelatrScore(targetPubkey);
if (relatrScore) {
console.log('Global trust rank:', relatrScore.rank); // 0-100
console.log('Followers:', relatrScore.followers);
console.log('Posts:', relatrScore.postCount);
}
```
**No API keys, no authentication needed** - just query Nostr events!
## Resources
- **Relatr Website**: https://www.relatr.xyz/
- **GitHub Repo**: https://github.com/ContextVM/relatr
- **ContextVM Org**: https://github.com/ContextVM
- **Contact**: Check Relatr GitHub issues or ContextVM Nostr account
## Next Steps
1. **Contact Relatr Team** - Get API documentation or examples
2. **Test API** - Verify endpoints work and understand response format
3. **Implement Client** - Complete `src/lib/relatr.ts` with actual API
4. **Add Feature Flag** - Toggle Relatr integration in settings
5. **Update UI** - Show "Powered by Relatr" when enabled
6. **Monitor Performance** - Ensure < 1s response times for good UX
---
**Status**: Waiting for Relatr API documentation to complete integration.
**ETA**: Can be completed in 2-3 hours once API structure is confirmed.