Token Integration

A comprehensive guide to implementing and integrating liquid staking tokens (stSOL) in your protocol on Solana. Learn about token creation, management, exchange rates, and integration with DeFi protocols.

Last updated: 2024-03-21
Edit on GitHub

Overview

Token integration is a crucial component of liquid staking protocols. This guide covers all aspects of implementing and managing liquid staking tokens (stSOL), including token creation, exchange rate management, and DeFi protocol integration.

Integration Checklist

  • Token mint created
  • Exchange rate oracle configured
  • Minting/burning logic implemented
  • Security measures in place

Token Setup

Configure and deploy the liquid staking token (stSOL) with proper parameters and metadata.

Token Configuration

1// token/config.ts
2export const TOKEN_CONFIG = {
3  // Token metadata
4  metadata: {
5    name: 'Staked SOL',
6    symbol: 'stSOL',
7    description: 'Liquid staking token for Solana',
8    decimals: 9,
9    image: 'https://assets.stsol.com/logo.png',
10  },
11  
12  // Supply configuration
13  supply: {
14    initialSupply: new BN(0),
15    maxSupply: null, // Unlimited
16    mintAuthority: PROTOCOL_AUTHORITY,
17    freezeAuthority: null,
18  },
19  
20  // Token program configuration
21  program: {
22    version: 'v2',
23    features: {
24      transferFeeConfig: null,
25      permanentDelegate: null,
26      interestBearingConfig: null,
27    },
28  },
29  
30  // Metadata program configuration
31  metadataProgram: {
32    updateAuthority: PROTOCOL_AUTHORITY,
33    collection: null,
34    uses: null,
35  }
36}

Token Deployment

1// token/deployment.ts
2export async function deployToken(
3  connection: Connection,
4  payer: Keypair,
5  config: TokenConfig
6): Promise<PublicKey> {
7  // Create mint account
8  const mint = Keypair.generate()
9  const space = MintLayout.span
10  const lamports = await connection.getMinimumBalanceForRentExemption(space)
11  
12  const transaction = new Transaction().add(
13    SystemProgram.createAccount({
14      fromPubkey: payer.publicKey,
15      newAccountPubkey: mint.publicKey,
16      lamports,
17      space,
18      programId: TOKEN_PROGRAM_ID
19    }),
20    createInitializeMintInstruction(
21      mint.publicKey,
22      config.metadata.decimals,
23      config.supply.mintAuthority,
24      config.supply.freezeAuthority,
25      TOKEN_PROGRAM_ID
26    ),
27    createCreateMetadataAccountV3Instruction({
28      metadata: findMetadataPda(mint.publicKey),
29      mint: mint.publicKey,
30      mintAuthority: payer.publicKey,
31      payer: payer.publicKey,
32      updateAuthority: config.metadataProgram.updateAuthority,
33      data: {
34        name: config.metadata.name,
35        symbol: config.metadata.symbol,
36        uri: config.metadata.uri,
37        sellerFeeBasisPoints: 0,
38        creators: null,
39        collection: null,
40        uses: null,
41      },
42      isMutable: true,
43    })
44  )
45  
46  await sendAndConfirmTransaction(
47    connection,
48    transaction,
49    [payer, mint]
50  )
51  
52  return mint.publicKey
53}

Exchange Rate Management

Implement robust exchange rate calculation and management for stSOL/SOL conversions.

Exchange Rate Oracle

1// token/exchange-rate.ts
2export const EXCHANGE_RATE_CONFIG = {
3  // Update parameters
4  updates: {
5    frequency: 'epoch',
6    minChange: 0.0001, // 0.01% minimum change
7    maxChange: 0.01, // 1% maximum change per update
8    staleness: 2, // epochs before rate considered stale
9  },
10  
11  // Calculation parameters
12  calculation: {
13    // Total staked SOL + rewards - protocol fees
14    totalStake: async (connection: Connection) => {
15      const stakes = await getValidatorStakes(connection)
16      const rewards = await getValidatorRewards(connection)
17      const fees = await getProtocolFees(connection)
18      return stakes.add(rewards).sub(fees)
19    },
20    
21    // Total stSOL supply
22    totalSupply: async (connection: Connection) => {
23      const mint = await getMint(connection, STSOL_MINT)
24      return mint.supply
25    },
26    
27    // Exchange rate calculation
28    calculateRate: (totalStake: BN, totalSupply: BN) => {
29      if (totalSupply.isZero()) {
30        return new Decimal(1)
31      }
32      return new Decimal(totalStake.toString())
33        .div(new Decimal(totalSupply.toString()))
34    }
35  },
36  
37  // Safety checks
38  safety: {
39    minRate: new Decimal(0.5), // Minimum 0.5 SOL per stSOL
40    maxRate: new Decimal(2.0), // Maximum 2 SOL per stSOL
41    maxRateChange: 0.1, // Maximum 10% change from previous
42  }
43}
Exchange Rate Best Practices
  • Regular rate updates at epoch boundaries
  • Implement safety checks and bounds
  • Monitor for unusual rate changes
  • Keep historical rate data
  • Provide rate query APIs

