Skip to main content
The Saros Main SDK provides a comprehensive foundation for building complete DeFi ecosystems, integrating traditional AMM functionality with advanced features like yield farming, governance, and staking into a cohesive protocol architecture.

Complete DeFi Stack

Core Components Integration

The Main SDK orchestrates multiple DeFi primitives into a unified system, enabling developers to build full-featured protocols rather than isolated components. Traditional AMM Foundation:
  • Constant product market making (x * y = k)
  • Uniform liquidity distribution across price ranges
  • Proven mechanics with predictable behavior
  • Battle-tested mathematical foundations
Yield Generation Layer:
  • Liquidity mining programs with configurable rewards
  • Multi-token farming strategies
  • Vesting schedules and lock-up mechanisms
  • Auto-compounding reward distribution
Governance Framework:
  • Token-weighted voting mechanisms
  • Proposal creation and execution systems
  • Treasury management and fund allocation
  • Community-driven protocol upgrades
Staking Infrastructure:
  • Single and multi-asset staking pools
  • Slashing protection mechanisms
  • Validator delegation and rewards
  • Liquid staking token support

Architectural Design Principles

Modular Composition

The Main SDK follows a modular architecture where each component can function independently while integrating seamlessly with others.
// Example: Modular component integration
import { 
  AmmModule,
  FarmingModule, 
  GovernanceModule,
  StakingModule 
} from '@saros/main-sdk';

class DeFiProtocol {
  constructor(config) {
    // Each module operates independently
    this.amm = new AmmModule(config.amm);
    this.farming = new FarmingModule(config.farming);
    this.governance = new GovernanceModule(config.governance);
    this.staking = new StakingModule(config.staking);
  }
  
  // Modules can be composed for complex operations
  async createIncentivizedPool(tokenA, tokenB, rewardToken) {
    // 1. Create AMM pool
    const pool = await this.amm.createPool(tokenA, tokenB);
    
    // 2. Create farming program for LP tokens
    const farm = await this.farming.createFarm({
      lpToken: pool.lpToken,
      rewardToken,
      rewardsPerBlock: '1000000'
    });
    
    // 3. Create governance proposal for farm activation
    const proposal = await this.governance.createProposal({
      title: 'Activate farming for new pool',
      actions: [farm.activate()]
    });
    
    return { pool, farm, proposal };
  }
}

Cross-Component Synergies

The Main SDK is designed to enable powerful synergies between different DeFi components: AMM + Farming Integration:
  • LP tokens automatically eligible for farming rewards
  • Dynamic APR calculation including trading fees and farming rewards
  • Auto-compounding mechanisms that reinvest rewards into LP positions
Governance + Protocol Management:
  • Community-controlled fee adjustments
  • Farming reward rate modifications through voting
  • Treasury-funded grants and development initiatives
Staking + Utility Integration:
  • Staked tokens provide governance voting power
  • Fee discounts for stakers
  • Priority access to new farming programs

Economic Model Architecture

Multi-Layer Value Accrual

The Main SDK implements a sophisticated value accrual mechanism across multiple layers: Layer 1: Trading Fees
// Traditional AMM trading fees (0.3% typical)
class TradingFees {
  constructor(feeRate = 0.003) {
    this.feeRate = feeRate;
    this.lpShare = 0.8;      // 80% to LPs
    this.protocolShare = 0.2; // 20% to protocol
  }
  
  calculateFees(tradeAmount) {
    const totalFee = tradeAmount * this.feeRate;
    return {
      lpFees: totalFee * this.lpShare,
      protocolFees: totalFee * this.protocolShare
    };
  }
}
Layer 2: Farming Rewards
// Additional yield through token incentives
class FarmingRewards {
  calculateAPY(poolTVL, rewardsPerYear, tokenPrice) {
    const yearlyRewardValue = rewardsPerYear * tokenPrice;
    const tradingFeeAPY = this.calculateTradingFeeAPY(poolTVL);
    const farmingAPY = yearlyRewardValue / poolTVL;
    
    return {
      tradingFeeAPY,
      farmingAPY,
      totalAPY: tradingFeeAPY + farmingAPY
    };
  }
}
Layer 3: Governance Participation
// Value from protocol decision-making
class GovernanceValue {
  constructor() {
    this.votingRewards = 0.001; // 0.1% of treasury per proposal
    this.proposalBond = 1000;   // Required tokens to create proposal
  }
  
