stellar-governance 0.7.0

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
use soroban_sdk::{
    contracttype, panic_with_error, xdr::ToXdr, Address, Bytes, BytesN, Env, Symbol, Val, Vec,
};

use crate::timelock::{
    emit_min_delay_changed, emit_operation_cancelled, emit_operation_executed,
    emit_operation_scheduled, TimelockError, DONE_LEDGER, TIMELOCK_EXTEND_AMOUNT,
    TIMELOCK_TTL_THRESHOLD, UNSET_LEDGER,
};

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

/// Represents a operation to be executed by the timelock.
///
/// An operation encapsulates all the information needed to invoke a function
/// on a target contract after the timelock delay has passed.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Operation {
    /// The contract address to call
    pub target: Address,
    /// The function name to invoke on the target contract
    pub function: Symbol,
    /// The serialized arguments to pass to the function
    pub args: Vec<Val>,
    /// Hash of a predecessor operation that must be executed first.
    /// Use BytesN::<32>::from_array(&[0u8; 32]) for no predecessor.
    pub predecessor: BytesN<32>,
    /// A salt value for operation uniqueness.
    /// Allows scheduling the same operation multiple times with different IDs.
    pub salt: BytesN<32>,
}

/// The state of an operation in the timelock system.
#[contracttype]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u32)]
pub enum OperationState {
    /// Operation has not been scheduled
    Unset,
    /// Operation is scheduled but the delay period has not passed
    Waiting,
    /// Operation is ready to be executed (delay has passed)
    Ready,
    /// Operation has been executed
    Done,
}

/// Storage keys for the timelock module.
#[derive(Clone)]
#[contracttype]
pub enum TimelockStorageKey {
    /// Minimum delay in ledgers for operations
    MinDelay,
    /// Maps operation ID to the ledger sequence number when it will be in a
    /// [`OperationState::Ready`] state (Note: value is 0 for
    /// [`OperationState::Unset`], 1 for [`OperationState::Done`]).
    OperationLedger(BytesN<32>),
}

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

/// Returns the minimum delay in ledgers required for operations.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
///
/// # Returns
///
/// The minimum delay in ledgers.
///
/// # Errors
///
/// * [`TimelockError::MinDelayNotSet`] - If the minimum delay has not been set.
pub fn get_min_delay(e: &Env) -> u32 {
    e.storage()
        .instance()
        .get(&TimelockStorageKey::MinDelay)
        .unwrap_or_else(|| panic_with_error!(e, TimelockError::MinDelayNotSet))
}

/// Returns the ledger sequence number at which an operation becomes ready.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
///
/// # Returns
///
/// - `UNSET_LEDGER` for unset operations
/// - `DONE_LEDGER` for done operations
/// - Ledger sequence number when the operation becomes ready for scheduled
///   operations
pub fn get_operation_ledger(e: &Env, operation_id: &BytesN<32>) -> u32 {
    let key = TimelockStorageKey::OperationLedger(operation_id.clone());
    if let Some(ready_ledger) = e.storage().persistent().get::<_, u32>(&key) {
        e.storage().persistent().extend_ttl(&key, TIMELOCK_TTL_THRESHOLD, TIMELOCK_EXTEND_AMOUNT);
        ready_ledger
    } else {
        UNSET_LEDGER
    }
}

/// Returns the current state of an operation.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
///
/// # Returns
///
/// The current [`OperationState`] of the operation.
pub fn get_operation_state(e: &Env, operation_id: &BytesN<32>) -> OperationState {
    let ready_ledger = get_operation_ledger(e, operation_id);
    let current_ledger = e.ledger().sequence();

    match ready_ledger {
        UNSET_LEDGER => OperationState::Unset,
        DONE_LEDGER => OperationState::Done,
        ready if ready > current_ledger => OperationState::Waiting,
        _ => OperationState::Ready,
    }
}

/// Returns whether an operation has been scheduled (in any state except Unset).
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
pub fn operation_exists(e: &Env, operation_id: &BytesN<32>) -> bool {
    get_operation_state(e, operation_id) != OperationState::Unset
}

