Solana Smart Contract
Contract Overview
The contract is designed with modularity in mind, separating concerns across different instruction handlers while maintaining a unified state management system. It supports multiple orchestrators with granular permissions, implements tiered fee structures, and provides robust error handling throughout all operations.
Key Features
Decentralized Cross-Chain Orders
Users can create cross-chain orders by depositing USDC on Solana, which are then fulfilled by orchestrators on destination chains. The system ensures atomic execution and provides strong guarantees for cross-chain transfers.
Multi-Orchestrator Architecture
The contract supports multiple orchestrators with configurable permissions, allowing for distributed order fulfillment while maintaining security through role-based access control.
Dynamic Fee Structure
Implements tiered fee structures based on order amounts, with separate fee categories for operational costs, liquidity provider rewards, protocol revenue, and insurance coverage.
Flexible Liquidity Management
Orchestrators can manage bridge liquidity through controlled deposit and withdrawal mechanisms, with balance thresholds to ensure sufficient reserves for order fulfillment.
Governance Controls
Administrative functions for managing orchestrators, fee structures, and emergency controls including the ability to freeze and thaw contract operations.
Comprehensive Error Handling
Detailed error messages and validation checks throughout all operations to help users understand transaction failures and resolve issues quickly.
Understanding the Workflow
Order Creation Process
Price Validation: The contract validates USDC price stability using Pyth Network feeds
Fee Calculation: Dynamic fees are calculated based on order amount and destination chain
Token Transfer: USDC is transferred from user to the vault
Order Recording: Order details are stored on-chain with unique identifiers
Event Emission: Order creation event is emitted for orchestrator monitoring
Order Fulfillment Process
Order Validation: Orchestrators validate order parameters and check permissions
Liquidity Check: System ensures sufficient vault balance for order fulfillment
Token Transfer: USDC is transferred from vault to orchestrator
Completion Recording: Order status is updated to fulfilled
The orchestrator swaps the USDC for the desired token, and deposits the token to the receiver. This action is handled off-chain in Lit Actions.
Fee Distribution Process
Fee Collection: Fees are automatically collected during order creation
Fee Categorization: Fees are split into base, LP, protocol, and insurance categories
Fee Claiming: Authorized orchestrators can claim fees based on their permissions
Balance Management: Unclaimed fees are tracked separately from operational liquidity
Core Instructions and Their Purposes
Create Order
pub fn create_order(
ctx: Context<CreateOrder>,
amount: u64,
seed: [u8; 32],
order_hash: [u8; 32],
receiver: [u8; 32],
src_chain_id: u32,
dest_chain_id: u32,
token_in: [u8; 32],
fee: u64,
min_amount_out: String,
token_out: [u8; 32],
) -> Result<()>
Creates a new cross-chain order by transferring USDC to the vault and recording order details.
Process:
Validates USDC price stability using Pyth price feeds
Calculates required fees based on amount and destination chain
Transfers USDC from user to vault
Records order details in on-chain storage
Emits order creation event
Fee Structure:
Base Fee: Minimum fee based on destination chain
BPS Fee: Percentage fee based on order amount (tiered)
Insurance Fee: Additional fee for risk coverage
Protocol Fee: Portion of BPS fee for protocol revenue
Fill Order
pub fn fill_order(
ctx: Context<FillOrder>,
amount: u64,
seed: [u8; 32],
order_hash: [u8; 32],
trader: [u8; 32],
src_chain_id: u32,
dest_chain_id: u32,
token_in: [u8; 32],
fee: u64,
min_amount_out: String,
) -> Result<()>
Allows authorized orchestrators to fulfill cross-chain orders by withdrawing USDC from the vault.
Process:
Validates orchestrator permissions
Checks vault balance sufficiency
Transfers USDC to orchestrator
Updates order status to filled
Emits order fulfillment event
Fill Order Token Transfer
pub fn fill_order_token_transfer(
ctx: Context<FillOrderTokenTransfer>,
min_amount_out: u64,
orchestrator_prev_balance: u64,
) -> Result<()>
Handles the final token transfer to the receiver on the destination chain, with special handling for wrapped SOL.
Features:
Validates minimum output amount
Supports both regular SPL tokens and wrapped SOL
Automatically unwraps SOL when transferring native tokens
Revert Order
pub fn revert_order(
ctx: Context<RevertOrder>,
order_hash: [u8; 32]
) -> Result<()>
Allows authorized orchestrators to revert orders and refund users minus the collected fees.
Process:
Validates order status and orchestrator permissions
Calculates refund amount (original amount minus fees)
Transfers refund to original trader
Updates order status to reverted
Claim Fees
pub fn claim_fees(
ctx: Context<ClaimFees>,
amount: u64,
fee_type: FeeType
) -> Result<()>
Allows authorized orchestrators to claim accumulated fees based on their permissions.
Fee Types:
Base: Operational fees for maintaining the bridge
LP: Liquidity provider rewards
Protocol: Protocol revenue
Liquidity Management
rust
pub fn remove_bridge_liquidity(
ctx: Context<RemoveBridgeLiquidity>,
amount: u64
) -> Result<()>
Allows authorized orchestrators to remove bridge liquidity while maintaining minimum balance requirements. This instruction is used for rabalancing vaults (solana and EVM protocols).
State Management
Global State
The GlobalState
account stores system-wide configuration:
pub struct GlobalState {
pub admin: Pubkey,
pub pending_admin: Option<Pubkey>,
pub rebalance_threshold: u16,
pub cross_chain_fee_bps: u16,
pub base_mint: Pubkey,
pub frozen: bool,
pub max_order_amount: u64,
}
Asset State
The Asset
account tracks fee collection and distribution:
pub struct Asset {
pub total_fee_collected: u64,
pub base_fee_collected: u64,
pub lp_fee_collected: u64,
pub protocol_fee_collected: u64,
pub insurance_fee_collected: u64,
pub unclaimed_base_fee: u64,
pub unclaimed_lp_fee: u64,
pub unclaimed_protocol_fee: u64,
pub unclaimed_insurance_fee: u64,
}
Order State
Individual orders are stored in Order
accounts:
pub struct Order {
pub seed: [u8; 32],
pub amount_in: u64,
pub trader: [u8; 32],
pub receiver: [u8; 32],
pub src_chain_id: u32,
pub dest_chain_id: u32,
pub token_in: [u8; 32],
pub status: OrderStatus,
pub fee: u64,
pub min_amount_out: String,
pub token_out: [u8; 32],
pub order_hash: [u8; 32],
}
Orchestrator State
Orchestrator permissions are managed in OrchestratorState
accounts:
pub struct OrchestratorState {
pub orchestrator: Pubkey,
pub authorized: bool,
pub fill_order_permission: bool,
pub revert_order_permission: bool,
pub remove_bridge_liquidity_permission: bool,
pub claim_base_fee_permission: bool,
pub claim_lp_fee_permission: bool,
pub claim_protocol_fee_permission: bool,
}
Security Features
Program Derived Addresses (PDAs)
All critical accounts use PDAs with specific seeds for security:
Global State:
b"genius-global-state-seed"
Vault:
b"genius-vault"
Orders:
order_hash + b"genius-order"
Orchestrators:
orchestrator_pubkey + b"genius-orchestrator-seed"
Permission-Based Access Control
Granular permissions for different operations:
Admin-only functions for critical configuration
Orchestrator permissions for operational tasks
User permissions for order creation and management
Price Validation
Integration with Pyth Network for USDC price validation:
Ensures price stability within acceptable bounds (0.99-1.10 USD)
Prevents orders during extreme market volatility
Uses confidence intervals for robust price checking
Balance Validation
Comprehensive balance checks:
Ensures sufficient vault liquidity for operations
Validates minimum balance requirements
Prevents over-withdrawal scenarios
Input Validation
Extensive input validation throughout:
Array length matching for batch operations
Valid address and amount checks
Status validation for state transitions
Error Handling
The contract implements comprehensive error handling with descriptive messages:
#[error_code]
pub enum GeniusError {
#[msg("Admin address dismatch")]
InvalidAdmin,
#[msg("Orchestrator is not authorized")]
IllegalOrchestrator,
#[msg("Invalid withdraw amount")]
InvalidAmount,
#[msg("Order already exists")]
OrderAlreadyExists,
// ... additional error types
}
Common error scenarios and their handling:
Invalid permissions: Clear error messages for unauthorized operations
Insufficient balance: Detailed balance validation with helpful feedback
Price instability: Specific errors for price-related failures
State validation: Comprehensive state transition validation
Last updated