miracle-api 0.6.0

Miracle is a pay2e protocol for sovereign individuals living in Mirascape Horizon.
Documentation
use solana_program::pubkey::Pubkey;
use steel::*;

#[repr(u8)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, TryFromPrimitive)]
pub enum MiracleInstruction {
    // User
    BatchClaim = 0, // Claim rewards for multiple epochs
    Claim = 1,      // Claim rewards with merkle proof
    Close = 2,
    Open = 3,
    Reset = 4,

    // Admin
    Initialize = 100,

    // Oracle
    UpdateMetrics = 101,  // Update community metrics
    UpdateOracle = 102,   // Update oracle authority
    UpdateSnapshot = 103, // Update daily payment snapshot
    UpdateTargets = 104,  // Update community targets and activity limits
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Close {}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Open {}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Reset {}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Initialize {
    pub project_wallet: Pubkey, // Project wallet for pre-mint allocation
}

// #[repr(C)]
// #[derive(Clone, Copy, Debug, Pod, Zeroable)]
// pub struct UpdateEvolver {
//     pub new_evolver: Pubkey,
// }

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateOracle {
    pub new_oracle_authority: Pubkey,
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateMetrics {
    pub weekly_active_users: [u8; 4],   // u32
    pub weekly_retention_rate: [u8; 2], // u16
    pub user_weight: [u8; 2],           // u16
    pub activity_weight: [u8; 2],       // u16
    pub retention_weight: [u8; 2],      // u16
    pub weekly_activity_count: [u8; 4], // u32
    pub customer_reward_share: [u8; 2], // u16
    pub merchant_reward_share: [u8; 2], // u16
    pub _padding: [u8; 4],              // 4 bytes padding for 8-byte alignment
}

// ===== PAYMENT-BASED REWARDS SYSTEM INSTRUCTIONS =====

/// Claim instruction data for Dual Merkle Tree system with optional social rewards.
///
/// This instruction allows users to claim rewards based on their activity contributions
/// for a specific epoch using the Dual Merkle Tree verification system. The claim is verified
/// using both a payment merkle proof and a seal merkle proof, with the payment root embedded
/// in the seal proof data for explicit verification. Optionally, users can also claim social
/// marketing rewards for the same epoch if they have verified social media engagement.
///
/// ## Dual Merkle Verification
/// 1. **Payment Proof**: Verifies user's activity within the epoch
/// 2. **Seal Proof**: Verifies the payment merkle root is authentic (from oracle)
/// 3. **Payment Root**: Embedded in seal proof data for explicit verification
/// 4. **Dual Verification**: Both proofs must pass for a valid claim
///
/// ## Social Rewards Support
/// - **Payment-First**: Social rewards require payment activity verification
/// - **Oracle Verification**: Social posts must be verified by oracle signature
/// - **Optional**: Users can choose payment-only or payment+social claims
/// - **Unified**: Single instruction supports both reward types
///
/// ## Data Structure
/// The instruction uses a hybrid approach with fixed-size fields followed by variable-length data:
///
/// ```rust
/// // Fixed-size struct (23 bytes)
/// struct Claim {
///     epoch: [u8; 8],              // 8 bytes - Epoch number for the claim
///     payment_proof_length: u8,    // 1 byte - Length of payment merkle path
///     seal_proof_length: u8,       // 1 byte - Length of seal merkle path
///     participant_type: u8,        // 1 byte - 0 for customer, 1 for merchant
///     has_social: u8,              // 1 byte - 0=payment only, 1=has social data
///     _padding: [u8; 4],           // 4 bytes - Padding for alignment
/// }
///
/// // Variable-size additional data (appended after fixed struct)
/// // participant_data: DailyParticipantData  // Variable size - Actual participant data for verification
/// // payment_proof: Vec<[u8; 32]>  // payment_proof_length * 32 bytes
/// // payment_indices: Vec<u8>      // payment_proof_length * 1 byte
/// // seal_proof: Vec<[u8; 32]>     // seal_proof_length * 32 bytes
/// // seal_indices: Vec<u8>         // seal_proof_length * 1 byte
/// // payment_root: [u8; 32]        // Payment root (embedded in seal proof data)
/// // epoch_data: EpochClaimData    // Epoch-specific data for accurate historical reward calculation
/// // social_data: SocialClaimData  // Optional: only if has_social = 1
/// ```
///
/// ## Security Features
/// - **Payment Proof**: Ensures claim data integrity within an epoch
/// - **Seal Proof**: Ensures payment merkle root is authentic (from oracle)
/// - **Payment Root**: Explicitly provided for verification
/// - **Dual Verification**: Both proofs must pass for a valid claim
/// - **Oracle Verification**: Social posts verified by authorized oracle
/// - **Unlimited History**: No storage limits for historical claims
///
/// ## On-Chain Reward Calculation
/// The reward amount is calculated on-chain using the transparent formula:
/// payment_reward = (activity_count * customer_reward_pool) / total_customer_activity
/// social_reward = base_reward_per_post * (1 + engagement_score / 1000)
///
/// Where:
/// - `activity_count` is extracted from the payment merkle proof
/// - `customer_reward_pool` and `total_customer_activity` are read from the Snapshot
/// - `base_reward_per_post` and engagement data come from social verification
///
/// ## Historical Claims Support
/// For historical epoch claims, the instruction includes epoch-specific data:
/// - **Current Epoch**: Uses on-chain snapshot data for reward calculation
/// - **Historical Epochs**: Uses epoch-specific data embedded in the instruction
/// - **No On-Chain Storage**: Historical data comes with the claim instruction
/// - **Accurate Rewards**: Users get correct rewards for historical activity
///
/// This enables the Dual Merkle Tree's promise of unlimited claim history without
/// requiring expensive on-chain storage of historical snapshots.
///
/// ## Off-Chain Development
/// When building claim instructions off-chain:
/// 1. Set `payment_proof_length` and `seal_proof_length` to actual path lengths
/// 2. Set `has_social` to 1 if social data is included, 0 otherwise
/// 3. Append payment proof data after the fixed struct
/// 4. Append payment indices data (1 = right, 0 = left)
/// 5. Append seal proof data
/// 6. Append seal indices data (1 = right, 0 = left)
/// 7. Append payment root data (32 bytes)
/// 8. Append epoch-specific data (EpochClaimData) for accurate historical calculations
/// 9. If has_social = 1, append SocialClaimData
/// 10. Verify total instruction size doesn't exceed Solana limits
///
/// See `DUAL_MERKLE_TREE_DESIGN.md` for detailed implementation examples.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Claim {
    pub epoch: [u8; 8],           // Epoch number for the claim
    pub payment_proof_length: u8, // Length of payment merkle path
    pub seal_proof_length: u8,    // Length of seal merkle path
    pub participant_type: u8,     // 0 for customer, 1 for merchant
    pub has_social: u8,           // 0=payment only, 1=has social data
    pub _padding: [u8; 4],        // Padding for alignment

                                  // Note: payment_proof, payment_indices, seal_proof, seal_indices, social_data will be passed as additional data
}

/// BatchClaim instruction data for Dual Merkle Tree system.
///
/// This instruction allows users to claim rewards for multiple epochs in a single transaction
/// using the Dual Merkle Tree verification system. Each epoch requires both payment and seal
/// merkle proofs for complete security verification.
///
/// ## Dual Merkle Verification for Batch Claims
/// For each epoch in the batch:
/// 1. **Payment Proof**: Verifies user's activity within the epoch
/// 2. **Seal Proof**: Verifies the payment merkle root is authentic (from oracle)
/// 3. **Dual Verification**: Both proofs must pass for each epoch
///
/// ## Data Structure
/// The instruction uses a hybrid approach supporting different claim types:
///
/// ```rust
/// // Fixed-size struct (25 bytes)
/// struct BatchClaim {
///     start_epoch: [u8; 8],     // 8 bytes - Start epoch for range claims
///     end_epoch: [u8; 8],       // 8 bytes - End epoch for range claims
///     participant_type: u8,     // 1 byte - 0 for customer, 1 for merchant
///     claim_type: u8,           // 1 byte - 0=range, 1=vector, 2=date_range
///     epoch_count: u8,          // 1 byte - Number of epochs for vector claims
///     max_batch_size: u8,       // 1 byte - Maximum epochs to process
///     _padding: [u8; 4],        // 4 bytes - Padding for alignment
/// }
///
/// // Variable-size additional data (appended after fixed struct)
/// // For vector claims: Vec<u64> of epochs
/// // For each epoch: payment_proof + payment_indices + payment_root + seal_proof + seal_indices + epoch_data
/// // Social flags array: 1 byte per epoch (0=no social, 1=has social)
/// // Social data array: SocialClaimData for epochs with social claims
/// ```
///
/// ## Claim Types
/// - **Range Claims (0)**: Claim all epochs from start_epoch to end_epoch (inclusive)
/// - **Vector Claims (1)**: Claim specific epochs listed in variable data
/// - **Date Range Claims (2)**: Convert date range to epoch range automatically
///
/// ## Benefits
/// - **Gas Efficiency**: Single transaction for multiple epochs
/// - **User Experience**: Natural date-based interface
/// - **Flexibility**: Support for both contiguous and non-contiguous epochs
/// - **Security**: Each epoch validated independently with dual merkle proofs
/// - **Unified**: Supports both payment and social rewards in single batch
/// - **Payment-First**: All social claims require payment activity
/// - **Unlimited History**: No storage limits for historical claims
///
/// ## Historical Claims Support
/// For historical epoch claims, each epoch includes epoch-specific data:
/// - **Current Epochs**: Use on-chain snapshot data for reward calculation
/// - **Historical Epochs**: Use epoch-specific data embedded in the instruction
/// - **No On-Chain Storage**: Historical data comes with the batch claim instruction
/// - **Accurate Rewards**: Users get correct rewards for historical activity across all epochs
///
/// This enables the Dual Merkle Tree's promise of unlimited claim history without
/// requiring expensive on-chain storage of historical snapshots.
///
/// ## Error Handling
/// - **No Activity**: Skip epochs with no user activity
/// - **Invalid Proofs**: Fail on security-critical errors (payment or seal)
/// - **Batch Limits**: Respect max_batch_size to prevent gas limit issues
/// - **Pool Limits**: Validate against both payment and social pool limits
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct BatchClaim {
    /// Start epoch for range claims (inclusive)
    pub start_epoch: [u8; 8],

    /// End epoch for range claims (inclusive)
    pub end_epoch: [u8; 8],

    /// Participant type: 0 for customer, 1 for merchant
    pub participant_type: u8,

    /// Claim type: 0=range, 1=vector, 2=date_range
    pub claim_type: u8,

    /// Number of epochs for vector claims
    pub epoch_count: u8,

    /// Maximum epochs to process (gas limit protection)
    pub max_batch_size: u8,

    /// Padding to ensure proper alignment (4 bytes)
    pub _padding: [u8; 4],
}

#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateSnapshot {
    pub epoch: [u8; 8], // Epoch number