/// Returns whether an operation is pending (Waiting or Ready).
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
pub fn is_operation_pending(e: &Env, operation_id: &BytesN<32>) -> bool {
    let state = get_operation_state(e, operation_id);
    state == OperationState::Waiting || state == OperationState::Ready
}

/// Returns whether an operation is ready for execution.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
pub fn is_operation_ready(e: &Env, operation_id: &BytesN<32>) -> bool {
    get_operation_state(e, operation_id) == OperationState::Ready
}

/// Returns whether an operation has been executed.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation.
pub fn is_operation_done(e: &Env, operation_id: &BytesN<32>) -> bool {
    get_operation_state(e, operation_id) == OperationState::Done
}

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

/// Sets the minimum delay required for operations.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `min_delay` - The new minimum delay in ledgers.
///
/// # Events
///
/// * topics - `["min_delay_changed"]`
/// * data - `[old_delay: u32, new_delay: u32]`
///
/// # Security Warning
///
/// **IMPORTANT**: This function does not perform authorization checks.
/// The caller must ensure proper authorization before calling this function.
pub fn set_min_delay(e: &Env, min_delay: u32) {
    let old_delay =
        e.storage().instance().get::<_, u32>(&TimelockStorageKey::MinDelay).unwrap_or(0);
    e.storage().instance().set(&TimelockStorageKey::MinDelay, &min_delay);
    emit_min_delay_changed(e, old_delay, min_delay);
}

/// Schedules an operation for execution after a delay.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation` - The operation to schedule.
/// * `delay` - The delay in ledgers before the operation can be executed.
///
/// # Returns
///
/// The unique identifier (hash) of the scheduled operation.
///
/// # Errors
///
/// * [`TimelockError::OperationAlreadyScheduled`] - If the operation is already
///   scheduled.
/// * [`TimelockError::InsufficientDelay`] - If the delay is less than the
///   minimum delay.
/// * [`TimelockError::MinDelayNotSet`] - If the minimum delay has not been
///   initialized.
///
/// # Events
///
/// * topics - `["operation_scheduled", id: BytesN<32>, target: Address]`
/// * data - `[function: Symbol, args: Vec<Val>, predecessor: BytesN<32>, salt:
///   BytesN<32>, delay: u32]`
///
/// # Security Warning
///
/// **IMPORTANT**: This function does not perform authorization checks.
/// The caller must ensure proper authorization before calling this function.
pub fn schedule_operation(e: &Env, operation: &Operation, delay: u32) -> BytesN<32> {
    let id = hash_operation(e, operation);

    if operation_exists(e, &id) {
        panic_with_error!(e, TimelockError::OperationAlreadyScheduled);
    }

    // Get minimum delay (will panic if not set)
    let min_delay = get_min_delay(e);

    if delay < min_delay {
        panic_with_error!(e, TimelockError::InsufficientDelay);
    }

    let current_ledger = e.ledger().sequence();
    let ready_ledger = current_ledger.saturating_add(delay);

    let key = TimelockStorageKey::OperationLedger(id.clone());
    e.storage().persistent().set(&key, &ready_ledger);

    emit_operation_scheduled(
        e,
        &id,
        &operation.target,
        &operation.function,
        &operation.args,
        &operation.predecessor,
        &operation.salt,
        delay,
    );

    id
}

/// Executes a scheduled operation by invoking the target contract.
///
/// This is a wrapper around [`set_execute_operation`] that also performs the
/// cross-contract invocation. For self-administration scenarios where the
/// target is the timelock contract itself, use [`set_execute_operation`]
/// directly instead.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation` - The operation to execute.
///
/// # Returns
///
/// The return value from the invoked contract function.
///
/// # Errors
///
/// * [`TimelockError::InvalidOperationState`] - If the operation is not ready
///   for execution.
/// * [`TimelockError::UnexecutedPredecessor`] - If the predecessor operation
///   has not been executed.
///
/// # Events
///
/// * topics - `["operation_executed", id: BytesN<32>, target: Address]`
/// * data - `[function: Symbol, args: Vec<Val>, predecessor: BytesN<32>, salt:
///   BytesN<32>]`
///
/// # Security Warning
///
/// **IMPORTANT**: This function does not perform authorization checks.
/// The caller must ensure proper authorization before calling this function.
pub fn execute_operation(e: &Env, operation: &Operation) -> Val {
    set_execute_operation(e, operation);

    e.invoke_contract::<Val>(&operation.target, &operation.function, operation.args.clone())
}

