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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Loop Agent SDK - Push Notifications
//! 
//! Lightweight notification layer that:
//! 1. Checks DynamoDB for cached push_token (<5ms)
//! 2. Falls back to Supabase if not cached
//! 3. Caches token in DynamoDB for future use
//! 4. Calls Supabase send-push Edge Function
//! 
//! This keeps 99% of notifications under 100ms.

use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};
use tracing::{info, warn, error, instrument};

// ============================================================================
// CONFIGURATION
// ============================================================================

/// Notification service configuration
#[derive(Debug, Clone)]
pub struct NotificationConfig {
    /// Supabase project URL
    pub supabase_url: String,
    /// Supabase service role key (for calling edge functions)
    pub supabase_service_key: String,
    /// DynamoDB table name
    pub dynamo_table: String,
    /// Cache TTL for push tokens (seconds)
    pub token_cache_ttl: i64,
}

impl NotificationConfig {
    /// Load from environment variables
    pub fn from_env() -> Result<Self, NotificationError> {
        Ok(Self {
            supabase_url: std::env::var("SUPABASE_URL")
                .map_err(|_| NotificationError::MissingConfig("SUPABASE_URL".into()))?,
            supabase_service_key: std::env::var("SUPABASE_SERVICE_ROLE_KEY")
                .map_err(|_| NotificationError::MissingConfig("SUPABASE_SERVICE_ROLE_KEY".into()))?,
            dynamo_table: std::env::var("DYNAMO_TABLE")
                .unwrap_or_else(|_| "loop-agent-state".into()),
            token_cache_ttl: 86400 * 7, // 7 days
        })
    }
}

// ============================================================================
// NOTIFICATION SERVICE
// ============================================================================

/// Push notification service with DynamoDB caching
pub struct NotificationService {
    config: NotificationConfig,
    http_client: reqwest::Client,
    dynamo_client: aws_sdk_dynamodb::Client,
}

impl NotificationService {
    /// Create new notification service
    pub async fn new(config: NotificationConfig) -> Result<Self, NotificationError> {
        let aws_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
        let dynamo_client = aws_sdk_dynamodb::Client::new(&aws_config);
        
        let http_client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(10))
            .build()
            .map_err(|e| NotificationError::InitError(e.to_string()))?;
        