    /// The seal merkle root of all historical payment merkle roots
    /// This is the root of the incremental seal merkle tree containing all payment roots
    pub seal_merkle_root: [u8; 32],

    /// The payment merkle root for the current epoch
    /// Used to compute epoch hash for tamper detection in the Epoch Hash Chain security solution
    pub payment_merkle_root: [u8; 32],

    /// Epoch hash for tamper detection in the Epoch Hash Chain security solution
    /// This field is computed as Hash(previous_epoch_hash + current_payment_merkle_root)
    pub epoch_hash: [u8; 32],

    pub customer_reward_pool: [u8; 8], // Customer reward pool for this epoch
    pub merchant_reward_pool: [u8; 8], // Merchant reward pool for this epoch
    pub customer_participants: [u8; 4], // Total customer participants
    pub merchant_participants: [u8; 4], // Total merchant participants
    pub total_customer_payments: [u8; 4], // Total customer payment count (activities)
    pub total_merchant_payments: [u8; 4], // Total merchant payment count (activities)
}

/// Update community targets, activity limits, and claim rewards threshold.
/// This instruction allows the oracle to update community health targets, activity limits,
/// and claim rewards threshold based on real-world community performance and operational needs.
///
/// ## Data Structure
/// Fixed-size struct (28 bytes) containing all configurable parameters:
///
/// ```rust
/// struct UpdateTargets {
///     // Claim Rewards Threshold
///     claim_rewards_threshold: [u8; 8],           // u64
///
///     // Community Health Targets
///     target_weekly_users: [u8; 4],           // u32
///     target_weekly_activity: [u8; 4],        // u32  
///     target_retention_rate: [u8; 2],         // u16
///
///     // Activity Limits
///     max_customer_activity_per_epoch: [u8; 4],  // u32
///     max_merchant_activity_per_epoch: [u8; 4],  // u32
///     activity_cap_enabled: u8,                   // u8
///     claim_cap_enabled: u8,                   // u8
///
///     // Padding
///     _padding: [u8; 4],                          // 4 bytes padding
/// }
/// ```
///
/// ## Parameters
/// - `target_weekly_users`: Target weekly active users (default: 10,000)
/// - `target_weekly_activity`: Target weekly activity count (default: 50,000)
/// - `target_retention_rate`: Target retention rate in basis points (default: 7,000 = 70%)
/// - `max_customer_activity_per_epoch`: Max customer activities per epoch (default: 5)
/// - `max_merchant_activity_per_epoch`: Max merchant activities per epoch (default: 50)
/// - `activity_cap_enabled`: Whether activity capping is enabled (default: 1 = enabled)
/// - `claim_cap_enabled`: Whether claim capping is enabled (default: 1 = enabled)
/// - `claim_rewards_threshold`: Risk threshold for rewards claim requests (default: BASE_DAILY_REWARDS)
///
/// ## Authority
/// - **Oracle Authority**: Only the oracle can update these parameters
/// - **Rationale**: Oracle has the data to make informed decisions about community health
///
/// ## Benefits
/// - **Operational Flexibility**: Adjust parameters based on real community performance
/// - **Anti-Gaming**: Update activity limits to prevent new gaming strategies
/// - **Community Adaptation**: Adjust targets as community grows and evolves
/// - **Economic Balance**: Fine-tune parameters for sustainable tokenomics
/// - **Risk Management**: Adjust claim rewards threshold based on market conditions
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct UpdateTargets {
    /// Risk threshold for rewards claim requests.
    pub claim_rewards_threshold: [u8; 8], // u64

    /// Target weekly active users for sustainable rewards.
    pub target_weekly_users: [u8; 4], // u32

    /// Target weekly activity count for sustainable rewards.
    pub target_weekly_activity: [u8; 4], // u32

    /// Maximum customer activity count per epoch (prevents payment splitting).
    pub max_customer_activity_per_epoch: [u8; 4], // u32

    /// Maximum merchant activity count per epoch (prevents payment splitting).
    pub max_merchant_activity_per_epoch: [u8; 4], // u32

    /// Target weekly retention rate in basis points (0-10000).
    pub target_retention_rate: [u8; 2], // u16

    /// Whether activity capping is enabled (1=enabled, 0=disabled).
    pub activity_cap_enabled: u8, // u8

    /// Whether claim capping is enabled (1=enabled, 0=disabled).
    pub claim_cap_enabled: u8, // u8

    /// Padding to ensure proper alignment (4 bytes).
    pub _padding: [u8; 4],
}

