-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathcurrent_lib.rs
More file actions
655 lines (601 loc) · 23.5 KB
/
Copy pathcurrent_lib.rs
File metadata and controls
655 lines (601 loc) · 23.5 KB
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#![no_std]
pub mod archive;
use soroban_sdk::{contract, contractimpl, contracttype, Address, Env};
#[contracttype]
#[derive(Clone)]
pub enum DataKey {
Vault,
TotalSettled,
}
pub use errors::SettlementError;
pub use timelock::PendingDeveloperMigration;
pub use types::*;
/// Tracks a developer's cumulative withdrawal amount for a given epoch day.
///
/// `day` is `timestamp / 86400` (UTC epoch day). When the current call's day
/// differs from the stored day the accumulator is silently reset.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DailyWithdrawState {
pub day: u64,
pub amount: i128,
}
/// Timestamp range during which a developer may claim accrued balance.
///
/// `start_ts` and `end_ts` are ledger timestamps in seconds. The window is
/// inclusive on both ends: a withdrawal is allowed when
/// `start_ts <= env.ledger().timestamp() <= end_ts`.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DeveloperClaimWindow {
pub start_ts: u64,
pub end_ts: u64,
}
/// Payment received event
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct PaymentReceivedEvent {
pub from_vault: Address,
pub amount: i128,
pub to_pool: bool, // true if credited to global pool, false if to specific developer
pub developer: Option<Address>, // developer address if credited to specific developer
pub token: Address,
}
/// Balance credited event
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct BalanceCreditedEvent {
pub developer: Address,
pub amount: i128,
pub new_balance: i128,
pub token: Address,
}
/// Emitted when a deposit is made for a developer.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DepositEvent {
pub developer: Address,
pub token: Address,
pub amount: i128,
}
/// Emitted when a new vault address is proposed via `propose_vault()`.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VaultProposedEvent {
pub current_vault: Address,
pub proposed_vault: Address,
}
/// Emitted when the proposed vault is accepted via `accept_vault()`.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct VaultAcceptedEvent {
pub old_vault: Address,
pub new_vault: Address,
pub accepted_by: Address,
}
/// Emitted when a developer withdraws their balance.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DeveloperWithdrawEvent {
pub developer: Address,
pub amount: i128,
pub remaining_balance: i128,
pub to: Address,
pub token: Address,
}
/// Emitted when the admin sets or changes a developer's daily withdrawal cap.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DailyWithdrawCapChanged {
pub developer: Address,
pub new_cap: i128,
}
/// Emitted when the admin sets or clears a developer claim window.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DeveloperClaimWindowChanged {
pub developer: Address,
pub start_ts: u64,
pub end_ts: u64,
pub enabled: bool,
}
/// Emitted when an admin force-credits a developer balance (escape hatch).
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct DeveloperForceCreditedEvent {
pub developer: Address,
pub amount: i128,
pub reason: Symbol,
pub new_balance: i128,
pub token: Address,
}
/// Emitted when the admin proposes or executes a timelock'd developer balance migration.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct AdminMigrationEvent {
pub from: Address,
pub to: Address,
pub amount: i128,
pub executed_at: u64,
}
/// Storage TTL entry for a given storage key category.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct StorageEntryTtl {
pub category: String,
pub key_desc: String,
pub storage_type: String,
pub ttl: u32,
pub threshold: u32,
pub bump_amount: u32,
}
/// Severity levels for admin broadcast messages.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub enum Severity {
Info,
Warn,
Crit,
}
/// Payload for the `admin_broadcast` event.
#[contracttype]
#[derive(Clone, Debug, PartialEq)]
pub struct AdminBroadcast {
pub severity: Severity,
pub message: String,
}
/// Maximum byte length for the `reason` Symbol in `force_credit_developer`.
/// The Soroban SDK enforces a 32-byte limit on Symbol values at construction;
/// this constant is used for explicit defense-in-depth validation.
pub const MAX_REASON_LENGTH: u32 = 32;
#[contract]
pub struct CalloraSettlement;
#[contractimpl]
impl CalloraSettlement {
pub fn init(env: Env, vault: Address) {
if env.storage().instance().has(&DataKey::Vault) {
panic!("Already initialized");
}
env.storage().instance().set(&DataKey::Vault, &vault);
env.storage().instance().set(&DataKey::TotalSettled, &0i128);
}
/// Receive payment from vault and credit to pool or developer balance.
///
/// # Arguments
/// * `caller` - Must be authorized vault address or admin
/// * `amount` - Payment amount in token micro-units; must be > 0
/// * `to_pool` - If true, credit global pool; if false, credit a specific developer
/// * `developer` - Required when `to_pool=false`; ignored when `to_pool=true`
/// * `token` - The token contract address for this payment
///
/// # Access Control
/// Only the registered vault address or admin can call this function.
///
/// # Persistent Storage Operations
/// When crediting to developer balance:
/// - Performs O(1) point-read from persistent storage for the developer + token
/// - Updates the specific developer's balance in persistent storage
/// - Extends persistent TTL for the developer's balance entry
/// - Adds developer to index if not already present
/// - Does NOT iterate any maps; only point operations
///
/// # Events
/// Always emits `payment_received`. Also emits `balance_credited` when `to_pool=false`.
///
/// # Arithmetic Safety
/// Credits use checked arithmetic:
/// - Pool credits panic with `"pool balance overflow"` on `i128` overflow.
/// - Developer credits panic with `"developer balance overflow"` on `i128` overflow.
pub fn receive_payment(
env: Env,
caller: Address,
amount: i128,
to_pool: bool,
developer: Option<Address>,
token: Address,
) {
caller.require_auth();
Self::require_authorized_caller(env.clone(), caller.clone());
if amount <= 0 {
env.panic_with_error(SettlementError::AmountNotPositive);
}
let inst = env.storage().instance();
if to_pool {
if developer.is_some() {
env.panic_with_error(SettlementError::DeveloperMustBeNone);
}
let mut global_pool = Self::get_global_pool(env.clone());
global_pool.total_balance = global_pool
.total_balance
.checked_add(amount)
.unwrap_or_else(|| env.panic_with_error(SettlementError::PoolOverflow));
global_pool.last_updated = env.ledger().timestamp();
inst.set(&StorageKey::GlobalPool, &global_pool);
env.events().publish(
(events::event_payment_received(&env), caller.clone()),
PaymentReceivedEvent {
from_vault: caller.clone(),
amount,
to_pool: true,
developer: None,
token: token.clone(),
},
);
} else {
let dev_address = developer
.unwrap_or_else(|| env.panic_with_error(SettlementError::DeveloperRequired));
// Per-token balance key: (developer, token)
let balance_key = StorageKey::DeveloperBalance(dev_address.clone(), token.clone());
// Read current balance from persistent storage
let current_balance: i128 = env
.storage()
.persistent()
.get(&balance_key)
.unwrap_or(0i128);
let new_balance = current_balance
.checked_add(amount)
.unwrap_or_else(|| env.panic_with_error(SettlementError::DeveloperOverflow));
// Write to persistent storage with TTL extension
env.storage().persistent().set(&balance_key, &new_balance);
// Extend TTL for the developer's balance entry (persistent storage live for 1 year)
env.storage()
.persistent()
.extend_ttl(&balance_key, 50000, 50000);
// Add developer to index in sorted order if not already present
let mut index: Vec<Address> = inst
.get(&StorageKey::DeveloperIndex)
.unwrap_or_else(|| Vec::new(&env));
Self::sorted_insert(&env, &mut index, dev_address.clone());
inst.set(&StorageKey::DeveloperIndex, &index);
env.events().publish(
(events::event_payment_received(&env), caller.clone()),
PaymentReceivedEvent {
from_vault: caller.clone(),
amount,
to_pool: false,
developer: Some(dev_address.clone()),
token: token.clone(),
},
);
env.events().publish(
(events::event_balance_credited(&env), dev_address.clone()),
BalanceCreditedEvent {
developer: dev_address.clone(),
amount,
new_balance,
token: token.clone(),
},
);
env.events().publish(
(events::event_deposit(&env), dev_address.clone()),
DepositEvent {
developer: dev_address,
token,
amount,
},
);
}
// Increment cumulative received total regardless of routing (pool or developer).
let inst = env.storage().instance();
let prev: i128 = inst.get(&StorageKey::TotalReceived).unwrap_or(0i128);
inst.set(
&StorageKey::TotalReceived,
&prev
.checked_add(amount)
.unwrap_or_else(|| env.panic_with_error(SettlementError::PoolOverflow)),
);
}
/// Atomically credit multiple developer balances in a single call.
///
/// # Arguments
/// * `caller` - Must be the registered vault address or admin
/// * `items` - Vec of `(developer_address, amount)` pairs; 1–[`MAX_BATCH_SIZE`] entries
/// * `token` - The token contract address for this batch payment
///
/// # Access Control
/// Only the registered vault address or admin can call this function.
///
/// # Validation
/// All amounts must be `> 0`. Empty and oversized batches are rejected before any state change.
///
/// # Atomicity
/// All validation runs before any state is written. A failure on any item leaves the
/// contract state unchanged.
///
/// # Events
/// Emits `balance_credited` for each item in the batch.
///
/// # Panics
/// * `"batch_receive_payment requires at least one item"` — empty batch
/// * `"batch too large"` — more than [`MAX_BATCH_SIZE`] items
/// * `"amount must be positive"` — any amount ≤ 0
/// * `"developer balance overflow"` — `i128` overflow on any developer balance
pub fn batch_receive_payment(
env: Env,
caller: Address,
items: Vec<(Address, i128)>,
token: Address,
) {
caller.require_auth();
Self::require_authorized_caller(env.clone(), caller.clone());
let n = items.len();
assert!(n > 0, "batch_receive_payment requires at least one item");
assert!(n <= MAX_BATCH_SIZE, "batch too large");
// Validate all amounts before touching state.
for item in items.iter() {
let (_, amount) = item;
assert!(amount > 0, "amount must be positive");
}
let inst = env.storage().instance();
for item in items.iter() {
let (dev, amount) = item;
let balance_key = StorageKey::DeveloperBalance(dev.clone(), token.clone());
let current: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0);
let new_balance = current
.checked_add(amount)
.unwrap_or_else(|| env.panic_with_error(SettlementError::DeveloperOverflow));
env.storage().persistent().set(&balance_key, &new_balance);
env.storage()
.persistent()
.extend_ttl(&balance_key, 50000, 50000);
// Add to index in sorted order if not already present
let mut index: Vec<Address> = inst
.get(&StorageKey::DeveloperIndex)
.unwrap_or_else(|| Vec::new(&env));
Self::sorted_insert(&env, &mut index, dev.clone());
inst.set(&StorageKey::DeveloperIndex, &index);
env.events().publish(
(events::event_balance_credited(&env), dev.clone()),
BalanceCreditedEvent {
developer: dev.clone(),
amount,
new_balance,
token: token.clone(),
},
);
env.events().publish(
(events::event_deposit(&env), dev.clone()),
DepositEvent {
developer: dev.clone(),
token: token.clone(),
amount,
},
);
}
// Increment cumulative received total by the batch sum.
let batch_total: i128 = items.iter().map(|(_, a)| a).fold(0i128, |acc, a| {
acc.checked_add(a)
.unwrap_or_else(|| env.panic_with_error(SettlementError::PoolOverflow))
});
let prev: i128 = inst.get(&StorageKey::TotalReceived).unwrap_or(0i128);
inst.set(
&StorageKey::TotalReceived,
&prev
.checked_add(batch_total)
.unwrap_or_else(|| env.panic_with_error(SettlementError::PoolOverflow)),
);
}
/// Get current admin address
pub fn get_admin(env: Env) -> Address {
env.storage()
.instance()
.get(&StorageKey::Admin)
.unwrap_or_else(|| env.panic_with_error(SettlementError::NotInitialized))
}
/// Returns the contract version from Cargo.toml
pub fn version(_env: Env) -> soroban_sdk::String {
soroban_sdk::String::from_str(&_env, env!("CARGO_PKG_VERSION"))
}
/// Get registered vault address
pub fn get_vault(env: Env) -> Address {
env.storage()
.instance()
.get(&StorageKey::Vault)
.unwrap_or_else(|| env.panic_with_error(SettlementError::NotInitialized))
}
/// Get global pool information
pub fn get_global_pool(env: Env) -> GlobalPool {
env.storage()
.instance()
.get(&StorageKey::GlobalPool)
.unwrap_or_else(|| env.panic_with_error(SettlementError::NotInitialized))
}
/// Get developer balance for a specific token.
///
/// Performs a direct O(1) persistent storage lookup for the specified
/// developer's balance denominated in `token`.
///
/// # Arguments
/// * `developer` - Developer address to query
/// * `token` - Token contract address
///
/// # Returns
/// Balance in token micro-units, or 0 if no balance recorded
///
/// # Safety
/// Safe for all use cases; uses persistent storage with TTL.
pub fn get_developer_balance(env: Env, developer: Address, token: Address) -> i128 {
if !env.storage().instance().has(&StorageKey::Admin) {
env.panic_with_error(SettlementError::NotInitialized);
}
env.storage()
.persistent()
.get(&StorageKey::DeveloperBalance(developer, token))
.unwrap_or(0)
}
/// Propose moving a developer's current balance to a replacement address.
///
/// The current admin must authorize this state change. If the admin is a
/// Stellar multisig account, `require_auth` enforces that account's signer
/// thresholds. The proposal snapshots the source balance and becomes
/// executable after [`DEVELOPER_MIGRATION_TIMELOCK_SECONDS`]. Re-proposing
/// for the same source replaces the prior proposal and restarts the delay.
///
/// # Errors
/// Panics with a typed [`SettlementError`] when the caller is unauthorized,
/// the addresses are equal or unsafe, the source balance is empty, or the
/// execution timestamp cannot be represented.
pub fn propose_balance_migration(env: Env, caller: Address, from: Address, to: Address) {
admin::propose_balance_migration(&env, &caller, &from, &to);
}
/// Execute a matured developer balance migration proposal.
///
/// The current admin must authorize execution independently of proposal.
/// Exactly the amount approved at proposal time is moved; credits received
/// afterward remain at `from`. The destination balance addition is checked
/// for overflow, and the consumed proposal is removed to prevent replay.
///
/// # Events
/// Emits `admin_migration` with [`AdminMigrationEvent`] after success.
pub fn execute_balance_migration(env: Env, caller: Address, from: Address) {
admin::execute_balance_migration(&env, &caller, &from);
}
/// Return the pending migration for `from`, if one exists.
pub fn get_balance_migration(env: Env, from: Address) -> Option<PendingDeveloperMigration> {
timelock::get_pending_migration(&env, &from)
}
/// Configure the USDC token contract address.
///
/// Only the current admin may set the on-chain USDC token address that this
/// contract will use to execute withdrawals.
pub fn set_usdc_token(env: Env, caller: Address, usdc_address: Address) {
caller.require_auth();
let current_admin = Self::get_admin(env.clone());
if caller != current_admin {
panic!("unauthorized: caller is not admin");
}
if usdc_address == env.current_contract_address() {
panic!("invalid config: usdc_token cannot be the contract itself");
}
env.storage()
.instance()
.set(&StorageKey::Usdc, &usdc_address);
}
fn get_usdc_token(env: Env) -> Result<Address, SettlementError> {
env.storage()
.instance()
.get(&StorageKey::Usdc)
.ok_or(SettlementError::UsdcTokenNotConfigured)
}
/// Withdraw developer balance as USDC to a designated recipient.
///
/// Requires the developer to authorize the request, the amount to be
/// positive, the developer's optional claim window to be open, and the
/// requested amount to be covered by the tracked developer balance.
///
/// # Arguments
/// * `developer` - Address of the developer withdrawing their balance.
/// * `amount` - Amount to withdraw in USDC micro-units.
/// * `to` - Optional recipient address; if `None`, defaults to `developer`.
///
/// # Errors
/// - `AmountNotPositive` if amount is <= 0.
/// - `ClaimWindowClosed` if a developer claim window exists and the current
/// ledger timestamp is outside that inclusive window.
/// - `InsufficientDeveloperBalance` if developer balance < amount.
/// - `DailyWithdrawCapExceeded` if daily cap is exceeded.
/// - `DeveloperBalanceUnderflow` if subtraction underflows.
/// - `UsdcTokenNotConfigured` if USDC token not set.
/// - `InsufficientContractBalance` if contract has insufficient USDC.
/// - Panics if `to` is the contract's own address.
pub fn withdraw_developer_balance(
env: Env,
developer: Address,
amount: i128,
to: Option<Address>,
) -> Result<(), SettlementError> {
developer.require_auth();
if amount <= 0 {
return Err(SettlementError::AmountNotPositive);
}
let usdc_address = Self::get_usdc_token(env.clone())?;
let usdc = token::Client::new(&env, &usdc_address);
let recipient = to.unwrap_or_else(|| developer.clone());
let contract_address = env.current_contract_address();
if recipient == contract_address {
panic!("invalid recipient: cannot withdraw to contract itself");
}
Self::require_claim_window_open(&env, &developer)?;
let usdc_address = Self::get_usdc_token(env.clone())?;
let current_balance: i128 = env
.storage()
.instance()
.get::<_, Address>(&DataKey::Vault)
.unwrap();
vault.require_auth();
let total = env
.storage()
.instance()
.get::<_, i128>(&DataKey::TotalSettled)
.unwrap_or(0);
let new_total = total.checked_add(amount).unwrap();
env.storage()
.instance()
.set(&DataKey::TotalSettled, &new_total);
}
/// Migrate a single developer's V1 balance to V2 (admin only).
pub fn migrate_developer_balance(
env: Env,
caller: Address,
developer: Address,
) -> Result<(), SettlementError> {
migrate::migrate_single_developer(&env, &caller, &developer)
}
/// Migrate a single developer's V1 balance to V2 (admin only).
pub fn migrate_single_dev_v2(
env: Env,
caller: Address,
developer: Address,
) -> Result<(), SettlementError> {
migrate::migrate_single_developer(&env, &caller, &developer)
}
/// Migrate a single developer's V1 balance to V2 (admin only).
pub fn migrate_developer_balance(
env: Env,
caller: Address,
developer: Address,
) -> Result<(), SettlementError> {
migrate::migrate_single_developer(&env, &caller, &developer)
}
/// Migrate a single developer's V1 balance to V2 (admin only).
pub fn migrate_single_dev_v2(
env: Env,
caller: Address,
developer: Address,
) -> Result<(), SettlementError> {
migrate::migrate_single_developer(&env, &caller, &developer)
}
/// Batch-withdraw developer balances with a cursor for pagination.
///
/// Processes up to `limit` (max: `MAX_BATCH_SIZE`) developers from the
/// provided `developers` list starting at `cursor` index.
///
/// Each developer authorises its own withdrawal; callers that have not
/// called `require_auth` will cause the transaction to abort.
///
/// Returns `(next_cursor, is_complete)`. When `is_complete` is `true` the
/// full list has been processed.
pub fn batch_withdraw_developer_balance_cursor(
env: Env,
developers: Vec<Address>,
amounts: Vec<i128>,
cursor: u32,
limit: u32,
) -> Result<(u32, bool), SettlementError> {
let count = developers.len();
if count != amounts.len() {
return Err(SettlementError::AmountNotPositive); // mismatched inputs
}
let safe_limit = limit.min(MAX_BATCH_SIZE);
let start = cursor as usize;
let end = (start + safe_limit as usize).min(count as usize);
for i in start..end {
let developer = developers.get(i as u32).ok_or(SettlementError::InsufficientDeveloperBalance)?;
let amount = amounts.get(i as u32).ok_or(SettlementError::AmountNotPositive)?;
Self::withdraw_developer_balance(env.clone(), developer, amount, None)?;
}
let next_cursor = end as u32;
let is_complete = next_cursor >= count;
Ok((next_cursor, is_complete))
}
}