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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Loop Agent SDK - Vault Action Implementation
//! 
//! Concrete implementation of VaultAction trait for Solana.
//! Uses session keys for scoped permissions - agent never touches user's main keypair.

use crate::action::{
    ActionError, CaptureResult, PermissionScope, ProofType, RiskTolerance,
    SessionKey, StakingPosition, VaultAction, YieldRecommendation, RecommendedAction,
    DISTRIBUTION, YIELD_RATES_BPS,
};
use crate::constants::{
    Network, ProgramIds, TokenMints, MainnetState,
    USER_SHARE_BPS, TREASURY_SHARE_BPS, STAKER_SHARE_BPS,
    STAKING_APY, LAMPORTS_PER_CRED, rpc_endpoint,
};
use crate::ZkProof;
use borsh::{BorshDeserialize, BorshSerialize};
use solana_sdk::{
    instruction::{AccountMeta, Instruction},
    message::Message,
    pubkey::Pubkey,
    signature::{Keypair, Signature},
    signer::Signer,
    transaction::Transaction,
};
use solana_client::rpc_client::RpcClient;
use std::str::FromStr;
use tracing::{info, instrument, warn};

/// Solana-backed vault action implementation
pub struct SolanaVaultAction {
    rpc_client: RpcClient,
    network: Network,
    programs: ProgramIds,
    mints: TokenMints,
    state: MainnetState,
}

impl SolanaVaultAction {
    /// Create new vault action client for specified network
    pub fn new(network: Network) -> Result<Self, ActionError> {
        let rpc_url = std::env::var("SOLANA_RPC_URL")
            .unwrap_or_else(|_| rpc_endpoint(network).to_string());
        Self::with_rpc(&rpc_url, network)
    }
    
    /// Create with custom RPC endpoint
    pub fn with_rpc(rpc_url: &str, network: Network) -> Result<Self, ActionError> {
        let rpc_client = RpcClient::new(rpc_url.to_string());
        
        Ok(Self {
            rpc_client,
            network,
            programs: ProgramIds::for_network(network),
            mints: TokenMints::for_network(network),
            state: MainnetState::get(), // TODO: Add devnet state
        })
    }
    
    /// Create from environment (defaults to mainnet)
    pub fn from_env() -> Result<Self, ActionError> {
        let network = std::env::var("SOLANA_NETWORK")
            .map(|n| if n == "devnet" { Network::Devnet } else { Network::Mainnet })
            .unwrap_or(Network::Mainnet);
        Self::new(network)
    }
    
    /// Get current network
    pub fn network(&self) -> Network {
        self.network
    }
    
    /// Verify session key has required scope
    fn verify_scope(&self, session: &SessionKey, required: PermissionScope) -> Result<(), ActionError> {
        // Check expiration
        let now = chrono::Utc::now().timestamp();
        if session.expires_at < now {
            return Err(ActionError::InvalidSession);
        }
        
        // Check scope
        if !session.scopes.contains(&required) {
            return Err(ActionError::InsufficientScope(required));
        }
        
        Ok(())
    }
    
    /// Derive user's Cred token account
    fn derive_user_cred_account(&self, user: &Pubkey) -> Pubkey {
        spl_associated_token_account::get_associated_token_address(user, &self.mints.cred)
    }
    
    /// Derive staking position PDA
    fn derive_position_pda(&self, user: &Pubkey, position_index: u64) -> (Pubkey, u8) {
        Pubkey::find_program_address(
            &[
                b"position",
                user.as_ref(),
                &position_index.to_le_bytes(),
            ],
            &self.programs.vault,
        )
    }
}

/// Shopping capture instruction data
#[derive(BorshSerialize, BorshDeserialize)]
struct CaptureInstructionData {
    /// Instruction discriminator (from Anchor)
    discriminator: [u8; 8],
    /// Amount in cents (will be converted to Cred)
    amount_cents: u64,
    /// Proof type enum
    proof_type: u8,
    /// Proof data hash (we verify off-chain, store hash on-chain)
    proof_hash: [u8; 32],
    /// Timestamp of purchase
    timestamp: i64,
}

