stellar-governance 0.7.1

Governance Utilities for Stellar contracts.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use soroban_sdk::{contracttype, panic_with_error, Address, Env};

use crate::votes::{
    emit_delegate_changed, emit_delegate_votes_changed, VotesError, VOTES_EXTEND_AMOUNT,
    VOTES_TTL_THRESHOLD,
};

// ################## ENUMS ##################

/// Represents the direction of a checkpoint delta operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CheckpointOp {
    /// Add the delta to the previous value (e.g., minting, receiving votes).
    Add,
    /// Subtract the delta from the previous value (e.g., burning, losing
    /// votes).
    Sub,
}

// ################## TYPES ##################

/// A checkpoint recording voting power at a specific ledger sequence number.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Checkpoint {
    /// The ledger sequence number when this checkpoint was created
    pub ledger: u32,
    /// The voting power at this ledger sequence number
    pub votes: u128,
}

/// Selects the checkpoint timeline to operate on.
///
/// Each variant maps to a different set of storage keys so that
/// per-account voting-power history and aggregate total supply history
/// are kept separate.
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub enum CheckpointType {
    /// The global total supply checkpoint.
    TotalSupply,
    /// A per-account (delegate) voting-power checkpoint.
    Account(Address),
}

/// Storage keys for the votes module.
///
/// Only delegated voting power counts as votes (i.e., only delegatees can
/// vote), so the storage design tracks delegates and their checkpointed
/// voting power separately from the raw voting units held by each account.
#[derive(Clone)]
#[contracttype]
pub enum VotesStorageKey {
    /// Maps account to its delegate
    Delegatee(Address),
    /// Number of checkpoints for a delegate
    NumCheckpoints(Address),
    /// Individual checkpoint for a delegate at index
    DelegateCheckpoint(Address, u32),
    /// Number of total supply checkpoints
    NumTotalSupplyCheckpoints,
    /// Individual total supply checkpoint at index
    TotalSupplyCheckpoint(u32),
    /// Voting units held by an account (tracked separately from delegation)
    VotingUnits(Address),
}

// ################## QUERY STATE ##################

/// Gets a checkpoint at a specific index for the given checkpoint type.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `checkpoint_type` - Type of the checkpoint (per-account or total supply).
/// * `index` - Index of the checkpoint.
///
/// # Errors
///
/// [`VotesError::CheckpointNotFound`] - If no checkpoint exists
/// at the given index.
pub fn get_checkpoint(e: &Env, checkpoint_type: &CheckpointType, index: u32) -> Checkpoint {
    let key = checkpoint_storage_key(checkpoint_type, index);
    let Some(checkpoint) = e.storage().persistent().get::<_, Checkpoint>(&key) else {
        panic_with_error!(e, VotesError::CheckpointNotFound);
    };
    e.storage().persistent().extend_ttl(&key, VOTES_TTL_THRESHOLD, VOTES_EXTEND_AMOUNT);
    checkpoint
}

/// Returns the current voting power (delegated votes) of an account.
///
/// This is the total voting power delegated to this account by others
/// (and itself if self-delegated). Returns `0` if no voting power has been
/// delegated to this account, or if the account does not exist in the
/// contract.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The address to query voting power for.
pub fn get_votes(e: &Env, account: &Address) -> u128 {
    let cp_type = CheckpointType::Account(account.clone());
    let num = get_num_checkpoints(e, &cp_type);
    if num == 0 {
        return 0;
    }
    get_checkpoint(e, &cp_type, num - 1).votes
}

/// Returns the voting power (delegated votes) of an account at a specific
/// past ledger sequence number.
///
/// Returns `0` if no voting power had been delegated to this account at the
/// given ledger, or if the account does not exist in the contract.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The address to query voting power for.
/// * `ledger` - The ledger sequence number to query (must be in the past).
///
/// # Errors
///
/// * [`VotesError::FutureLookup`] - If `ledger` >= current ledger sequence
///   number.
pub fn get_votes_at_checkpoint(e: &Env, account: &Address, ledger: u32) -> u128 {
    if ledger >= e.ledger().sequence() {
        panic_with_error!(e, VotesError::FutureLookup);
    }

    let cp_type = CheckpointType::Account(account.clone());
    let num = get_num_checkpoints(e, &cp_type);

    lookup_checkpoint_at(e, ledger, num, &cp_type)
}

