Governance Setup

A comprehensive guide to implementing decentralized governance for your liquid staking protocol on Solana. Learn about proposal creation, voting mechanisms, execution processes, and security measures.

Last updated: 2024-03-21
Edit on GitHub

Overview

Decentralized governance is essential for managing and upgrading your liquid staking protocol. This guide covers all aspects of implementing a robust governance system, including proposal creation, voting mechanisms, execution processes, and security measures.

Setup Checklist

  • Governance token configured
  • Voting parameters set
  • Timelock mechanism implemented
  • Security measures in place

Initial Setup

Configure and deploy the governance system with proper parameters and security measures.

Governance Configuration

1// governance/config.ts
2export const GOVERNANCE_CONFIG = {
3  // Governance token
4  token: {
5    mint: GOVERNANCE_TOKEN_MINT,
6    decimals: 9,
7    name: 'Governance Token',
8    symbol: 'GOV',
9  },
10  
11  // Voting configuration
12  voting: {
13    quorum: 0.04, // 4% of total supply
14    threshold: 0.60, // 60% yes votes required
15    votingDelay: 1, // 1 epoch delay before voting
16    votingPeriod: 3, // 3 epochs for voting
17    minProposalPower: new BN(100_000_000_000), // 100 tokens
18  },
19  
20  // Proposal settings
21  proposals: {
22    maxActions: 10,
23    maxDescriptionLen: 10_000,
24    cooldownPeriod: 1, // 1 epoch between proposals
25    executionDelay: 2, // 2 epochs after approval
26  },
27  
28  // Council configuration
29  council: {
30    enabled: true,
31    members: COUNCIL_MEMBERS,
32    threshold: 4, // 4 out of N required
33    veto: true, // Can veto proposals
34  }
35}

Governance Deployment

1// governance/deployment.ts
2export async function deployGovernance(
3  connection: Connection,
4  payer: Keypair,
5  config: GovernanceConfig
6): Promise<PublicKey> {
7  // Create governance program account
8  const governance = Keypair.generate()
9  const space = GovernanceLayout.span
10  const lamports = await connection.getMinimumBalanceForRentExemption(space)
11  
12  const transaction = new Transaction().add(
13    // Create governance account
14    SystemProgram.createAccount({
15      fromPubkey: payer.publicKey,
16      newAccountPubkey: governance.publicKey,
17      lamports,
18      space,
19      programId: GOVERNANCE_PROGRAM_ID
20    }),
21    
22    // Initialize governance
23    createInitializeGovernanceInstruction({
24      governance: governance.publicKey,
25      config: {
26        votingDelay: config.voting.votingDelay,
27        votingPeriod: config.voting.votingPeriod,
28        quorumVotes: calculateQuorumVotes(config),
29        thresholdVotes: calculateThresholdVotes(config),
30        timelock: config.proposals.executionDelay,
31        proposalThreshold: config.voting.minProposalPower,
32        votingToken: config.token.mint,
33      },
34      councilMembers: config.council.members,
35      councilThreshold: config.council.threshold,
36      payer: payer.publicKey,
37    })
38  )
39  
40  await sendAndConfirmTransaction(
41    connection,
42    transaction,
43    [payer, governance]
44  )
45  
46  return governance.publicKey
47}

Proposal Management

Implement secure proposal creation and management functionality.

Proposal Creation