Token Minting

Implement secure and efficient token minting logic for staking operations.

Minting Logic

1// token/minting.ts
2export const MINTING_CONFIG = {
3  // Minting parameters
4  parameters: {
5    minAmount: new BN(1_000_000), // 0.001 SOL
6    maxAmount: new BN(1_000_000_000_000), // 1000 SOL
7    cooldown: 0, // No cooldown between mints
8  },
9  
10  // Fee configuration
11  fees: {
12    deposit: 0.001, // 0.1% deposit fee
13    minimum: new BN(1_000_000), // 0.001 SOL minimum
14    recipient: PROTOCOL_TREASURY,
15  },
16  
17  // Minting limits
18  limits: {
19    perAccount: new BN(1_000_000_000_000_000), // 1M SOL
20    perTransaction: new BN(100_000_000_000_000), // 100k SOL
21    dailyLimit: new BN(10_000_000_000_000_000), // 10M SOL
22  },
23  
24  // Safety checks
25  safety: {
26    requireKYC: false,
27    requireAML: false,
28    blacklist: [],
29    pausable: true,
30  }
31}

Minting Implementation

1// token/mint.ts
2export async function mintStSol(
3  connection: Connection,
4  amount: BN,
5  user: PublicKey,
6  payer: Keypair
7): Promise<TransactionSignature> {
8  // Validate amount
9  if (amount.lt(MINTING_CONFIG.parameters.minAmount)) {
10    throw new Error('Amount below minimum')
11  }
12  if (amount.gt(MINTING_CONFIG.parameters.maxAmount)) {
13    throw new Error('Amount above maximum')
14  }
15  
16  // Calculate fees
17  const fee = amount.muln(MINTING_CONFIG.fees.deposit)
18  if (fee.lt(MINTING_CONFIG.fees.minimum)) {
19    fee = MINTING_CONFIG.fees.minimum
20  }
21  
22  // Calculate stSOL amount
23  const rate = await getExchangeRate(connection)
24  const stSolAmount = new Decimal(amount.toString())
25    .mul(rate)
26    .floor()
27    .toString()
28  
29  // Build transaction
30  const transaction = new Transaction().add(
31    // Transfer SOL to stake pool
32    SystemProgram.transfer({
33      fromPubkey: payer.publicKey,
34      toPubkey: STAKE_POOL,
35      lamports: amount,
36    }),
37    // Transfer fee
38    SystemProgram.transfer({
39      fromPubkey: payer.publicKey,
40      toPubkey: MINTING_CONFIG.fees.recipient,
41      lamports: fee,
42    }),
43    // Mint stSOL
44    createMintToInstruction(
45      STSOL_MINT,
46      userStSolAccount,
47      MINT_AUTHORITY,
48      stSolAmount,
49      [],
50      TOKEN_PROGRAM_ID
51    )
52  )
53  
54  return await sendAndConfirmTransaction(
55    connection,
56    transaction,
57    [payer]
58  )
59}

Token Burning

Implement secure token burning mechanisms for unstaking operations.

Burning Configuration

1// token/burning.ts
2export const BURNING_CONFIG = {
3  // Burning parameters
4  parameters: {
5    minAmount: new BN(1_000_000), // 0.001 stSOL
6    maxAmount: new BN(1_000_000_000_000), // 1000 stSOL
7    cooldown: 2, // 2 epoch cooldown
8  },
9  
10  // Fee configuration
11  fees: {
12    withdrawal: 0.002, // 0.2% withdrawal fee
13    minimum: new BN(2_000_000), // 0.002 SOL minimum
14    recipient: PROTOCOL_TREASURY,
15  },
16  
17  // Burning limits
18  limits: {
19    perAccount: new BN(1_000_000_000_000_000), // 1M stSOL
20    perTransaction: new BN(100_000_000_000_000), // 100k stSOL
21    dailyLimit: new BN(10_000_000_000_000_000), // 10M stSOL
22  },
23  
24  // Unstaking configuration
25  unstaking: {
26    method: 'delayed', // instant or delayed
27    delay: 2, // epochs
28    maxPending: 1000, // max pending unstakes
29    priorityFee: 0.001, // 0.1% for instant unstaking
30  }
31}

Burning Implementation