/// Returns the current total supply of voting units.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
pub fn get_total_supply(e: &Env) -> u128 {
    let cp_type = CheckpointType::TotalSupply;
    let num = get_num_checkpoints(e, &cp_type);
    if num == 0 {
        return 0;
    }
    get_checkpoint(e, &cp_type, num - 1).votes
}

/// Returns the total supply of voting units at a specific past ledger
/// sequence number.
///
/// Returns `0` if there were no voting units at the given ledger.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `ledger` - The ledger sequence number to query (must be in the past).
///
/// # Errors
///
/// * [`VotesError::FutureLookup`] - If `ledger` >= current ledger sequence
///   number.
pub fn get_total_supply_at_checkpoint(e: &Env, ledger: u32) -> u128 {
    if ledger >= e.ledger().sequence() {
        panic_with_error!(e, VotesError::FutureLookup);
    }

    let cp_type = CheckpointType::TotalSupply;
    let num = get_num_checkpoints(e, &cp_type);

    lookup_checkpoint_at(e, ledger, num, &cp_type)
}

/// Returns the delegate for an account.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The address to query the delegate for.
///
/// # Returns
///
/// * `Some(Address)` - The delegate address (may be the account itself if
///   self-delegated).
/// * `None` - If the account has never delegated. An account whose delegate is
///   `None` has no active voting power; it must call [`delegate`] (even to
///   itself) before its votes are counted.
pub fn get_delegate(e: &Env, account: &Address) -> Option<Address> {
    let key = VotesStorageKey::Delegatee(account.clone());
    if let Some(delegatee) = e.storage().persistent().get::<_, Address>(&key) {
        e.storage().persistent().extend_ttl(&key, VOTES_TTL_THRESHOLD, VOTES_EXTEND_AMOUNT);
        Some(delegatee)
    } else {
        None
    }
}

/// Returns the number of checkpoints for an account.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The address to query checkpoints for.
pub fn num_checkpoints(e: &Env, account: &Address) -> u32 {
    get_num_checkpoints(e, &CheckpointType::Account(account.clone()))
}

/// Returns the voting units held by an account.
///
/// Voting units represent the underlying balance that can be delegated.
/// This is tracked separately from the delegated voting power.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The address to query voting units for.
pub fn get_voting_units(e: &Env, account: &Address) -> u128 {
    let key = VotesStorageKey::VotingUnits(account.clone());
    if let Some(units) = e.storage().persistent().get::<_, u128>(&key) {
        e.storage().persistent().extend_ttl(&key, VOTES_TTL_THRESHOLD, VOTES_EXTEND_AMOUNT);
        units
    } else {
        0
    }
}

// ################## CHANGE STATE ##################

/// Delegates voting power from `account` to `delegatee`.
///
/// To reclaim voting power (i.e. "undelegate"), call this with `delegatee`
/// set to `account` (self-delegation). There is no separate undelegate
/// operation.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `account` - The account delegating its voting power.
/// * `delegatee` - The account receiving the delegated voting power.
///
/// # Events
///
/// * topics - `["delegate_changed", delegator: Address]`
/// * data - `[from_delegate: Option<Address>, to_delegate: Address]`
///
/// * topics - `["delegate_votes_changed", delegate: Address]`
/// * data - `[old_votes: u128, new_votes: u128]`
///
/// # Errors
///
/// * [`VotesError::SameDelegate`] - If `delegatee` is already the current
///   delegate for `account`.
///
/// # Notes
///
/// Authorization for `account` is required.
pub fn delegate(e: &Env, account: &Address, delegatee: &Address) {
    account.require_auth();
    let old_delegate = get_delegate(e, account);

    if old_delegate.as_ref() == Some(delegatee) {
        panic_with_error!(e, VotesError::SameDelegate);
    }

    e.storage().persistent().set(&VotesStorageKey::Delegatee(account.clone()), delegatee);

    emit_delegate_changed(e, account, old_delegate.clone(), delegatee);

    let voting_units = get_voting_units(e, account);
    move_delegate_votes(e, old_delegate.as_ref(), Some(delegatee), voting_units);
}