1// governance/proposals.ts
2export const PROPOSAL_CONFIG = {
3  // Proposal types
4  types: {
5    PARAMETER_CHANGE: {
6      id: 1,
7      name: 'Parameter Change',
8      description: 'Update protocol parameters',
9      requiredPower: new BN(1000_000_000_000), // 1000 tokens
10    },
11    PROGRAM_UPGRADE: {
12      id: 2,
13      name: 'Program Upgrade',
14      description: 'Upgrade program code',
15      requiredPower: new BN(5000_000_000_000), // 5000 tokens
16    },
17    EMERGENCY_ACTION: {
18      id: 3,
19      name: 'Emergency Action',
20      description: 'Emergency protocol actions',
21      requiredPower: new BN(10000_000_000_000), // 10000 tokens
22    },
23  },
24  
25  // Validation rules
26  validation: {
27    titleMinLength: 10,
28    titleMaxLength: 100,
29    descriptionMinLength: 100,
30    descriptionMaxLength: 10000,
31    maxActions: 10,
32    requiredFields: [
33      'title',
34      'description',
35      'actions',
36      'type',
37    ],
38  },
39  
40  // Lifecycle hooks
41  hooks: {
42    beforeCreate: async (proposal) => {
43      // Validate proposal
44      validateProposal(proposal)
45      // Check proposer power
46      await checkProposerPower(proposal)
47      // Simulate actions
48      await simulateActions(proposal)
49    },
50    afterCreate: async (proposal) => {
51      // Notify stakeholders
52      await notifyProposalCreated(proposal)
53      // Index proposal
54      await indexProposal(proposal)
55    },
56  }
57}
Proposal Best Practices
  • Clear proposal guidelines and templates
  • Thorough action simulation before execution
  • Proper parameter validation
  • Comprehensive proposal metadata
  • Transparent discussion process

Voting Mechanism

Implement secure and efficient voting mechanisms with proper power calculation.

Voting Configuration

1// governance/voting.ts
2export const VOTING_CONFIG = {
3  // Vote types
4  voteTypes: {
5    FOR: 0,
6    AGAINST: 1,
7    ABSTAIN: 2,
8  },
9  
10  // Vote weight calculation
11  weightCalculation: {
12    // Base voting power
13    baseWeight: (tokenAmount: BN) => tokenAmount,
14    
15    // Time-lock multiplier
16    timeMultiplier: (lockDuration: number) => {
17      const maxMultiplier = 2.0 // 2x max multiplier
18      const maxLockDuration = 365 * 24 * 60 * 60 // 1 year
19      return 1 + (lockDuration / maxLockDuration) * (maxMultiplier - 1)
20    },
21    
22    // Delegation rules
23    delegation: {
24      enabled: true,
25      maxDelegates: 1,
26      lockRequired: false,
27    },
28  },
29  
30  // Vote tracking
31  tracking: {
32    // Vote receipt
33    receipt: {
34      enabled: true,
35      transferable: false,
36      metadata: true,
37    },
38    
39    // Vote history
40    history: {
41      enabled: true,
42      indexed: true,
43      retention: '365d',
44    },
45  },
46  
47  // Vote restrictions
48  restrictions: {
49    // Minimum holding period
50    minHoldingPeriod: 2, // epochs
51    
52    // Vote changes
53    allowVoteChanges: true,
54    changeDeadline: 0.5, // 50% of voting period
55    
56    // Vote cancellation
57    allowCancellation: false,
58  }
59}

Vote Processing

1// governance/process-vote.ts
2export async function processVote(
3  connection: Connection,
4  vote: Vote,
5  user: PublicKey,
6  payer: Keypair
7): Promise<TransactionSignature> {
8  // Validate vote
9  if (!isValidVote(vote)) {
10    throw new Error('Invalid vote')
11  }
12  
13  // Check voting power
14  const votingPower = await calculateVotingPower(
15    connection,
16    user,
17    vote.proposal
18  )
19  
20  if (votingPower.lt(VOTING_CONFIG.minVotingPower)) {
21    throw new Error('Insufficient voting power')
22  }
23  
24  // Check restrictions
25  await validateVoteRestrictions(
26    connection,
27    vote,
28    user
29  )
30  
31  // Build vote transaction
32  const transaction = new Transaction().add(
33    // Cast vote
34    createCastVoteInstruction({
35      proposal: vote.proposal,
36      voter: user,
37      vote: vote.voteType,
38      votingPower,
39      metadata: vote.metadata,
40    }),
41    
42    // Create vote receipt
43    createVoteReceiptInstruction({
44      proposal: vote.proposal,
45      voter: user,
46      receipt: generateVoteReceipt(vote),
47    })
48  )
49  
50  // Process vote
51  const signature = await sendAndConfirmTransaction(
52    connection,
53    transaction,
54    [payer]
55  )
56  
57  // Update vote tracking
58  await updateVoteTracking(vote, signature)
59  
60  return signature
61}

