loop-agent-sdk 0.1.0

Trustless agent SDK for Loop Protocol — intent-based execution on Solana.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Supabase Integration for Reputation Engine
//!
//! Fetches attestations from the Supabase `attestations` table
//! and hydrates the ReputationEngine for score calculation.

use crate::reputation_engine::{
    AttestationMetadata, AttestationRecord, CaptureLayer, ReputationEngine,
};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, error, info, warn};

/// Supabase configuration
#[derive(Debug, Clone)]
pub struct SupabaseConfig {
    /// Supabase project URL (e.g., https://xxx.supabase.co)
    pub url: String,
    /// Service role key (for server-side access)
    pub service_role_key: String,
}

impl SupabaseConfig {
    /// Create from environment variables
    pub fn from_env() -> Result<Self, String> {
        let url = std::env::var("SUPABASE_URL")
            .map_err(|_| "Missing SUPABASE_URL environment variable")?;
        let service_role_key = std::env::var("SUPABASE_SERVICE_ROLE_KEY")
            .map_err(|_| "Missing SUPABASE_SERVICE_ROLE_KEY environment variable")?;

        Ok(Self {
            url,
            service_role_key,
        })
    }
}

/// Raw attestation row from Supabase
#[derive(Debug, Deserialize)]
pub struct SupabaseAttestation {
    pub id: String,
    pub user_id: String,
    pub layer_id: Option<i32>,
    pub layer_group: Option<String>,
    #[serde(rename = "type")]
    pub attestation_type: String,
    pub weight: i32,
    pub is_positive: bool,
    pub metadata_json: Option<serde_json::Value>,
    pub verified: bool,
    pub source: String,
    pub source_tx: Option<String>,
    pub created_at: String,
    pub expires_at: Option<String>,
    pub deleted_at: Option<String>,
}

/// Reputation score response from Supabase function
#[derive(Debug, Deserialize)]
pub struct SupabaseReputationScore {
    pub composite: i32,
    pub reliability: i32,
    pub skill: i32,
    pub social: i32,
    pub tenure: i32,
    pub infrastructure: i32,
    pub tier: String,
}

/// Supabase client for reputation data
pub struct SupabaseClient {
    config: SupabaseConfig,
    http: Client,
}

impl SupabaseClient {
    /// Create new Supabase client
    pub fn new(config: SupabaseConfig) -> Self {
        Self {
            config,
            http: Client::new(),
        }
    }

    /// Create from environment variables
    pub fn from_env() -> Result<Self, String> {
        let config = SupabaseConfig::from_env()?;
        Ok(Self::new(config))
    }

    /// Fetch all attestations for a user
    pub async fn fetch_attestations(
        &self,
        user_id: &str,
    ) -> Result<Vec<SupabaseAttestation>, String> {
        let url = format!(
            "{}/rest/v1/attestations?user_id=eq.{}&deleted_at=is.null&order=created_at.desc",
            self.config.url, user_id
        );

        let response = self
            .http
            .get(&url)
            .header("apikey", &self.config.service_role_key)
            .header("Authorization", format!("Bearer {}", self.config.service_role_key))
            .header("Content-Type", "application/json")
            .send()
            .await
            .map_err(|e| format!("HTTP request failed: {}", e))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(format!("Supabase error {}: {}", status, body));
        }

        let attestations: Vec<SupabaseAttestation> = response
            .json()
            .await
            .map_err(|e| format!("JSON parse error: {}", e))?;