        Ok(Self {
            config,
            http_client,
            dynamo_client,
        })
    }
    
    /// Send push notification to user
    /// 
    /// Flow:
    /// 1. Check DynamoDB cache for push_token
    /// 2. If miss, query Supabase profiles table
    /// 3. Cache token in DynamoDB
    /// 4. Call Supabase send-push edge function
    #[instrument(skip(self))]
    pub async fn send(
        &self,
        user_pubkey: &str,
        notification: &PushNotification,
    ) -> Result<NotificationResult, NotificationError> {
        // Step 1: Try to get push token from DynamoDB cache
        let push_token = match self.get_cached_token(user_pubkey).await? {
            Some(token) => {
                info!(user = %user_pubkey, "Push token found in cache");
                token
            }
            None => {
                // Step 2: Query Supabase for token
                info!(user = %user_pubkey, "Cache miss, querying Supabase");
                let token = self.fetch_token_from_supabase(user_pubkey).await?;
                
                // Step 3: Cache it for next time
                if let Some(ref t) = token {
                    self.cache_token(user_pubkey, t).await?;
                }
                
                token.ok_or(NotificationError::NoToken)?
            }
        };
        
        // Step 4: Send via Supabase edge function
        self.send_via_supabase(&push_token, user_pubkey, notification).await
    }
    
    /// Send capture notification (convenience method)
    pub async fn send_capture_notification(
        &self,
        user_pubkey: &str,
        cred_amount: f64,
        merchant_name: &str,
    ) -> Result<NotificationResult, NotificationError> {
        let notification = PushNotification {
            title: "Cred Captured! 🎉".into(),
            body: format!(
                "You earned {:.2} Cred at {}. Tap to see it grow.",
                cred_amount,
                merchant_name
            ),
            data: Some(NotificationData {
                notification_type: "capture".into(),
                cred_amount: Some(cred_amount),
                merchant_name: Some(merchant_name.into()),
                ..Default::default()
            }),
            sound: Some("default".into()),
            priority: NotificationPriority::High,
            badge: None,
        };
        
        self.send(user_pubkey, &notification).await
    }
    
    /// Send auto-stake notification
    pub async fn send_stake_notification(
        &self,
        user_pubkey: &str,
        cred_amount: f64,
        duration_days: u16,
        apy: f64,
    ) -> Result<NotificationResult, NotificationError> {
        let notification = PushNotification {
            title: "Auto-Staked 📈".into(),
            body: format!(
                "{:.2} Cred staked for {} days at {:.1}% APY",
                cred_amount, duration_days, apy
            ),
            data: Some(NotificationData {
                notification_type: "stake".into(),
                cred_amount: Some(cred_amount),
                ..Default::default()
            }),
            sound: None, // Silent for auto-actions
            priority: NotificationPriority::Normal,
            badge: None,
        };
        
        self.send(user_pubkey, &notification).await
    }
    
    /// Send unlock reminder
    pub async fn send_unlock_notification(
        &self,
        user_pubkey: &str,
        cred_amount: f64,
        yield_amount: f64,
        hours_until: u16,
    ) -> Result<NotificationResult, NotificationError> {
        let notification = PushNotification {
            title: "Position Unlocking Soon ⏰".into(),
            body: format!(
                "Your {:.2} Cred stake unlocks in {} hours with {:.2} Cred yield!",
                cred_amount, hours_until, yield_amount
            ),
            data: Some(NotificationData {
                notification_type: "unlock".into(),
                cred_amount: Some(cred_amount),
                ..Default::default()
            }),
            sound: Some("default".into()),
            priority: NotificationPriority::High,
            badge: None,
        };
        
        self.send(user_pubkey, &notification).await
    }
    
    // ========================================================================
    // INTERNAL METHODS
    // ========================================================================
    
    /// Get cached push token from DynamoDB
    async fn get_cached_token(&self, user_pubkey: &str) -> Result<Option<String>, NotificationError> {
        use aws_sdk_dynamodb::types::AttributeValue;
        
        let result = self.dynamo_client
            .get_item()
            .table_name(&self.config.dynamo_table)
            .key("pk", AttributeValue::S(format!("USER#{}", user_pubkey)))
            .key("sk", AttributeValue::S("PUSH_TOKEN".into()))
            .send()
            .await
            .map_err(|e| NotificationError::DynamoError(e.to_string()))?;
        
        if let Some(item) = result.item {
            // Check TTL
            if let Some(AttributeValue::N(ttl_str)) = item.get("ttl") {
                let ttl: i64 = ttl_str.parse().unwrap_or(0);
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs() as i64;
                
                if ttl < now {
                    // Token expired
                    return Ok(None);
                }
            }
            
            if let Some(AttributeValue::S(token)) = item.get("push_token") {
                return Ok(Some(token.clone()));
            }
        }
        
        Ok(None)
    }
    
    /// Cache push token in DynamoDB
    async fn cache_token(&self, user_pubkey: &str, token: &str) -> Result<(), NotificationError> {
        use aws_sdk_dynamodb::types::AttributeValue;
        
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        let ttl = now + self.config.token_cache_ttl;
        
        self.dynamo_client
            .put_item()
            .table_name(&self.config.dynamo_table)
            .item("pk", AttributeValue::S(format!("USER#{}", user_pubkey)))
            .item("sk", AttributeValue::S("PUSH_TOKEN".into()))
            .item("push_token", AttributeValue::S(token.into()))
            .item("cached_at", AttributeValue::N(now.to_string()))
            .item("ttl", AttributeValue::N(ttl.to_string()))
            .send()
            .await
            .map_err(|e| NotificationError::DynamoError(e.to_string()))?;
        
        info!(user = %user_pubkey, "Push token cached in DynamoDB");
        Ok(())
    }
    
    /// Fetch push token from Supabase profiles table
    async fn fetch_token_from_supabase(&self, user_pubkey: &str) -> Result<Option<String>, NotificationError> {
        // Query profiles table by wallet_address
        let url = format!(
            "{}/rest/v1/profiles?select=push_token&wallet_address=eq.{}",
            self.config.supabase_url,
            user_pubkey
        );
        
        let response = self.http_client
            .get(&url)
            .header("apikey", &self.config.supabase_service_key)
            .header("Authorization", format!("Bearer {}", self.config.supabase_service_key))
            .send()
            .await
            .map_err(|e| NotificationError::SupabaseError(e.to_string()))?;
        
        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            error!(status = %status, body = %body, "Supabase query failed");
            return Err(NotificationError::SupabaseError(format!("HTTP {}: {}", status, body)));
        }
        
        #[derive(Deserialize)]
        struct ProfileRow {
            push_token: Option<String>,
        }
        
        let profiles: Vec<ProfileRow> = response.json().await
            .map_err(|e| NotificationError::SupabaseError(e.to_string()))?;
        
        Ok(profiles.first().and_then(|p| p.push_token.clone()))
    }
    
    /// Send notification via Supabase send-push edge function
    async fn send_via_supabase(
        &self,
        push_token: &str,
        user_pubkey: &str,
        notification: &PushNotification,
    ) -> Result<NotificationResult, NotificationError> {
        let url = format!("{}/functions/v1/send-push", self.config.supabase_url);
        
        let payload = SendPushPayload {
            push_token: push_token.into(),
            user_id: None, // We use pubkey, not Supabase user_id
            title: Some(notification.title.clone()),
            body: Some(notification.body.clone()),
            data: notification.data.clone(),
            sound: notification.sound.clone(),
            priority: match notification.priority {
                NotificationPriority::High => "high",
                NotificationPriority::Normal => "normal",
            }.into(),
            badge: notification.badge,
        };
        
        let response = self.http_client
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.config.supabase_service_key))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await
            .map_err(|e| NotificationError::SupabaseError(e.to_string()))?;
        
        let status = response.status();
        let body: SendPushResponse = response.json().await
            .map_err(|e| NotificationError::SupabaseError(e.to_string()))?;
        
        if body.sent {
            info!(
                user = %user_pubkey,
                ticket_id = ?body.ticket_id,
                "Push notification sent"
            );
            Ok(NotificationResult {
                sent: true,
                ticket_id: body.ticket_id,
                error: None,
            })
        } else {
            warn!(
                user = %user_pubkey,
                error = ?body.error,
                "Push notification failed"
            );
            
            // If token is invalid, clear the cache
            if body.error.as_deref() == Some("DeviceNotRegistered") {
                self.clear_cached_token(user_pubkey).await.ok();
            }
            
            Ok(NotificationResult {
                sent: false,
                ticket_id: None,
                error: body.error,
            })
        }
    }
    
    /// Clear cached push token (e.g., if it's invalid)
    async fn clear_cached_token(&self, user_pubkey: &str) -> Result<(), NotificationError> {
        use aws_sdk_dynamodb::types::AttributeValue;
        
        self.dynamo_client
            .delete_item()
            .table_name(&self.config.dynamo_table)
            .key("pk", AttributeValue::S(format!("USER#{}", user_pubkey)))
            .key("sk", AttributeValue::S("PUSH_TOKEN".into()))
            .send()
            .await
            .map_err(|e| NotificationError::DynamoError(e.to_string()))?;
        
        info!(user = %user_pubkey, "Cleared invalid push token from cache");
        Ok(())
    }
}