Proposal Execution

Implement secure proposal execution with proper validation and safety measures.

Execution Process

1// governance/execution.ts
2export const EXECUTION_CONFIG = {
3  // Execution requirements
4  requirements: {
5    // Voting requirements
6    voting: {
7      quorumMet: true,
8      thresholdMet: true,
9      votingEnded: true,
10      noVetos: true,
11    },
12    
13    // Timelock requirements
14    timelock: {
15      delayMet: true,
16      notExpired: true,
17      queuedProperly: true,
18    },
19    
20    // Technical requirements
21    technical: {
22      validActions: true,
23      simulationPassed: true,
24      resourcesAvailable: true,
25    },
26  },
27  
28  // Execution process
29  process: {
30    // Pre-execution checks
31    preExecution: async (proposal) => {
32      // Validate requirements
33      await validateRequirements(proposal)
34      // Check action validity
35      await validateActions(proposal)
36      // Simulate execution
37      await simulateExecution(proposal)
38    },
39    
40    // Execution steps
41    steps: {
42      // Queue for execution
43      queue: async (proposal) => {
44        await queueProposal(proposal)
45      },
46      
47      // Execute actions
48      execute: async (proposal) => {
49        for (const action of proposal.actions) {
50          await executeAction(action)
51        }
52      },
53      
54      // Post-execution
55      postExecution: async (proposal) => {
56        await updateState(proposal)
57        await emitEvents(proposal)
58        await notifyExecution(proposal)
59      },
60    },
61    
62    // Error handling
63    errorHandling: {
64      retryable: [
65        'ResourceUnavailable',
66        'NetworkError',
67        'TimeoutError',
68      ],
69      maxRetries: 3,
70      backoff: 'exponential',
71    },
72  },
73  
74  // Execution monitoring
75  monitoring: {
76    metrics: [
77      'executionTime',
78      'resourceUsage',
79      'errorRate',
80      'successRate',
81    ],
82    alerts: {
83      executionFailed: true,
84      highResourceUsage: true,
85      longExecutionTime: true,
86    },
87  }
88}
Execution Safety
  • Always simulate actions before execution
  • Implement proper error handling
  • Monitor execution metrics
  • Have fallback procedures
  • Keep execution logs

Timelock Mechanism

Implement secure timelock mechanisms for proposal execution.

Timelock Configuration

1// governance/timelock.ts
2export const TIMELOCK_CONFIG = {
3  // Delay configuration
4  delays: {
5    // Standard changes
6    STANDARD: {
7      delay: 2, // 2 epochs
8      maxDelay: 10, // 10 epochs
9      minDelay: 1, // 1 epoch
10    },
11    
12    // Critical changes
13    CRITICAL: {
14      delay: 5, // 5 epochs
15      maxDelay: 20, // 20 epochs
16      minDelay: 3, // 3 epochs
17    },
18    
19    // Emergency actions
20    EMERGENCY: {
21      delay: 0, // No delay
22      maxDelay: 1, // 1 epoch
23      minDelay: 0, // No delay
24    },
25  },
26  
27  // Cancellation settings
28  cancellation: {
29    // Who can cancel
30    cancelAuthority: {
31      council: true,
32      proposer: true,
33      governance: true,
34    },
35    
36    // Cancellation window
37    window: {
38      start: 0, // Immediate
39      end: 0.8, // Up to 80% of delay
40    },
41    
42    // Restrictions
43    restrictions: {
44      requireReason: true,
45      allowPartial: false,
46      minimumDelay: 1, // 1 epoch after cancel
47    },
48  },
49  
50  // Queue management
51  queue: {
52    // Capacity limits
53    capacity: {
54      maxQueued: 100,
55      maxPerType: 10,
56      maxPerProposer: 5,
57    },
58    
59    // Prioritization
60    priority: {
61      emergency: 0, // Highest
62      critical: 1,
63      standard: 2,
64    },
65    
66    // Execution order
67    order: 'priority', // priority or fifo
68  }
69}