/// Stake instruction data
#[derive(BorshSerialize, BorshDeserialize)]
struct StakeInstructionData {
    discriminator: [u8; 8],
    amount: u64,
    duration_days: u16,
    auto_compound: bool,
}

/// Claim instruction data
#[derive(BorshSerialize, BorshDeserialize)]
struct ClaimInstructionData {
    discriminator: [u8; 8],
    restake: bool,
}

impl VaultAction for SolanaVaultAction {
    /// Capture value from a verified purchase
    /// 
    /// Flow:
    /// 1. Verify session key has Capture scope
    /// 2. Verify the ZK proof (off-chain)
    /// 3. Build capture instruction
    /// 4. Sign with session key (NOT user's main key)
    /// 5. Submit transaction
    /// 6. Contract enforces 80/14/6 distribution
    #[instrument(skip(self, session, proof))]
    fn capture_value(
        &self,
        session: &SessionKey,
        merchant_id: Pubkey,
        proof: ZkProof,
    ) -> Result<CaptureResult, ActionError> {
        // 1. Verify session
        self.verify_scope(session, PermissionScope::Capture)?;
        
        info!(
            user = %session.vault,
            merchant = %merchant_id,
            amount_cents = proof.amount_cents,
            "Executing capture"
        );
        
        // 2. Verify proof (off-chain verification)
        let proof_valid = self.verify_proof(&proof)?;
        if !proof_valid {
            return Err(ActionError::InvalidProof("Proof verification failed".into()));
        }
        
        // 3. Calculate amounts
        // 1 cent = 0.01 Cred = 10,000,000 lamports (since 1 Cred = 1B lamports)
        let total_cred_lamports = proof.amount_cents * 10_000_000;
        let (user_amount, treasury_amount, staker_amount) = calculate_distribution(total_cred_lamports);
        
        // 4. Build instruction
        let proof_hash = self.hash_proof(&proof);
        let instruction_data = CaptureInstructionData {
            discriminator: [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0], // capture discriminator
            amount_cents: proof.amount_cents,
            proof_type: proof.proof_type as u8,
            proof_hash,
            timestamp: proof.timestamp,
        };
        
        let accounts = vec![
            // Shopping program state
            AccountMeta::new(self.state.shopping_state, false),
            // Cred config
            AccountMeta::new_readonly(self.state.cred_config, false),
            // Cred mint (for minting new Cred)
            AccountMeta::new(self.mints.cred, false),
            // User's Cred token account (receives 80%)
            AccountMeta::new(self.derive_user_cred_account(&session.vault), false),
            // Treasury account (receives 14%)
            AccountMeta::new(self.state.treasury, false),
            // Staker pool (receives 6%)
            AccountMeta::new(self.state.staker_pool, false),
            // Merchant (for attribution)
            AccountMeta::new_readonly(merchant_id, false),
            // Session key as signer (NOT user's main key!)
            AccountMeta::new_readonly(session.key, true),
            // User vault (for verification)
            AccountMeta::new_readonly(session.vault, false),
            // System program
            AccountMeta::new_readonly(solana_sdk::system_program::id(), false),
            // Token program
            AccountMeta::new_readonly(spl_token::id(), false),
        ];
        
        let instruction = Instruction {
            program_id: self.programs.shopping,
            accounts,
            data: borsh::to_vec(&instruction_data)
                .map_err(|e| ActionError::TransactionFailed(e.to_string()))?,
        };
        
        // 5. Build and sign transaction with session key
        let recent_blockhash = self.rpc_client.get_latest_blockhash()
            .map_err(|e| ActionError::TransactionFailed(e.to_string()))?;
        
        // Note: In production, session key signing happens via secure key service
        // The session key is a limited-permission key, NOT the user's main wallet
        let message = Message::new(&[instruction], Some(&session.key));
        let mut transaction = Transaction::new_unsigned(message);
        transaction.message.recent_blockhash = recent_blockhash;
        
        // Session key signs (this would be via HSM/KMS in production)
        // For now, we return what the signed transaction would produce
        let signature = self.submit_capture_transaction(transaction, session)?;
        
        info!(
            signature = %signature,
            cred_minted = total_cred_lamports,
            user_share = user_amount,
            "Capture transaction submitted"
        );
        
        Ok(CaptureResult {
            signature,
            cred_minted: total_cred_lamports,
            user_amount,
            treasury_amount,
            staker_amount,
            merchant: merchant_id,
        })
    }
    