// ============================================================================
// DATA TYPES
// ============================================================================

/// Push notification to send
#[derive(Debug, Clone, Serialize)]
pub struct PushNotification {
    pub title: String,
    pub body: String,
    pub data: Option<NotificationData>,
    pub sound: Option<String>,
    pub priority: NotificationPriority,
    pub badge: Option<u32>,
}

#[derive(Debug, Clone, Copy, Serialize)]
pub enum NotificationPriority {
    High,
    Normal,
}

/// Additional data payload
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct NotificationData {
    #[serde(rename = "type")]
    pub notification_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cred_amount: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub position_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transaction_id: Option<String>,
}

/// Result of sending a notification
#[derive(Debug, Clone)]
pub struct NotificationResult {
    pub sent: bool,
    pub ticket_id: Option<String>,
    pub error: Option<String>,
}

/// Payload for Supabase send-push function
#[derive(Debug, Serialize)]
struct SendPushPayload {
    push_token: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    user_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    body: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<NotificationData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sound: Option<String>,
    priority: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    badge: Option<u32>,
}

/// Response from Supabase send-push function
#[derive(Debug, Deserialize)]
struct SendPushResponse {
    sent: bool,
    ticket_id: Option<String>,
    error: Option<String>,
}

// ============================================================================
// ERRORS
// ============================================================================

#[derive(Debug, Clone)]
pub enum NotificationError {
    /// Missing required configuration
    MissingConfig(String),
    /// Initialization failed
    InitError(String),
    /// DynamoDB error
    DynamoError(String),
    /// Supabase error
    SupabaseError(String),
    /// User has no push token
    NoToken,
}

impl std::fmt::Display for NotificationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingConfig(key) => write!(f, "Missing config: {}", key),
            Self::InitError(msg) => write!(f, "Init error: {}", msg),
            Self::DynamoError(msg) => write!(f, "DynamoDB error: {}", msg),
            Self::SupabaseError(msg) => write!(f, "Supabase error: {}", msg),
            Self::NoToken => write!(f, "User has no push token"),
        }
    }
}

impl std::error::Error for NotificationError {}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn notification_data_serializes() {
        let data = NotificationData {
            notification_type: "capture".into(),
            cred_amount: Some(4.95),
            merchant_name: Some("Miami Coffee".into()),
            ..Default::default()
        };
        
        let json = serde_json::to_string(&data).unwrap();
        assert!(json.contains("capture"));
        assert!(json.contains("4.95"));
        assert!(json.contains("Miami Coffee"));
    }
}