Timelock Implementation

1// governance/timelock-processor.ts
2export async function processTimelock(
3  connection: Connection,
4  proposal: Proposal,
5  payer: Keypair
6): Promise<TransactionSignature> {
7  // Get timelock configuration
8  const config = getTimelockConfig(proposal.type)
9  
10  // Validate timelock requirements
11  if (!meetsTimelockRequirements(proposal, config)) {
12    throw new Error('Does not meet timelock requirements')
13  }
14  
15  // Calculate timelock period
16  const timelockPeriod = calculateTimelockPeriod(
17    proposal,
18    config
19  )
20  
21  // Build timelock transaction
22  const transaction = new Transaction().add(
23    // Queue proposal
24    createQueueProposalInstruction({
25      proposal: proposal.publicKey,
26      timelockPeriod,
27      config: config.queue,
28    }),
29    
30    // Create timelock state
31    createTimelockStateInstruction({
32      proposal: proposal.publicKey,
33      eta: calculateExecutionTime(timelockPeriod),
34      actions: proposal.actions,
35    })
36  )
37  
38  // Process timelock
39  const signature = await sendAndConfirmTransaction(
40    connection,
41    transaction,
42    [payer]
43  )
44  
45  // Update proposal state
46  await updateProposalState(
47    proposal,
48    ProposalState.Queued
49  )
50  
51  return signature
52}

Security Measures

Implement comprehensive security measures for governance operations.

Security Configuration

1// governance/security.ts
2export const SECURITY_CONFIG = {
3  // Access control
4  access: {
5    // Role configuration
6    roles: {
7      ADMIN: {
8        permissions: ['FULL_ACCESS'],
9        multisig: true,
10        threshold: 4,
11      },
12      PROPOSER: {
13        permissions: ['CREATE_PROPOSAL'],
14        powerRequired: true,
15        threshold: new BN(1000_000_000_000),
16      },
17      VOTER: {
18        permissions: ['VOTE'],
19        powerRequired: true,
20        threshold: new BN(1_000_000_000),
21      },
22    },
23    
24    // Action permissions
25    actions: {
26      UPGRADE_PROGRAM: ['ADMIN'],
27      CHANGE_CONFIG: ['ADMIN', 'GOVERNANCE'],
28      EMERGENCY_ACTION: ['ADMIN', 'COUNCIL'],
29    },
30  },
31  
32  // Transaction security
33  transactions: {
34    simulation: true,
35    verification: true,
36    maxRetries: 3,
37    timeout: 60_000,
38  },
39  
40  // Monitoring
41  monitoring: {
42    // Proposal monitoring
43    proposals: {
44      rateLimit: 10, // per epoch
45      complexityLimit: 5, // max actions
46      sizeLimit: 100_000, // bytes
47    },
48    
49    // Vote monitoring
50    votes: {
51      rateLimit: 1000, // per epoch
52      powerLimit: 0.1, // 10% of supply
53      changeLimit: 3, // changes per vote
54    },
55    
56    // System monitoring
57    system: {
58      metrics: ['cpu', 'memory', 'storage'],
59      alerts: true,
60      logging: true,
61    },
62  },
63  
64  // Recovery procedures
65  recovery: {
66    // Backup procedures
67    backup: {
68      frequency: '1h',
69      retention: '30d',
70      encrypted: true,
71    },
72    
73    // Emergency procedures
74    emergency: {
75      shutdown: true,
76      recovery: true,
77      contact: EMERGENCY_CONTACTS,
78    },
79  }
80}
Critical Security Measures
  • Multi-signature control for critical actions
  • Proper role-based access control
  • Transaction simulation and verification
  • Rate limiting and monitoring
  • Emergency procedures and recovery plans