    /// Stake Cred for yield
    #[instrument(skip(self, session))]
    fn stake_cred(
        &self,
        session: &SessionKey,
        amount: u64,
        duration_days: u16,
        auto_compound: bool,
    ) -> Result<StakingPosition, ActionError> {
        self.verify_scope(session, PermissionScope::Stake)?;
        
        // Validate duration
        let apy_bps = YIELD_RATES_BPS.iter()
            .find(|(days, _)| *days == duration_days)
            .map(|(_, apy)| *apy)
            .ok_or_else(|| ActionError::InvalidProof(format!(
                "Invalid duration: {}. Valid: 30, 90, 180, 365",
                duration_days
            )))?;
        
        info!(
            user = %session.vault,
            amount = amount,
            duration = duration_days,
            apy_bps = apy_bps,
            "Executing stake"
        );
        
        // Build stake instruction
        let instruction_data = StakeInstructionData {
            discriminator: [0x98, 0x76, 0x54, 0x32, 0x10, 0xab, 0xcd, 0xef], // stake discriminator
            amount,
            duration_days,
            auto_compound,
        };
        
        // Get next position index for user
        let position_index = self.get_next_position_index(&session.vault)?;
        let (position_pda, _bump) = self.derive_position_pda(&session.vault, position_index);
        
        let accounts = vec![
            // Vault program state
            AccountMeta::new(self.state.reserve_vault, false),
            // User's Cred token account (source)
            AccountMeta::new(self.derive_user_cred_account(&session.vault), false),
            // Staking pool (destination)
            AccountMeta::new(self.state.staker_pool, false),
            // Position account (to be created)
            AccountMeta::new(position_pda, false),
            // Session key as signer
            AccountMeta::new_readonly(session.key, true),
            // User vault
            AccountMeta::new_readonly(session.vault, false),
            // System program
            AccountMeta::new_readonly(solana_sdk::system_program::id(), false),
            // Token program
            AccountMeta::new_readonly(spl_token::id(), false),
        ];
        
        let instruction = Instruction {
            program_id: self.programs.vault,
            accounts,
            data: borsh::to_vec(&instruction_data)
                .map_err(|e| ActionError::TransactionFailed(e.to_string()))?,
        };
        
        // Build and submit
        let recent_blockhash = self.rpc_client.get_latest_blockhash()
            .map_err(|e| ActionError::TransactionFailed(e.to_string()))?;
        
        let message = Message::new(&[instruction], Some(&session.key));
        let mut transaction = Transaction::new_unsigned(message);
        transaction.message.recent_blockhash = recent_blockhash;
        
        let _signature = self.submit_stake_transaction(transaction, session)?;
        
        let now = chrono::Utc::now().timestamp();
        let unlock_time = now + (duration_days as i64 * 86400);
        
        Ok(StakingPosition {
            position_id: position_pda,
            amount,
            start_time: now,
            duration_days,
            unlock_time,
            apy_bps,
            auto_compound,
            accrued_yield: 0,
        })
    }
    