  // Governance participants earn portion of protocol revenue
  calculateGovernanceYield(stakedAmount, totalStaked, protocolRevenue) {
    const stakingRatio = stakedAmount / totalStaked;
    return protocolRevenue * stakingRatio * 0.1; // 10% to governance
  }
}

Sustainable Tokenomics

The Main SDK implements tokenomics that balance growth incentives with long-term sustainability: Token Utility Matrix:
  • Trading: Fee discounts for token holders
  • Liquidity Provision: Boosted farming rewards for token holders
  • Governance: Voting power proportional to stake
  • Staking: Direct yield generation from protocol fees
Emission Schedule:
class TokenEmission {
  constructor(totalSupply = 100_000_000) {
    this.totalSupply = totalSupply;
    this.distribution = {
      farming: 0.40,      // 40% for liquidity mining
      treasury: 0.25,     // 25% for treasury/development
      team: 0.15,         // 15% for team (vested)
      publicSale: 0.10,   // 10% for initial distribution
      reserves: 0.10      // 10% for future initiatives
    };
  }
  
  // Decreasing emission over time for sustainability
  calculateEmissionRate(currentBlock, startBlock) {
    const blocksElapsed = currentBlock - startBlock;
    const halvingPeriod = 2_102_400; // ~1 year at 1 block/second
    const halvingsCycles = Math.floor(blocksElapsed / halvingPeriod);
    
    const baseEmission = 1000; // Initial tokens per block
    return baseEmission / Math.pow(2, halvingsCycles);
  }
}

Technical Architecture Patterns

State Management

The Main SDK implements sophisticated state management to coordinate between different DeFi components:
class ProtocolState {
  constructor() {
    this.pools = new Map();        // AMM pool states
    this.farms = new Map();        // Farming program states  
    this.proposals = new Map();    // Governance proposals
    this.stakes = new Map();       // Staking positions
  }
  
  // Cross-component state synchronization
  async syncState() {
    // Update pool reserves and fees
    await this.updatePoolStates();
    
    // Recalculate farming APYs based on new pool states
    await this.updateFarmingAPYs();
    
    // Update governance voting power based on current stakes
    await this.updateVotingPower();
    
    // Emit state change events for UI updates
    this.emit('stateSync', this.getPublicState());
  }
  
  // Atomic operations across components
  async executeGovernanceAction(proposalId) {
    const proposal = this.proposals.get(proposalId);
    
    // Execute all actions atomically
    const transaction = new Transaction();
    for (const action of proposal.actions) {
      transaction.add(await action.createInstruction());
    }
    
    return this.connection.sendTransaction(transaction);
  }
}

Event-Driven Architecture

Components communicate through a robust event system that enables loose coupling and extensibility:
class DeFiEventBus extends EventEmitter {
  constructor() {
    super();
    this.setupCrossComponentEvents();
  }
  
  setupCrossComponentEvents() {
    // AMM events trigger farming updates
    this.on('pool:liquidityAdded', (poolId, amount, user) => {
      this.emit('farming:updateStake', poolId, amount, user);
    });
    
    // Farming events trigger governance power updates
    this.on('farming:rewardsHarvested', (user, amount) => {
      this.emit('governance:updateVotingPower', user);
    });
    
    // Governance events trigger protocol parameter changes
    this.on('governance:proposalExecuted', (proposalId, actions) => {
      this.executeProtocolChanges(actions);
    });
  }
}

Protocol Governance Model

Democratic Protocol Evolution

The Main SDK implements a comprehensive governance model that enables community-driven protocol evolution: Proposal Types:
  • Parameter Changes: Fee rates, farming rewards, staking parameters
  • Treasury Management: Fund allocation, grants, partnerships
  • Protocol Upgrades: Smart contract improvements, new feature additions
  • Emergency Actions: Pause mechanisms, security responses