/// Transfers voting units between accounts.
///
/// This function should be called by the token contract whenever tokens
/// are transferred, minted, or burned. It updates the voting power of
/// the delegates accordingly.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `from` - The source account (`None` for minting).
/// * `to` - The destination account (`None` for burning).
/// * `amount` - The amount of voting units to transfer.
///
/// # Events
///
/// * topics - `["delegate_votes_changed", delegate: Address]`
/// * data - `[previous_votes: u128, new_votes: u128]`
///
/// # Notes
///
/// This function does not perform authorization - it should be called
/// from within the token contract's transfer/mint/burn logic.
pub fn transfer_voting_units(e: &Env, from: Option<&Address>, to: Option<&Address>, amount: u128) {
    if amount == 0 {
        return;
    }

    // Look up delegates first so we can make a single move_delegate_votes call
    let from_delegate = from.and_then(|addr| get_delegate(e, addr));
    let to_delegate = to.and_then(|addr| get_delegate(e, addr));

    if let Some(from_addr) = from {
        let from_units = get_voting_units(e, from_addr);
        let Some(new_from_units) = from_units.checked_sub(amount) else {
            panic_with_error!(e, VotesError::InsufficientVotingUnits);
        };
        set_voting_units(e, from_addr, new_from_units);
    } else {
        // Minting: increase total supply
        push_checkpoint(e, &CheckpointType::TotalSupply, CheckpointOp::Add, amount);
    }

    if let Some(to_addr) = to {
        let to_units = get_voting_units(e, to_addr);
        let Some(new_to_units) = to_units.checked_add(amount) else {
            panic_with_error!(e, VotesError::MathOverflow);
        };
        set_voting_units(e, to_addr, new_to_units);
    } else {
        // Burning: decrease total supply
        push_checkpoint(e, &CheckpointType::TotalSupply, CheckpointOp::Sub, amount);
    }

    move_delegate_votes(e, from_delegate.as_ref(), to_delegate.as_ref(), amount);
}

// ################## INTERNAL HELPERS ##################

/// Sets the voting units for an account.
fn set_voting_units(e: &Env, account: &Address, units: u128) {
    let key = VotesStorageKey::VotingUnits(account.clone());
    if units == 0 {
        e.storage().persistent().remove(&key);
    } else {
        e.storage().persistent().set(&key, &units);
    }
}

/// Moves delegated votes from one delegate to another.
fn move_delegate_votes(e: &Env, from: Option<&Address>, to: Option<&Address>, amount: u128) {
    if amount == 0 {
        return;
    }

    if from == to {
        return;
    }

    if let Some(from_addr) = from {
        let cp_type = CheckpointType::Account(from_addr.clone());
        let (old_votes, new_votes) = push_checkpoint(e, &cp_type, CheckpointOp::Sub, amount);
        emit_delegate_votes_changed(e, from_addr, old_votes, new_votes);
    }

    if let Some(to_addr) = to {
        let cp_type = CheckpointType::Account(to_addr.clone());
        let (old_votes, new_votes) = push_checkpoint(e, &cp_type, CheckpointOp::Add, amount);
        emit_delegate_votes_changed(e, to_addr, old_votes, new_votes);
    }
}