        debug!("Fetched {} attestations for user {}", attestations.len(), user_id);
        Ok(attestations)
    }

    /// Fetch reputation score using the Supabase function
    pub async fn fetch_reputation_score(
        &self,
        user_id: &str,
    ) -> Result<Option<SupabaseReputationScore>, String> {
        let url = format!(
            "{}/rest/v1/rpc/calculate_reputation_score",
            self.config.url
        );

        let body = serde_json::json!({
            "p_user_id": user_id
        });

        let response = self
            .http
            .post(&url)
            .header("apikey", &self.config.service_role_key)
            .header("Authorization", format!("Bearer {}", self.config.service_role_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| format!("HTTP request failed: {}", e))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(format!("Supabase error {}: {}", status, body));
        }

        // The RPC returns an array with one row
        let scores: Vec<SupabaseReputationScore> = response
            .json()
            .await
            .map_err(|e| format!("JSON parse error: {}", e))?;

        Ok(scores.into_iter().next())
    }

    /// Add a new attestation
    pub async fn add_attestation(
        &self,
        user_id: &str,
        layer_id: Option<i32>,
        attestation_type: &str,
        weight: i32,
        is_positive: bool,
        metadata: Option<serde_json::Value>,
        source: &str,
        source_tx: Option<&str>,
        verified: bool,
    ) -> Result<String, String> {
        let url = format!("{}/rest/v1/attestations", self.config.url);

        // Map layer_id to layer_group
        let layer_group = layer_id.map(|id| match id {
            1..=6 => "passive_utility",
            7..=11 => "infrastructure",
            12..=16 => "intelligence",
            17..=22 => "aggressive_autopilot",
            _ => "passive_utility",
        });

        let body = serde_json::json!({
            "user_id": user_id,
            "layer_id": layer_id,
            "layer_group": layer_group,
            "type": attestation_type,
            "weight": weight,
            "is_positive": is_positive,
            "metadata_json": metadata.unwrap_or(serde_json::json!({})),
            "source": source,
            "source_tx": source_tx,
            "verified": verified,
            "verified_at": if verified { Some(chrono::Utc::now().to_rfc3339()) } else { None },
            "verified_by": if verified { Some("system") } else { None },
        });

        let response = self
            .http
            .post(&url)
            .header("apikey", &self.config.service_role_key)
            .header("Authorization", format!("Bearer {}", self.config.service_role_key))
            .header("Content-Type", "application/json")
            .header("Prefer", "return=representation")
            .json(&body)
            .send()
            .await
            .map_err(|e| format!("HTTP request failed: {}", e))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            return Err(format!("Supabase error {}: {}", status, body));
        }

        let created: Vec<serde_json::Value> = response
            .json()
            .await
            .map_err(|e| format!("JSON parse error: {}", e))?;

        let id = created
            .first()
            .and_then(|v| v.get("id"))
            .and_then(|v| v.as_str())
            .unwrap_or("unknown")
            .to_string();

        info!("Created attestation {} for user {}", id, user_id);
        Ok(id)
    }
}

/// Convert Supabase attestation type string to CaptureLayer
fn map_attestation_type_to_layer(attestation_type: &str, layer_id: Option<i32>) -> CaptureLayer {
    // If layer_id is provided, use it directly
    if let Some(id) = layer_id {
        return match id {
            1 => CaptureLayer::Shopping,
            2 => CaptureLayer::Referral,
            3 => CaptureLayer::Attention,
            4 => CaptureLayer::Data,
            5 => CaptureLayer::Insurance,
            6 => CaptureLayer::Compute,
            7 => CaptureLayer::Network,
            8 => CaptureLayer::Energy,
            9 => CaptureLayer::DePINAggregator,
            10 => CaptureLayer::InferenceArbitrage,
            11 => CaptureLayer::StorageDePIN,
            12 => CaptureLayer::Skill,
            13 => CaptureLayer::CurationSignal,
            14 => CaptureLayer::Social,
            15 => CaptureLayer::KnowledgeAPI,
            16 => CaptureLayer::PersonalModelLicensing,
            17 => CaptureLayer::Liquidity,
            18 => CaptureLayer::GovernanceProxy,
            19 => CaptureLayer::InventoryArbitrage,
            20 => CaptureLayer::SubAgentManager,
            21 => CaptureLayer::ReputationCollateral,
            22 => CaptureLayer::SwarmCoordinationFee,
            _ => CaptureLayer::Shopping,
        };
    }

    // Otherwise, infer from attestation type
    match attestation_type {
        // Reliability types → Shopping layer
        "vault_created" | "stack_initiated" | "stack_completed" | "yield_claimed"
        | "yield_compounded" | "early_withdrawal" | "transaction_failed" => CaptureLayer::Shopping,

        // Skill types → Skill layer
        "certification_submitted" | "certification_verified" | "expertise_demonstrated"
        | "api_contribution" => CaptureLayer::Skill,

        // Social types → Social layer
        "referral_given" | "referral_received" | "community_contribution" | "governance_vote" => {
            CaptureLayer::Social
        }

        // Tenure types → Shopping (base activity)
        "daily_login" | "weekly_active" | "monthly_milestone" | "anniversary" => {
            CaptureLayer::Shopping
        }

        // Infrastructure types → Network layer
        "node_registered" | "bandwidth_contributed" | "compute_contributed"
        | "storage_contributed" => CaptureLayer::Network,

        // Default
        _ => CaptureLayer::Shopping,
    }
}