Voting Mechanisms:
class GovernanceSystem {
  constructor() {
    this.votingPeriod = 604800;      // 1 week
    this.executionDelay = 172800;    // 2 days
    this.quorumThreshold = 0.04;     // 4% of total supply
    this.approvalThreshold = 0.51;   // 51% of votes cast
  }
  
  async createProposal(creator, title, description, actions) {
    const proposal = {
      id: this.generateProposalId(),
      creator,
      title,
      description,
      actions,
      votingStart: Date.now(),
      votingEnd: Date.now() + this.votingPeriod * 1000,
      forVotes: 0,
      againstVotes: 0,
      status: 'active'
    };
    
    // Require minimum stake to prevent spam
    await this.validateCreatorStake(creator);
    
    return proposal;
  }
  
  async executeProposal(proposalId) {
    const proposal = this.getProposal(proposalId);
    
    // Verify execution conditions
    this.validateExecution(proposal);
    
    // Execute all actions atomically
    const results = [];
    for (const action of proposal.actions) {
      results.push(await this.executeAction(action));
    }
    
    proposal.status = 'executed';
    this.emit('proposalExecuted', proposalId, results);
    
    return results;
  }
}

Treasury Management

The governance system controls a protocol treasury that funds ongoing development and ecosystem growth:
class ProtocolTreasury {
  constructor(governanceSystem) {
    this.governance = governanceSystem;
    this.assets = new Map();
    this.allocations = {
      development: 0.40,    // 40% for core development
      marketing: 0.20,      // 20% for growth and marketing
      grants: 0.25,         // 25% for ecosystem grants
      operations: 0.10,     // 10% for operational costs
      reserves: 0.05        // 5% emergency reserves
    };
  }
  
  // Treasury funding comes from protocol fees
  async collectProtocolFees() {
    const fees = await this.calculateTotalFees();
    
    for (const [token, amount] of fees) {
      const currentBalance = this.assets.get(token) || 0;
      this.assets.set(token, currentBalance + amount);
    }
    
    this.emit('feesCollected', fees);
  }
  
  // Governance-controlled fund allocation
  async allocateFunds(proposal) {
    if (!this.governance.isApproved(proposal)) {
      throw new Error('Proposal not approved');
    }
    
    const allocation = proposal.treasuryAllocation;
    await this.transferFunds(allocation.recipient, allocation.amount, allocation.token);
    
    this.emit('fundsAllocated', allocation);
  }
}

Integration Patterns

Frontend Integration

The Main SDK provides comprehensive frontend integration patterns that enable rich user experiences:
// React integration example
import { useMainSDK, useProtocolState } from '@saros/main-sdk-react';

function DeFiDashboard() {
  const sdk = useMainSDK();
  const { pools, farms, governance, loading } = useProtocolState();
  
  return (
    <div className="defi-dashboard">
      <PoolsOverview pools={pools} />
      <FarmingSection farms={farms} />
      <GovernancePanel proposals={governance.proposals} />
      <PortfolioSummary userPositions={sdk.getUserPositions()} />
    </div>
  );
}

Backend Infrastructure

The SDK supports sophisticated backend architectures for professional DeFi protocols:
class DeFiProtocolBackend {
  constructor() {
    this.sdk = new MainSDK(config);
    this.monitoring = new ProtocolMonitoring();
    this.analytics = new ProtocolAnalytics();
  }
  
  async startProtocol() {
    // Initialize all components
    await this.sdk.initialize();
    
    // Start monitoring services
    this.monitoring.trackPoolHealth();
    this.monitoring.trackTreasuryBalance();
    this.monitoring.trackGovernanceActivity();
    
    // Start analytics collection
    this.analytics.trackUserActivity();
    this.analytics.trackTVL();
    this.analytics.trackYieldMetrics();
  }
}
The Main SDK’s comprehensive architecture enables developers to build sophisticated DeFi protocols that rival the complexity and functionality of major DeFi platforms while maintaining code simplicity and maintainability. The modular design ensures that protocols can start simple and gradually add complexity as they grow, making it suitable for both early-stage projects and mature DeFi platforms.