/// Binary search over checkpoints to find votes at a given ledger.
fn lookup_checkpoint_at(e: &Env, ledger: u32, num: u32, checkpoint_type: &CheckpointType) -> u128 {
    if num == 0 {
        return 0;
    }

    // Check if ledger is after the latest checkpoint
    let latest = get_checkpoint(e, checkpoint_type, num - 1);
    if latest.ledger <= ledger {
        return latest.votes;
    }

    // Check if ledger is before the first checkpoint
    let first = get_checkpoint(e, checkpoint_type, 0);
    if first.ledger > ledger {
        return 0;
    }

    // Binary search
    let mut low: u32 = 0;
    let mut high: u32 = num - 1;

    while low < high {
        let mid = low + (high - low).div_ceil(2);
        let checkpoint = get_checkpoint(e, checkpoint_type, mid);
        if checkpoint.ledger <= ledger {
            low = mid;
        } else {
            high = mid - 1;
        }
    }

    get_checkpoint(e, checkpoint_type, low).votes
}

/// Applies a [`CheckpointOp`] to compute the new votes value from the
/// previous value and a delta.
fn apply_checkpoint_op(e: &Env, previous: u128, op: CheckpointOp, delta: u128) -> u128 {
    match op {
        CheckpointOp::Add => previous
            .checked_add(delta)
            .unwrap_or_else(|| panic_with_error!(e, VotesError::MathOverflow)),
        CheckpointOp::Sub => previous
            .checked_sub(delta)
            .unwrap_or_else(|| panic_with_error!(e, VotesError::MathOverflow)),
    }
}

/// Returns the storage key for a checkpoint at the given index.
fn checkpoint_storage_key(checkpoint_type: &CheckpointType, index: u32) -> VotesStorageKey {
    match checkpoint_type {
        CheckpointType::TotalSupply => VotesStorageKey::TotalSupplyCheckpoint(index),
        CheckpointType::Account(account) => {
            VotesStorageKey::DelegateCheckpoint(account.clone(), index)
        }
    }
}

/// Returns the number of checkpoints for the given checkpoint type.
fn get_num_checkpoints(e: &Env, checkpoint_type: &CheckpointType) -> u32 {
    match checkpoint_type {
        CheckpointType::TotalSupply => {
            let key = VotesStorageKey::NumTotalSupplyCheckpoints;
            e.storage().instance().get(&key).unwrap_or(0)
        }
        CheckpointType::Account(account) => {
            let key = VotesStorageKey::NumCheckpoints(account.clone());
            if let Some(checkpoints) = e.storage().persistent().get::<_, u32>(&key) {
                e.storage().persistent().extend_ttl(&key, VOTES_TTL_THRESHOLD, VOTES_EXTEND_AMOUNT);
                checkpoints
            } else {
                0
            }
        }
    }
}

/// Pushes a new checkpoint or updates the last one if same ledger sequence
/// number. Returns (previous_votes, new_votes).
fn push_checkpoint(
    e: &Env,
    checkpoint_type: &CheckpointType,
    op: CheckpointOp,
    delta: u128,
) -> (u128, u128) {
    let num = get_num_checkpoints(e, checkpoint_type);
    let ledger = e.ledger().sequence();

    let last_checkpoint =
        if num > 0 { Some(get_checkpoint(e, checkpoint_type, num - 1)) } else { None };

    let previous_votes = last_checkpoint.as_ref().map_or(0, |cp| cp.votes);
    let votes = apply_checkpoint_op(e, previous_votes, op, delta);

    // Check if we can update the last checkpoint (same ledger sequence number)
    if let Some(cp) = &last_checkpoint {
        if cp.ledger == ledger {
            let key = checkpoint_storage_key(checkpoint_type, num - 1);
            e.storage().persistent().set(&key, &Checkpoint { ledger, votes });
            return (previous_votes, votes);
        }
    }

    // Create new checkpoint
    let key = checkpoint_storage_key(checkpoint_type, num);
    e.storage().persistent().set(&key, &Checkpoint { ledger, votes });

    // Update checkpoint count
    match checkpoint_type {
        CheckpointType::TotalSupply => {
            let num_key = VotesStorageKey::NumTotalSupplyCheckpoints;
            e.storage().instance().set(&num_key, &(num + 1));
        }
        CheckpointType::Account(account) => {
            let num_key = VotesStorageKey::NumCheckpoints(account.clone());
            e.storage().persistent().set(&num_key, &(num + 1));
        }
    }

    (previous_votes, votes)
}