/// Convert Supabase attestation to SDK AttestationRecord
fn convert_to_attestation_record(supabase: &SupabaseAttestation) -> AttestationRecord {
    let layer = map_attestation_type_to_layer(&supabase.attestation_type, supabase.layer_id);

    // Parse timestamp
    let timestamp = chrono::DateTime::parse_from_rfc3339(&supabase.created_at)
        .map(|dt| dt.timestamp() as u64)
        .unwrap_or(0);

    // Parse metadata
    let metadata = supabase.metadata_json.as_ref().and_then(|json| {
        let mut meta = AttestationMetadata::default();

        if let Some(obj) = json.as_object() {
            if let Some(days) = obj.get("durationDays").and_then(|v| v.as_i64()) {
                meta.lock_duration_days = Some(days as u16);
            }
            if let Some(days) = obj.get("lock_duration_days").and_then(|v| v.as_i64()) {
                meta.lock_duration_days = Some(days as u16);
            }
            if let Some(held) = obj.get("held_to_maturity").and_then(|v| v.as_bool()) {
                meta.held_to_maturity = Some(held);
            }
            if let Some(acc) = obj.get("accuracy_percent").and_then(|v| v.as_i64()) {
                meta.accuracy_percent = Some(acc as u8);
            }
            if let Some(uptime) = obj.get("uptime_percent").and_then(|v| v.as_i64()) {
                meta.uptime_percent = Some(uptime as u8);
            }
            // VPA fields
            if let Some(tier) = obj.get("difficulty_tier").and_then(|v| v.as_i64()) {
                meta.difficulty_tier = Some(tier as u8);
            }
            if let Some(mult) = obj.get("verification_multiplier").and_then(|v| v.as_f64()) {
                meta.verification_multiplier = Some(mult as f32);
            }
        }

        Some(meta)
    });

    // Use weight directly as magnitude (Supabase weights are typically 10-200)
    let magnitude = (supabase.weight as u64) * 10_000; // Scale up for scoring

    AttestationRecord {
        layer,
        timestamp,
        positive: supabase.is_positive,
        magnitude,
        metadata,
    }
}

/// Extension trait for ReputationEngine to load from Supabase
impl ReputationEngine {
    /// Load attestations from Supabase and process them
    pub async fn load_from_supabase(&mut self, client: &SupabaseClient) -> Result<usize, String> {
        let attestations = client.fetch_attestations(&self.user_pubkey).await?;
        let count = attestations.len();

        for supabase_att in &attestations {
            let record = convert_to_attestation_record(supabase_att);
            self.process_attestation(&record);
        }

        info!(
            "Loaded {} attestations from Supabase for user {}",
            count, self.user_pubkey
        );
        Ok(count)
    }

    /// Create engine and load from Supabase in one step
    pub async fn from_supabase(
        user_pubkey: String,
        client: &SupabaseClient,
    ) -> Result<Self, String> {
        let mut engine = Self::new(user_pubkey);
        engine.load_from_supabase(client).await?;
        Ok(engine)
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_layer_mapping() {
        assert_eq!(
            map_attestation_type_to_layer("stack_initiated", None),
            CaptureLayer::Shopping
        );
        assert_eq!(
            map_attestation_type_to_layer("certification_verified", None),
            CaptureLayer::Skill
        );
        assert_eq!(
            map_attestation_type_to_layer("referral_given", None),
            CaptureLayer::Social
        );
        assert_eq!(
            map_attestation_type_to_layer("node_registered", None),
            CaptureLayer::Network
        );
    }

    #[test]
    fn test_layer_id_override() {
        // layer_id should override the type-based mapping
        assert_eq!(
            map_attestation_type_to_layer("stack_initiated", Some(12)),
            CaptureLayer::Skill
        );
    }

    #[test]
    fn test_convert_attestation() {
        let supabase = SupabaseAttestation {
            id: "test-id".to_string(),
            user_id: "test-user".to_string(),
            layer_id: Some(1),
            layer_group: Some("passive_utility".to_string()),
            attestation_type: "stack_initiated".to_string(),
            weight: 50,
            is_positive: true,
            metadata_json: Some(serde_json::json!({
                "durationDays": 90,
                "amount": 100000000
            })),
            verified: true,
            source: "api".to_string(),
            source_tx: None,
            created_at: "2024-03-27T00:00:00Z".to_string(),
            expires_at: None,
            deleted_at: None,
        };

        let record = convert_to_attestation_record(&supabase);
        assert_eq!(record.layer, CaptureLayer::Shopping);
        assert!(record.positive);
        assert!(record.metadata.is_some());
        assert_eq!(record.metadata.unwrap().lock_duration_days, Some(90));
    }
}