    /// Claim yield from positions
    #[instrument(skip(self, session))]
    fn claim_yield(
        &self,
        session: &SessionKey,
        position_id: Option<Pubkey>,
        restake: bool,
    ) -> Result<u64, ActionError> {
        self.verify_scope(session, PermissionScope::Stake)?;
        
        info!(
            user = %session.vault,
            position = ?position_id,
            restake = restake,
            "Executing yield claim"
        );
        
        // Get positions to claim from
        let positions = match position_id {
            Some(pid) => vec![pid],
            None => self.get_user_positions(&session.vault)?,
        };
        
        let mut total_claimed = 0u64;
        
        for position in positions {
            // Fetch position data
            let position_data = self.get_position_data(&position)?;
            
            // Check if unlocked
            let now = chrono::Utc::now().timestamp();
            if position_data.unlock_time > now {
                // Position still locked, skip (or error if specific position requested)
                if position_id.is_some() {
                    return Err(ActionError::PositionLocked {
                        unlock_time: position_data.unlock_time,
                    });
                }
                continue;
            }
            
            // Build claim instruction
            let instruction_data = ClaimInstructionData {
                discriminator: [0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89],
                restake,
            };
            
            let accounts = vec![
                AccountMeta::new(position, false),
                AccountMeta::new(self.state.staker_pool, false),
                AccountMeta::new(self.derive_user_cred_account(&session.vault), false),
                AccountMeta::new_readonly(session.key, true),
                AccountMeta::new_readonly(session.vault, false),
                AccountMeta::new_readonly(spl_token::id(), false),
            ];
            
            let instruction = Instruction {
                program_id: self.programs.vault,
                accounts,
                data: borsh::to_vec(&instruction_data)
                    .map_err(|e| ActionError::TransactionFailed(e.to_string()))?,
            };
            
            let recent_blockhash = self.rpc_client.get_latest_blockhash()
                .map_err(|e| ActionError::TransactionFailed(e.to_string()))?;
            
            let message = Message::new(&[instruction], Some(&session.key));
            let mut transaction = Transaction::new_unsigned(message);
            transaction.message.recent_blockhash = recent_blockhash;
            
            // Submit and add to total
            let claimed = self.submit_claim_transaction(transaction, session, &position)?;
            total_claimed += claimed;
        }
        
        Ok(total_claimed)
    }
    
    /// Get yield optimization recommendation
    fn request_yield_optimization(
        &self,
        session: &SessionKey,
        risk_tolerance: RiskTolerance,
    ) -> Result<YieldRecommendation, ActionError> {
        self.verify_scope(session, PermissionScope::Read)?;
        
        // Fetch user's vault state
        let vault_state = self.get_vault_state(&session.vault)?;
        let positions = self.get_user_positions(&session.vault)?;
        
        // Calculate current effective APY
        let total_staked: u64 = positions.iter()
            .filter_map(|p| self.get_position_data(p).ok())
            .map(|pd| pd.amount)
            .sum();
        
        let weighted_apy: u64 = positions.iter()
            .filter_map(|p| self.get_position_data(p).ok())
            .map(|pd| (pd.amount as u128 * pd.apy_bps as u128 / total_staked.max(1) as u128) as u64)
            .sum();
        
        let current_apy = weighted_apy as u16;
        
        // Determine recommendation based on state and risk tolerance
        let (recommended_action, projected_apy, reasoning) = if vault_state.cred_balance > 0 {
            // Has idle Cred - recommend staking
            let duration = match risk_tolerance {
                RiskTolerance::Conservative => 30,
                RiskTolerance::Balanced => 90,
                RiskTolerance::Aggressive => 365,
            };
            let new_apy = YIELD_RATES_BPS.iter()
                .find(|(d, _)| *d == duration)
                .map(|(_, a)| *a)
                .unwrap_or(1200);
            
            (
                RecommendedAction::Stake {
                    amount: vault_state.cred_balance,
                    duration_days: duration,
                },
                new_apy,
                format!(
                    "You have {:.2} idle Cred. Staking for {} days would earn {}% APY.",
                    vault_state.cred_balance as f64 / 1_000_000_000.0,
                    duration,
                    new_apy as f64 / 100.0
                ),
            )
        } else if positions.len() > 3 {
            // Many small positions - recommend consolidation
            (
                RecommendedAction::Consolidate {
                    from_positions: positions.clone(),
                },
                current_apy + 50, // Slight improvement from reduced overhead
                "You have multiple small positions. Consolidating could reduce gas costs and simplify management.".into(),
            )
        } else {
            // Already optimized
            (
                RecommendedAction::Hold,
                current_apy,
                "Your positions are well-optimized. Hold current strategy.".into(),
            )
        };
        
        Ok(YieldRecommendation {
            current_apy,
            recommended_action,
            projected_apy,
            reasoning,
        })
    }
}