/*
/// ## Off-Chain Development
/// When building batch claim instructions off-chain:
/// 1. Set claim parameters (participant_type, claim_type, start/end epochs, etc.)
/// 2. For each epoch in the batch:
///    - Generate payment proof and indices
///    - Generate seal proof and indices
///    - Include epoch-specific data (EpochClaimData) for accurate historical calculations
/// 3. Append social flags array (1 byte per epoch)
/// 4. Append social data array for epochs with social claims
/// 5. Verify total instruction size doesn't exceed Solana limits
///
/// ## Epoch Data Requirements
/// - **Current Epoch Claims**: Can omit epoch data (uses on-chain snapshot)
/// - **Historical Epoch Claims**: Must include epoch-specific data for each epoch
/// - **Mixed Batches**: Include epoch data only for historical epochs
/// - **Validation**: Ensure epoch data matches the specific epoch being claimed
*/
instruction!(MiracleInstruction, BatchClaim);
instruction!(MiracleInstruction, Claim);
instruction!(MiracleInstruction, Close);
instruction!(MiracleInstruction, Open);
instruction!(MiracleInstruction, Reset);

instruction!(MiracleInstruction, Initialize);

instruction!(MiracleInstruction, UpdateMetrics);
instruction!(MiracleInstruction, UpdateOracle);
instruction!(MiracleInstruction, UpdateSnapshot);
instruction!(MiracleInstruction, UpdateTargets);