A comprehensive DeFi yield optimization platform built on Stellar's Soroban smart contracts, featuring auto-compounding vaults, intelligent rebalancing, and advanced risk management tools.
- Auto-compounding Yield Vaults: Automatically harvest and reinvest rewards for maximum yield
- Smart Rebalancing Engine: Move liquidity between pools based on APY and impermanent loss metrics
- Multi-token Reward Distribution: Support for XLM, USDC, and native reward tokens
- Plug-in Strategy System: Customizable yield farming strategies with risk levels
- Emergency Controls: Pause functionality and admin controls for security
- Impermanent Loss Calculation: Real-time IL tracking and historical analysis
- Risk Assessment: Comprehensive risk scoring and scenario analysis
- Performance Analytics: Detailed metrics, Sharpe ratios, and drawdown analysis
- Automated Bots: Harvest and rebalancing bots with configurable parameters
- React UI Components: Modern interface for vault management and monitoring
stellar-liquidity-yield-engine/
├── src/ # Soroban Contracts (Rust)
│ ├── lib.rs # Main contract exports
│ ├── yield_vault.rs # Auto-compounding vault logic
│ ├── rebalance_engine.rs # Smart liquidity rebalancing
│ ├── reward_distributor.rs # Multi-token reward distribution
│ └── strategy_registry.rs # Strategy management system
├── sdk/src/ # TypeScript SDK
│ ├── vaultClient.ts # Vault interaction client
│ ├── rebalancer.ts # Rebalancing execution client
│ ├── yieldCalculator.ts # Risk and yield calculations
│ ├── types.ts # TypeScript interfaces
│ └── index.ts # SDK exports
├── ui/src/components/ # React Components
│ ├── YieldVaultCard.tsx # Vault display and controls
│ ├── RebalancePanel.tsx # Rebalancing visualization
│ ├── ImpermanentLossChart.tsx # IL analysis charts
│ ├── StrategySelector.tsx # Strategy selection interface
│ └── hooks/useYieldVault.ts # React hooks for vault data
└── examples/ # Example Scripts
├── auto-compound-setup.ts # Auto-compounding configuration
├── cross-pool-rebalance.ts # Cross-pool rebalancing
├── yield-harvest-bot.ts # Automated harvesting bot
└── risk-analysis.ts # Risk analysis tools
- Rust 1.70+ with Soroban CLI
- Node.js 18+
- TypeScript 5+
- Stellar SDK
# Install Rust and Soroban
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
cargo install soroban-cli
# Build contracts (run from the repository root — Cargo.toml lives there)
cargo build --target wasm32-unknown-unknown --releasecd sdk/
npm install
npm run buildcd ui/
npm install
npm run devSee the full Contract Deployment section below for the actual build/deploy/initialize commands and current build caveats.
import { VaultClient, TESTNET_CONFIG } from 'stellar-liquidity-yield-engine-sdk';
const vaultClient = new VaultClient('VAULT_ADDRESS', TESTNET_CONFIG);
// Initialize vault
await vaultClient.initialize(
adminKeyPair,
'USDC-XLM Vault',
USDC_ADDRESS,
XLM_ADDRESS,
POOL_ADDRESS,
STRATEGY_ID,
100, // 1% fee rate
50, // 0.5% harvest fee
100 // 1% withdrawal fee
);// Deposit tokens
const result = await vaultClient.deposit(userKeyPair, {
amountA: BigInt(1000000), // 1 USDC
amountB: BigInt(5000000), // 5 XLM
minShares: BigInt(950000)
});// Configure auto-compounding
const autoCompoundManager = new AutoCompoundManager(vaultAddress, TESTNET_CONFIG);
// Start monitoring (every hour)
autoCompoundManager.startMonitoring(userKeyPair, 60);- Risk Level: Low (1/3)
- Target APY: 8-12%
- Max IL Risk: 10%
- Suitable For: Risk-averse users, stable assets
- Risk Level: Medium (2/3)
- Target APY: 12-20%
- Max IL Risk: 20%
- Suitable For: Balanced risk-return profile
- Risk Level: High (3/3)
- Target APY: 20-35%
- Max IL Risk: 30%
- Suitable For: High risk tolerance, volatile assets
The rebalancing engine automatically optimizes liquidity allocation:
- Multi-pool Analysis: Monitor performance across all vault pools
- APY Thresholds: Rebalance when APY gaps exceed thresholds
- IL Risk Assessment: Consider impermanent loss in decisions
- Gas Optimization: Batch transactions for cost efficiency
- Slippage Protection: Maximum slippage tolerance settings
const rebalancerClient = new RebalancerClient(TESTNET_CONFIG);
// Create rebalancing strategy
const strategyId = await rebalancerClient.createStrategy(
adminKeyPair,
'Dynamic Yield Optimization',
2, // Balanced risk
1000, // 10% minimum APY
1500, // 15% max IL risk
86400, // Rebalance every 24 hours
allocations
);Multi-token reward system supporting:
- XLM: Native Stellar token
- USDC: Stablecoin rewards
- Native Tokens: Project-specific reward tokens
- Merkle Distribution: Efficient off-chain calculation
- Claim Deadlines: Time-limited reward claims
- Fee Structure: Performance and management fees
const rewardClient = new RewardDistributorClient(TESTNET_CONFIG);
// Claim rewards
const claimed = await rewardClient.claimRewards(
userKeyPair,
userAddress,
vaultAddress,
rewards,
merkleProof
);import { YieldCalculator } from 'stellar-liquidity-yield-engine-sdk';
// Calculate current IL
const il = YieldCalculator.calculateImpermanentLoss(
1.0, // Initial price ratio
1.5, // Current price ratio
30 // Days elapsed
);
console.log(`Current IL: ${il.ilPercent.toFixed(2)}%`);- Value at Risk (VaR): 95% confidence level
- Conditional VaR (CVaR): Expected loss beyond VaR
- Maximum Drawdown: Historical peak-to-trough loss
- Sharpe Ratio: Risk-adjusted return measure
- Volatility Analysis: Asset and portfolio volatility
// Run Monte Carlo simulation
const simulation = YieldCalculator.simulateImpermanentLoss(
1.0, // Initial price ratio
0.25, // 25% volatility
30, // 30 days
1000 // 1000 simulations
);
console.log(`Average IL: ${simulation.averageIl.toFixed(2)}%`);
console.log(`Worst case IL: ${simulation.worstCaseIl.toFixed(2)}%`);Automated reward harvesting with intelligent timing:
import { YieldHarvestBot } from './examples/yield-harvest-bot';
const bot = new YieldHarvestBot(BOT_CONFIG, BOT_KEYPAIR, TESTNET_CONFIG);
// Start bot
await bot.start();
// Force harvest specific vault
await bot.forceHarvest('VAULT_ADDRESS');- Check Interval: Monitoring frequency (15-60 minutes)
- Reward Thresholds: Minimum rewards for harvesting
- Gas Price Limits: Maximum acceptable gas costs
- Cooldown Periods: Minimum time between harvests
- Performance Tracking: Detailed harvest statistics
Complete vault interface with deposit/withdraw functionality:
import { YieldVaultCard } from '@/components/YieldVaultCard';
<YieldVaultCard
vaultAddress="VAULT_ADDRESS"
userAddress="USER_ADDRESS"
network="testnet"
/>Visual rebalancing interface with strategy management:
import { RebalancePanel } from '@/components/RebalancePanel';
<RebalancePanel network="testnet" />Interactive IL analysis and visualization:
import { ImpermanentLossChart } from '@/components/ImpermanentLossChart';
<ImpermanentLossChart
initialPriceRatio={1.0}
currentPriceRatio={1.5}
timeElapsed={30}
/>- Emergency Pause: Admin can pause all operations
- Access Control: Role-based permissions
- Input Validation: Comprehensive parameter checks
- Reentrancy Protection: Prevent recursive calls
- Overflow Protection: Safe arithmetic operations
- Slippage Protection: Maximum acceptable price impact
- Position Limits: Maximum exposure per vault
- Time Locks: Delays for sensitive operations
- Multi-signature: Enhanced admin security
- Audit Trail: Complete operation logging
- APY: Annual percentage yield after fees
- TVL: Total value locked across all vaults
- Harvest Efficiency: Rewards harvested per gas spent
- IL Impact: Average impermanent loss experienced
- User Retention: User engagement and retention rates
Real-time monitoring of:
- Vault performance and rankings
- Strategy effectiveness
- Risk metrics and alerts
- Gas usage and optimization
- User activity patterns
- RPC:
https://soroban-testnet.stellar.org - Horizon:
https://horizon-testnet.stellar.org - Network Passphrase:
Test SDF Network ; September 2015
- RPC:
https://soroban.stellar.org - Horizon:
https://horizon.stellar.org - Network Passphrase:
Public Global Stellar Network ; September 2015
Copy .env.example to .env and fill in real values:
cp .env.example .env# Network configuration
STELLAR_NETWORK=testnet
SOROBAN_RPC_URL=https://soroban-testnet.stellar.org
HORIZON_URL=https://horizon-testnet.stellar.org
# Contract addresses
YIELD_ENGINE_ADDRESS=...
REWARD_DISTRIBUTOR_ADDRESS=...
REBALANCE_ENGINE_ADDRESS=...
STRATEGY_REGISTRY_ADDRESS=...
# Bot configuration
BOT_PRIVATE_KEY=...
HARVEST_THRESHOLD=1000
CHECK_INTERVAL=300000.env.example also lists governance-related addresses
(GOVERNANCE_CONTRACT, VOTING_ESCROW_CONTRACT, etc.) read by
sdk/src/governance.ts. There is no working contract to deploy for those
yet — see GOVERNANCE_STATUS.md.
There is no scripts/ directory in this repo — deploy with the soroban
CLI directly. All commands below run from the repository root (that's
where Cargo.toml lives; the crate is not under src/).
Known blocker:
src/lib.rsunconditionally includessrc/governance.rs(mod governance;), which does not compile — see GOVERNANCE_STATUS.md. Until that's fixed,cargo buildfor this crate fails and none of the steps below will produce a wasm file.
# 0. One-time setup: install the wasm target and create/fund a testnet identity
rustup target add wasm32-unknown-unknown
soroban keys generate deployer --network testnet
soroban keys fund deployer --network testnet
# 1. Build the contract wasm
cargo build --target wasm32-unknown-unknown --release
# -> target/wasm32-unknown-unknown/release/stellar_liquidity_yield_engine.wasm
# 2. (Optional) Optimize the wasm binary size
soroban contract optimize \
--wasm target/wasm32-unknown-unknown/release/stellar_liquidity_yield_engine.wasm
# 3. Deploy — prints the deployed CONTRACT_ID
soroban contract deploy \
--wasm target/wasm32-unknown-unknown/release/stellar_liquidity_yield_engine.wasm \
--source deployer \
--network testnet
# 4. Initialize the deployed contract (use the CONTRACT_ID from step 3)
soroban contract invoke \
--id CONTRACT_ID \
--source deployer \
--network testnet \
-- \
initialize \
--admin $(soroban keys address deployer) \
--strategy_registry STRATEGY_REGISTRY_ADDRESS \
--reward_distributor REWARD_DISTRIBUTOR_ADDRESS
# 5. Verify it deployed correctly by reading back a value
soroban contract invoke \
--id CONTRACT_ID \
--source deployer \
--network testnet \
-- \
get_adminSave the resulting CONTRACT_ID into your .env file as
YIELD_ENGINE_ADDRESS (and repeat steps 3–4 for any other addresses you
need, such as STRATEGY_REGISTRY_ADDRESS and REWARD_DISTRIBUTOR_ADDRESS,
before running step 4 above).
# Run contract tests (run from the repository root)
cargo test
# Run SDK tests
cd sdk/
npm test
# Run component tests
cd ui/
npm test# Run full integration suite
npm run test:integration
# Run performance benchmarks
npm run test:performanceclass VaultClient {
// Core operations
deposit(keypair: any, params: DepositParams): Promise<TransactionResult>
withdraw(keypair: any, params: WithdrawParams): Promise<TransactionResult>
harvest(keypair: any): Promise<TransactionResult>
// Queries
getVaultInfo(): Promise<VaultInfo>
getMetrics(): Promise<VaultMetrics>
getUserPosition(address: Address): Promise<UserPosition>
getAPY(): Promise<number>
getTVL(): Promise<bigint>
// Admin functions
pause(keypair: any): Promise<TransactionResult>
unpause(keypair: any): Promise<TransactionResult>
}class RebalancerClient {
// Strategy management
createStrategy(keypair: any, ...params): Promise<number>
updateStrategy(keypair: any, ...params): Promise<void>
getStrategies(): Promise<RebalanceStrategy[]>
// Rebalancing
analyzeRebalanceOpportunities(strategyId: number): Promise<RebalanceProposal[]>
executeRebalance(keypair: any, proposal: RebalanceProposal): Promise<boolean>
// Analytics
getHistory(limit: number): Promise<RebalanceHistory[]>
calculateImpermanentLoss(poolId: Address, ...): Promise<number>
}class YieldCalculator {
// Impermanent loss
static calculateImpermanentLoss(initialRatio: number, currentRatio: number, timeElapsed: number): ImpermanentLossData
static simulateImpermanentLoss(initialRatio: number, volatility: number, timePeriod: number, simulations: number): SimulationResult
// Yield calculations
static projectApy(historicalApy: number[], marketConditions: MarketConditions, timeHorizon: number): ApyProjection
static estimateFeeRevenue(tvl: bigint, ...): FeeRevenue
// Risk metrics
static calculateSharpeRatio(returns: number[], riskFreeRate: number): number
static calculateMaxDrawdown(values: number[]): MaxDrawdownData
}We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
- Rust:
cargo fmtandcargo clippy - TypeScript: ESLint and Prettier
- React: Component testing with Jest
- Documentation: Updated README and API docs
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: GitHub Repository
- Discord: Stellar Yield Community
- Issues: GitHub Issues
- Email: support@stellar-yield.com
- Core vault functionality
- Auto-compounding system
- Basic rebalancing engine
- React UI components
- Advanced strategy system
- Cross-chain support
- Mobile app
- Governance features (in-progress scaffolding exists in
src/governance.rsbut does not compile or work yet — see GOVERNANCE_STATUS.md)
- DeFi integrations
- Advanced analytics
- Insurance products
- Layer 2 optimization
- AI-powered optimization
- Social trading
- Enterprise features
- Regulatory compliance
- Deposit: ~50,000 gas
- Withdraw: ~60,000 gas
- Harvest: ~45,000 gas
- Rebalance: ~80,000 gas
- Vault Query: <100ms
- Strategy Analysis: <500ms
- Risk Calculation: <200ms
- Batch Operations: <1s
- Initial Load: <2s
- Transaction Response: <500ms
- Chart Rendering: <300ms
- Real-time Updates: <100ms
This project has not yet undergone a third-party security audit. Do not use in production or with real funds until an audit has been completed. This section will be updated with audit firm names, dates, and report links once an audit is performed.
There is no bug bounty program at this time. If you discover a security issue, please open a GitHub issue or contact the maintainers directly rather than disclosing it publicly.
Built with ❤️ for the Stellar ecosystem