1// token/burn.ts
2export async function burnStSol(
3  connection: Connection,
4  amount: BN,
5  user: PublicKey,
6  payer: Keypair
7): Promise<TransactionSignature> {
8  // Validate amount
9  if (amount.lt(BURNING_CONFIG.parameters.minAmount)) {
10    throw new Error('Amount below minimum')
11  }
12  if (amount.gt(BURNING_CONFIG.parameters.maxAmount)) {
13    throw new Error('Amount above maximum')
14  }
15  
16  // Calculate fees
17  const fee = amount.muln(BURNING_CONFIG.fees.withdrawal)
18  if (fee.lt(BURNING_CONFIG.fees.minimum)) {
19    fee = BURNING_CONFIG.fees.minimum
20  }
21  
22  // Calculate SOL amount
23  const rate = await getExchangeRate(connection)
24  const solAmount = new Decimal(amount.toString())
25    .div(rate)
26    .floor()
27    .toString()
28  
29  // Build transaction
30  const transaction = new Transaction().add(
31    // Burn stSOL
32    createBurnInstruction(
33      STSOL_MINT,
34      userStSolAccount,
35      user,
36      amount,
37      [],
38      TOKEN_PROGRAM_ID
39    ),
40    // Create unstake request
41    createUnstakeRequestInstruction({
42      user,
43      amount: solAmount,
44      fee,
45      recipient: BURNING_CONFIG.fees.recipient,
46      epoch: await connection.getEpochInfo(),
47    })
48  )
49  
50  return await sendAndConfirmTransaction(
51    connection,
52    transaction,
53    [payer]
54  )
55}

DeFi Protocol Integration

Guidelines for integrating stSOL with DeFi protocols and implementing yield strategies.

Integration Guidelines

1// defi/integration.ts
2export const DEFI_INTEGRATION = {
3  // Protocol support
4  protocols: {
5    amm: {
6      poolTypes: ['constant-product', 'stable'],
7      recommendedPairs: ['SOL', 'USDC', 'USDT'],
8      minLiquidity: new BN(100_000_000_000), // 100 SOL
9    },
10    
11    lending: {
12      collateralFactor: 0.7, // 70% LTV
13      liquidationThreshold: 0.75,
14      liquidationPenalty: 0.05,
15      interestModel: 'jump-rate',
16    },
17    
18    yield: {
19      strategies: ['lending', 'liquidity'],
20      rewardTokens: ['RAY', 'MNDE'],
21      compounding: 'auto',
22    },
23  },
24  
25  // Risk parameters
26  risk: {
27    maxConcentration: 0.3, // 30% max in single protocol
28    minProtocolTVL: new BN(10_000_000_000_000), // 10k SOL
29    minProtocolAge: 180, // days
30    auditRequired: true,
31  },
32  
33  // Integration requirements
34  requirements: {
35    priceOracle: true,
36    emergencyWithdraw: true,
37    pausable: true,
38    upgradeability: 'transparent',
39  }
40}
DeFi Integration Best Practices
  • Thorough security audits of protocols
  • Implement emergency withdrawal mechanisms
  • Monitor protocol health and TVL
  • Regular yield strategy optimization
  • Maintain protocol diversification

Security Measures

Implement comprehensive security measures for token operations.

Security Configuration

1// token/security.ts
2export const SECURITY_CONFIG = {
3  // Access control
4  access: {
5    mintAuthority: {
6      type: 'multisig',
7      threshold: 4,
8      members: 7,
9    },
10    upgradeAuthority: {
11      type: 'timelock',
12      delay: 7 * 24 * 60 * 60, // 7 days
13      proposers: ['GOVERNANCE'],
14    },
15    pauseAuthority: {
16      type: 'immediate',
17      authorized: ['ADMIN', 'GUARDIAN'],
18    },
19  },
20  
21  // Transaction security
22  transactions: {
23    simulation: true,
24    maxRetries: 3,
25    confirmation: 'finalized',
26    timeout: 60_000, // ms
27  },
28  
29  // Monitoring
30  monitoring: {
31    supplyChanges: {
32      threshold: 0.05, // 5% change alert
33      window: '1h',
34    },
35    rateChanges: {
36      threshold: 0.02, // 2% change alert
37      window: '1h',
38    },
39    transactions: {
40      maxSize: new BN(1_000_000_000_000), // 1000 SOL
41      maxDaily: new BN(10_000_000_000_000), // 10000 SOL
42    },
43  },
44  
45  // Recovery procedures
46  recovery: {
47    backup: {
48      frequency: '1h',
49      retention: '30d',
50      encrypted: true,
51    },
52    procedures: {
53      rateDeviation: '/procedures/rate-deviation.md',
54      supplyMismatch: '/procedures/supply-mismatch.md',
55      contractUpgrade: '/procedures/upgrade.md',
56    },
57  }
58}
Critical Security Measures
  • Multi-signature control for critical operations
  • Rate and supply change monitoring
  • Transaction limits and cooling periods
  • Regular security audits
  • Comprehensive backup procedures