/// Validates and marks an operation as executed without invoking the target.
///
/// This function performs all the validation and state updates for executing
/// an operation, but does not perform the cross-contract invocation. It is
/// used by [`execute_operation`] and can be called directly for
/// self-administration scenarios where the timelock contract needs to execute
/// operations on itself.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation` - The operation to validate and mark as executed.
///
/// # Errors
///
/// * [`TimelockError::InvalidOperationState`] - If the operation is not ready
///   for execution.
/// * [`TimelockError::UnexecutedPredecessor`] - If the predecessor operation
///   has not been executed.
///
/// # Events
///
/// * topics - `["operation_executed", id: BytesN<32>, target: Address]`
/// * data - `[function: Symbol, args: Vec<Val>, predecessor: BytesN<32>, salt:
///   BytesN<32>]`
///
/// # Security Warning
///
/// **IMPORTANT**: This function does not perform authorization checks.
/// The caller must ensure proper authorization before calling this function.
pub fn set_execute_operation(e: &Env, operation: &Operation) {
    let id = hash_operation(e, operation);

    if !is_operation_ready(e, &id) {
        panic_with_error!(e, TimelockError::InvalidOperationState);
    }

    // Check predecessor is done (if specified)
    let no_predecessor = BytesN::<32>::from_array(e, &[0u8; 32]);
    if operation.predecessor != no_predecessor && !is_operation_done(e, &operation.predecessor) {
        panic_with_error!(e, TimelockError::UnexecutedPredecessor);
    }

    let key = TimelockStorageKey::OperationLedger(id.clone());
    e.storage().persistent().set(&key, &DONE_LEDGER);

    emit_operation_executed(
        e,
        &id,
        &operation.target,
        &operation.function,
        &operation.args,
        &operation.predecessor,
        &operation.salt,
    );
}

/// Cancels a scheduled operation.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation_id` - The unique identifier of the operation to cancel.
///
/// # Errors
///
/// * [`TimelockError::InvalidOperationState`] - If the operation is not pending
///   (must be Waiting or Ready).
///
/// # Events
///
/// * topics - `["operation_cancelled", id: BytesN<32>]`
/// * data - `[]`
///
/// # Security Warning
///
/// **IMPORTANT**: This function does not perform authorization checks.
/// The caller must ensure proper authorization before calling this function.
pub fn cancel_operation(e: &Env, operation_id: &BytesN<32>) {
    if !is_operation_pending(e, operation_id) {
        panic_with_error!(e, TimelockError::InvalidOperationState);
    }

    let key = TimelockStorageKey::OperationLedger(operation_id.clone());
    e.storage().persistent().remove(&key);

    emit_operation_cancelled(e, operation_id);
}

// ################## HASHING ##################

/// Computes the unique identifier for a operation.
///
/// The operation ID is derived from all operation parameters using Keccak256.
/// This ensures that the same operation parameters always produce the same ID,
/// unless the salt is changed.
///
/// # Arguments
///
/// * `e` - Access to Soroban environment.
/// * `operation` - The operation to hash.
///
/// # Returns
///
/// A 32-byte hash uniquely identifying the operation.
pub fn hash_operation(e: &Env, operation: &Operation) -> BytesN<32> {
    let mut data = Bytes::new(e);

    data.append(&operation.target.clone().to_xdr(e));
    data.append(&operation.function.clone().to_xdr(e));
    data.append(&operation.args.clone().to_xdr(e));
    data.append(&operation.predecessor.clone().into());
    data.append(&operation.salt.clone().into());

    e.crypto().keccak256(&data).into()
}