// Helper implementations
impl SolanaVaultAction {
    fn verify_proof(&self, proof: &ZkProof) -> Result<bool, ActionError> {
        // TODO: Implement actual proof verification
        // For Reclaim: verify ZK proof against Reclaim verifier
        // For zkTLS: verify TLS proof
        // For POS: verify webhook signature
        match proof.proof_type {
            ProofType::Reclaim => {
                // Verify Reclaim protocol proof
                // This would call the Reclaim verifier contract or service
                Ok(true)
            }
            ProofType::ZkTls => {
                // Verify zkTLS proof
                Ok(true)
            }
            ProofType::SquarePos | ProofType::StripeConnect => {
                // These come from trusted webhook - already verified upstream
                Ok(true)
            }
            ProofType::Fidel => {
                // Fidel webhooks are signed - verify signature
                Ok(true)
            }
        }
    }
    
    fn hash_proof(&self, proof: &ZkProof) -> [u8; 32] {
        use solana_sdk::hash::hash;
        let data = borsh::to_vec(proof).unwrap_or_default();
        hash(&data).to_bytes()
    }
    
    fn submit_capture_transaction(
        &self,
        _transaction: Transaction,
        _session: &SessionKey,
    ) -> Result<Signature, ActionError> {
        // TODO: Sign with session key and submit
        // In production, this calls a signing service that holds session keys
        // Session keys are limited-permission keys created for agent use
        Ok(Signature::default())
    }
    
    fn submit_stake_transaction(
        &self,
        _transaction: Transaction,
        _session: &SessionKey,
    ) -> Result<Signature, ActionError> {
        Ok(Signature::default())
    }
    
    fn submit_claim_transaction(
        &self,
        _transaction: Transaction,
        _session: &SessionKey,
        _position: &Pubkey,
    ) -> Result<u64, ActionError> {
        // Returns amount claimed
        Ok(0)
    }
    
    fn get_next_position_index(&self, _user: &Pubkey) -> Result<u64, ActionError> {
        // TODO: Query on-chain for user's position count
        Ok(0)
    }
    
    fn get_user_positions(&self, _user: &Pubkey) -> Result<Vec<Pubkey>, ActionError> {
        // TODO: Query positions via getProgramAccounts or indexer
        Ok(vec![])
    }
    
    fn get_position_data(&self, position: &Pubkey) -> Result<PositionData, ActionError> {
        // TODO: Fetch and deserialize position account
        Ok(PositionData {
            amount: 0,
            unlock_time: 0,
            apy_bps: 0,
        })
    }
    
    fn get_vault_state(&self, user: &Pubkey) -> Result<VaultStateData, ActionError> {
        // TODO: Fetch user's token balances
        Ok(VaultStateData {
            cred_balance: 0,
            oxo_balance: 0,
        })
    }
}

/// Position account data
struct PositionData {
    amount: u64,
    unlock_time: i64,
    apy_bps: u16,
}

/// Vault state data
struct VaultStateData {
    cred_balance: u64,
    oxo_balance: u64,
}

/// Calculate 80/14/6 distribution
fn calculate_distribution(total: u64) -> (u64, u64, u64) {
    let user = (total as u128 * USER_SHARE_BPS as u128 / 10000) as u64;
    let treasury = (total as u128 * TREASURY_SHARE_BPS as u128 / 10000) as u64;
    let stakers = total - user - treasury; // Remainder to avoid rounding loss
    (user, treasury, stakers)
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn distribution_is_correct() {
        let total = 1_000_000_000u64; // 1 Cred
        let (user, treasury, stakers) = calculate_distribution(total);
        
        assert_eq!(user, 800_000_000);      // 80%
        assert_eq!(treasury, 140_000_000);  // 14%
        assert_eq!(stakers, 60_000_000);    // 6%
        assert_eq!(user + treasury + stakers, total);
    }
    
    #[test]
    fn distribution_handles_small_amounts() {
        let total = 100u64; // Very small amount
        let (user, treasury, stakers) = calculate_distribution(total);
        
        assert_eq!(user + treasury + stakers, total);
    }
}