-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathlib.rs
More file actions
1098 lines (989 loc) · 42.1 KB
/
Copy pathlib.rs
File metadata and controls
1098 lines (989 loc) · 42.1 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # bc-forge Token Contract
//!
//! A compact SEP-41-compatible token used by the vesting contract tests.
//!
//! @title BcForgeToken
//! @author bc-forge contributors
#![no_std]
mod events;
mod rate_limit;
mod reentrancy_guard;
#[cfg(test)]
mod test;
#[cfg(test)]
mod fuzz_mint;
#[cfg(test)]
mod lockup;
#[cfg(test)]
mod storage_collisions;
use bc_forge_admin as admin;
use bc_forge_ttl as ttl;
use soroban_sdk::token::TokenInterface;
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, Address, BytesN, Env, String, Vec,
};
/// A mint recipient with an amount.
///
/// @title Recipient
#[contracttype]
pub struct Recipient {
/// The recipient address.
pub to: Address,
/// The amount to mint or transfer.
pub amount: i128,
}
#[derive(Clone)]
#[contracttype]
pub enum DataKey {
/// Admin address — stored here for caller convenience; delegates to `AdminKey::Admin`.
Admin,
/// Legacy pending admin — unused; retained to preserve storage discriminant order.
/// The transfer-ownership flow uses `admin::set_admin` directly.
PendingAdmin,
/// Spending allowance: (owner, spender) -> amount and expiration ledger.
Allowance(Address, Address),
/// Legacy allowance expiration — stored per-key; prefer `AllowanceData` struct.
AllowanceExp(Address, Address),
/// Token balance for an address.
Balance(Address),
/// Lockup state for an address: amount currently locked and the timestamp
/// at which the locked tokens become withdrawable.
Lockup(Address),
/// Number of decimal places for the token.
Decimals,
/// Token name (e.g., "bc-forge Token").
Name,
/// Token symbol (e.g., "SFG").
Symbol,
/// Current total token supply.
Supply,
/// Maximum total supply cap.
MaxSupply,
/// Treasury address for collected fees.
Treasury,
/// Fee configuration.
FeeConfig,
/// Fee exemptions keyed by address.
FeeExemption(Address),
}
/// Fee configuration for dynamic contract fee charging.
///
/// @title FeeConfig
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct FeeConfig {
/// Base fee amount charged per operation.
pub base_fee: i128,
/// Multiplier applied to the fee based on operation complexity.
pub complexity_multiplier: u32,
/// Maximum fee cap.
pub max_fee: i128,
/// Whether fee charging is enabled.
pub enabled: bool,
}
/// Fee exemption for a specific address.
///
/// @title FeeExemption
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct FeeExemption {
/// Exemption type: 0 = all operations, 1 = transfers only, 2 = mint only.
pub exemption_type: u32,
}
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
struct AllowanceData {
amount: i128,
expiration_ledger: u32,
}
/// Lockup period state for a single user, stored per address under
/// [`DataKey::Lockup`].
///
/// @title LockupState
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct LockupState {
/// Total amount of tokens currently locked for the user.
pub amount: i128,
/// Unix timestamp (seconds since epoch) at which the locked tokens
/// become withdrawable.
pub unlock_timestamp: u64,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[contracterror]
#[repr(u32)]
pub enum TokenError {
/// Contract has already been initialized; cannot re-initialize.
AlreadyInitialized = 1,
/// Contract has not been initialized yet.
NotInitialized = 2,
/// The amount provided is invalid (e.g., negative or zero).
InvalidAmount = 3,
/// The caller's balance is insufficient for the requested operation.
InsufficientBalance = 4,
/// The spender's allowance is insufficient for the requested operation.
InsufficientAllowance = 5,
/// The contract is currently paused and operations are rejected.
ContractPaused = 6,
/// Fee configuration has not been set.
FeeNotConfigured = 7,
/// Treasury balance is insufficient to cover the fee.
InsufficientFeeBalance = 8,
/// No fee exemption found for the specified address.
FeeExemptionNotFound = 9,
/// Minting would exceed the configured maximum supply.
MaxSupplyExceeded = 10,
AlreadyPaused = 11,
NotPaused = 12,
}
#[contract]
pub struct BcForgeToken;
impl BcForgeToken {
fn ensure_initialized(env: &Env) -> Result<(), TokenError> {
if admin::has_admin(env) {
Ok(())
} else {
Err(TokenError::NotInitialized)
}
}
fn panic_on_err<T>(env: &Env, result: Result<T, TokenError>) -> T {
match result {
Ok(value) => value,
Err(error) => soroban_sdk::panic_with_error!(env, error),
}
}
fn ensure_not_paused(env: &Env) -> Result<(), TokenError> {
if bc_forge_lifecycle::is_paused(env) {
Err(TokenError::ContractPaused)
} else {
Ok(())
}
}
fn read_balance(env: &Env, address: &Address) -> i128 {
env.storage()
.persistent()
.get(&DataKey::Balance(address.clone()))
.unwrap_or(0)
}
fn write_balance(env: &Env, address: &Address, amount: i128) {
env.storage()
.persistent()
.set(&DataKey::Balance(address.clone()), &amount);
}
fn read_supply(env: &Env) -> i128 {
let key = DataKey::Supply;
if env.storage().instance().has(&key) {
ttl::extend_instance_ttl(env);
}
env.storage().instance().get(&key).unwrap_or(0)
}
fn write_supply(env: &Env, supply: i128) {
env.storage().instance().set(&DataKey::Supply, &supply);
ttl::extend_instance_ttl(env);
}
fn read_max_supply(env: &Env) -> i128 {
let key = DataKey::MaxSupply;
if env.storage().instance().has(&key) {
ttl::extend_instance_ttl(env);
}
env.storage().instance().get(&key).unwrap_or(i128::MAX)
}
fn write_max_supply(env: &Env, max_supply: i128) {
env.storage()
.instance()
.set(&DataKey::MaxSupply, &max_supply);
ttl::extend_instance_ttl(env);
}
fn read_allowance_data(env: &Env, from: &Address, spender: &Address) -> AllowanceData {
env.storage()
.persistent()
.get(&DataKey::Allowance(from.clone(), spender.clone()))
.unwrap_or(AllowanceData {
amount: 0,
expiration_ledger: 0,
})
}
fn allowance_amount(env: &Env, from: &Address, spender: &Address) -> i128 {
let data = Self::read_allowance_data(env, from, spender);
if data.expiration_ledger > 0 && env.ledger().sequence() > data.expiration_ledger {
0
} else {
data.amount
}
}
fn extend_instance_ttl_for_call(env: &Env) {
ttl::extend_instance_ttl(env);
}
fn write_allowance(env: &Env, from: &Address, spender: &Address, amount: i128, exp: u32) {
let data = AllowanceData {
amount,
expiration_ledger: exp,
};
env.storage()
.persistent()
.set(&DataKey::Allowance(from.clone(), spender.clone()), &data);
}
fn move_balance(
env: &Env,
from: &Address,
to: &Address,
amount: i128,
) -> Result<(), TokenError> {
let from_balance = Self::read_balance(env, from);
if from_balance < amount {
return Err(TokenError::InsufficientBalance);
}
if from != to {
let to_balance = Self::read_balance(env, to);
Self::write_balance(env, from, from_balance - amount);
Self::write_balance(env, to, to_balance + amount);
}
Ok(())
}
fn internal_mint(
env: &Env,
admin_address: &Address,
to: &Address,
amount: i128,
) -> Result<(), TokenError> {
if amount <= 0 {
return Err(TokenError::InvalidAmount);
}
let max_supply = Self::read_max_supply(env);
let new_supply = Self::read_supply(env) + amount;
if new_supply > max_supply {
return Err(TokenError::MaxSupplyExceeded);
}
let new_balance = Self::read_balance(env, to) + amount;
Self::write_balance(env, to, new_balance);
Self::write_supply(env, new_supply);
events::emit_mint(env, admin_address, to, amount, new_balance, new_supply);
Ok(())
}
fn read_fee_config(env: &Env) -> Result<FeeConfig, TokenError> {
env.storage()
.instance()
.get(&DataKey::FeeConfig)
.ok_or(TokenError::FeeNotConfigured)
}
fn read_treasury(env: &Env) -> Result<Address, TokenError> {
env.storage()
.instance()
.get(&DataKey::Treasury)
.ok_or(TokenError::FeeNotConfigured)
}
fn write_fee_config(env: &Env, config: &FeeConfig) {
env.storage().instance().set(&DataKey::FeeConfig, config);
ttl::extend_instance_ttl(env);
}
fn write_treasury(env: &Env, treasury: &Address) {
env.storage().instance().set(&DataKey::Treasury, treasury);
ttl::extend_instance_ttl(env);
}
fn write_fee_exemption(env: &Env, address: &Address, exemption: &FeeExemption) {
env.storage()
.instance()
.set(&DataKey::FeeExemption(address.clone()), exemption);
ttl::extend_instance_ttl(env);
}
fn delete_fee_exemption(env: &Env, address: &Address) {
env.storage()
.instance()
.remove(&DataKey::FeeExemption(address.clone()));
ttl::extend_instance_ttl(env);
}
}
/// Lockup period state storage helpers (#719).
///
/// These back the upcoming `lock_tokens` / `withdraw_locked` entry points
/// (see `.kiro/specs/token-locking-vesting`); until those land they are
/// exercised only by the `lockup` unit-test module, so dead-code analysis is
/// silenced for library builds.
#[allow(dead_code)]
impl BcForgeToken {
fn read_lockup(env: &Env, user: &Address) -> Option<LockupState> {
let key = DataKey::Lockup(user.clone());
let state = env.storage().persistent().get::<_, LockupState>(&key);
if state.is_some() {
ttl::extend_storage_ttl_for_key(
env,
&key,
ttl::BALANCE_LIFETIME_THRESHOLD,
ttl::BALANCE_BUMP_AMOUNT,
);
}
state
}
fn write_lockup(env: &Env, user: &Address, state: &LockupState) {
let key = DataKey::Lockup(user.clone());
env.storage().persistent().set(&key, state);
ttl::extend_storage_ttl_for_key(
env,
&key,
ttl::BALANCE_LIFETIME_THRESHOLD,
ttl::BALANCE_BUMP_AMOUNT,
);
}
fn remove_lockup(env: &Env, user: &Address) {
env.storage()
.persistent()
.remove(&DataKey::Lockup(user.clone()));
}
fn get_locked_amount(env: &Env, user: &Address) -> i128 {
Self::read_lockup(env, user)
.map(|state| state.amount)
.unwrap_or(0)
}
/// Returns `true` while the user has a lock whose unlock timestamp is still
/// in the future. An expired lock no longer counts as locked, even though
/// its tokens stay in storage until explicitly withdrawn.
fn is_locked(env: &Env, user: &Address) -> bool {
match Self::read_lockup(env, user) {
Some(state) => env.ledger().timestamp() < state.unlock_timestamp,
None => false,
}
}
}
#[contractimpl]
impl BcForgeToken {
/// Initializes the token contract.
///
/// Sets the admin address, decimals, name, and symbol.
/// Emits the `init` event. Can only be called once.
///
/// @notice Initializes the token contract with the given admin, decimals, name, and symbol.
/// @dev This function can only be called once. Subsequent calls will revert with `AlreadyInitialized`.
/// @param env The Soroban environment.
/// @param admin_address The address to set as the contract admin.
/// @param decimal The number of decimal places for the token.
/// @param name The token name (e.g., "bc-forge Token").
/// @param symbol The token symbol (e.g., "SFG").
/// @return `Ok(())` on success, or `TokenError::AlreadyInitialized` if the contract is already initialized.
pub fn initialize(
env: Env,
admin_address: Address,
decimal: u32,
name: String,
symbol: String,
) -> Result<(), TokenError> {
// Ensure only the deployer can initialize the contract
env.current_contract_address().require_auth();
if admin::has_admin(&env) {
return Err(TokenError::AlreadyInitialized);
}
admin::set_admin(&env, &admin_address);
env.storage().instance().set(&DataKey::Decimals, &decimal);
env.storage().instance().set(&DataKey::Name, &name);
env.storage().instance().set(&DataKey::Symbol, &symbol);
Self::write_supply(&env, 0);
Self::write_max_supply(&env, i128::MAX);
events::emit_initialized(&env, &admin_address, decimal, &name, &symbol);
Ok(())
}
/// Returns the admin address.
///
/// @notice Returns the address of the contract admin.
/// @param env The Soroban environment.
/// @return The admin address.
pub fn admin(env: Env) -> Address {
Self::panic_on_err(&env, Self::ensure_initialized(&env));
admin::get_admin(&env)
}
/// Mints new tokens to a recipient.
///
/// @notice Mints `amount` tokens to the `to` address. Only authorized miners can call this function.
/// @dev Requires the caller to have the Minter role. Rate limits are checked before minting.
/// @param env The Soroban environment.
/// @param minter The address of the minter calling this function.
/// @param to The address to receive the minted tokens.
/// @param amount The amount of tokens to mint.
/// @return `Ok(())` on success, or an error if the minter is unauthorized, the contract is paused, or the amount is invalid.
pub fn mint(env: Env, minter: Address, to: Address, amount: i128) -> Result<(), TokenError> {
if amount <= 0 {
return Err(TokenError::InvalidAmount);
}
reentrancy_guard!(&env, "mint_guard", {
Self::ensure_initialized(&env)?;
Self::ensure_not_paused(&env)?;
bc_forge_admin::has_role!(&env, bc_forge_admin::Role::Minter, &minter);
if !crate::rate_limit::check_mint_rate_limit(&env, &minter, amount) {
return Err(TokenError::InvalidAmount);
}
Self::internal_mint(&env, &minter, &to, amount)
})
}
/// Mints new tokens to multiple recipients in a single call.
///
/// @notice Mints tokens to each recipient in the `recipients` list. Only authorized miners can call this function.
/// @dev Requires the caller to have the Minter role. Rate limits are checked per recipient. The total supply is updated atomically.
/// @param env The Soroban environment.
/// @param minter The address of the minter calling this function.
/// @param recipients A list of recipients with amounts to mint to each.
/// @return `Ok(())` on success, or an error if the minter is unauthorized, the contract is paused, or any amount is invalid.
pub fn batch_mint(
env: Env,
minter: Address,
recipients: Vec<Recipient>,
) -> Result<(), TokenError> {
reentrancy_guard!(&env, "batch_mint_guard", {
Self::ensure_initialized(&env)?;
Self::ensure_not_paused(&env)?;
// Check for any invalid amounts before requiring minter role
for i in 0..recipients.len() {
let recipient = recipients.get(i).expect("recipient should exist");
if recipient.amount <= 0 {
return Err(TokenError::InvalidAmount);
}
}
bc_forge_admin::has_role!(&env, bc_forge_admin::Role::Minter, &minter);
for i in 0..recipients.len() {
let recipient = recipients.get(i).expect("recipient should exist");
if !crate::rate_limit::check_mint_rate_limit(&env, &minter, recipient.amount) {
return Err(TokenError::InvalidAmount);
}
Self::internal_mint(&env, &minter, &recipient.to, recipient.amount)?;
}
Ok(())
})
}
/// Transfers tokens from a single sender to multiple recipients.
///
/// @notice Transfers `amount` tokens from `from` to each recipient in sequence. The caller must be the `from` address.
/// @dev Requires the caller to be the `from` address. Rate limits are checked per transfer. Total balance is verified before any transfers.
/// @param env The Soroban environment.
/// @param from The address sending the tokens.
/// @param recipients A list of (recipient, amount) pairs.
/// @return `Ok(())` on success, or an error if the balance is insufficient, any amount is invalid, or a rate limit is exceeded.
pub fn batch_transfer(
env: Env,
from: Address,
recipients: Vec<(Address, i128)>,
) -> Result<(), TokenError> {
Self::extend_instance_ttl_for_call(&env);
reentrancy_guard!(&env, "batch_transfer_guard", {
Self::ensure_initialized(&env)?;
Self::ensure_not_paused(&env)?;
from.require_auth();
let mut total: i128 = 0;
for i in 0..recipients.len() {
let (_, amount) = recipients.get(i).expect("recipient should exist");
if amount <= 0 {
return Err(TokenError::InvalidAmount);
}
total = match total.checked_add(amount) {
Some(total) => total,
None => return Err(TokenError::InvalidAmount),
};
}
if Self::read_balance(&env, &from) < total {
return Err(TokenError::InsufficientBalance);
}
for i in 0..recipients.len() {
let (to, amount) = recipients.get(i).expect("recipient should exist");
if !crate::rate_limit::check_transfer_rate_limit(&env, &from, amount) {
return Err(TokenError::InvalidAmount);
}
Self::move_balance(&env, &from, &to, amount)?;
events::emit_transfer(&env, &from, &to, amount);
}
Ok(())
})
}
/// Returns the current total token supply.
///
/// @notice Returns the total supply of tokens in circulation.
/// @param env The Soroban environment.
/// @return The total token supply.
pub fn supply(env: Env) -> i128 {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
Self::read_supply(&env)
}
/// Returns the maximum total supply cap.
///
/// @notice Returns the maximum supply that the token can ever have.
/// @param env The Soroban environment.
/// @return The maximum supply cap.
pub fn get_max_supply(env: Env) -> i128 {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
Self::read_max_supply(&env)
}
/// Sets the maximum total supply cap.
///
/// @notice Updates the maximum supply cap. Only the minter role holder can call this function.
/// @param env The Soroban environment.
/// @param caller The address calling this function (must have Minter role).
/// @param max_supply The new maximum supply cap.
/// @return `Ok(())` on success, or an error if the caller is unauthorized or the value is negative.
pub fn set_max_supply(env: Env, caller: Address, max_supply: i128) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
if max_supply < 0 {
return Err(TokenError::InvalidAmount);
}
admin::require_minter(&env, &caller);
Self::write_max_supply(&env, max_supply);
events::emit_max_supply_changed(&env, &caller, max_supply);
Ok(())
}
/// Transfers contract ownership to a new admin.
///
/// @notice Transfers the admin role to `new_admin`. Only the current admin can call this function.
/// @param env The Soroban environment.
/// @param new_admin The address to become the new admin.
/// @return `Ok(())` on success, or an error if the caller is not the current admin.
pub fn transfer_ownership(env: Env, new_admin: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
let current_admin = admin::get_admin(&env);
admin::require_admin(&env, ¤t_admin);
admin::set_admin(&env, &new_admin);
events::emit_ownership_transferred(&env, ¤t_admin, &new_admin);
Ok(())
}
/// Pauses the contract.
///
/// @notice Pauses all token operations. Only the admin (or SuperAdmin/Pauser role holder) can call this function.
/// @param env The Soroban environment.
/// @param caller The address requesting the pause; must be admin or hold the Pauser role.
/// @return `Ok(())` on success, or an error if the caller is unauthorized or already paused.
pub fn pause(env: Env, caller: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
let admin_address = admin::get_admin(&env);
if caller != admin_address && !admin::has_role(&env, admin::Role::Pauser, &caller) {
return Err(TokenError::ContractPaused);
}
if caller == admin_address {
admin_address.require_auth();
} else {
caller.require_auth();
}
if bc_forge_lifecycle::is_paused(&env) {
return Err(TokenError::AlreadyPaused);
}
bc_forge_lifecycle::set_paused(&env, true);
events::emit_paused(&env, &caller);
Ok(())
}
/// Unpauses the contract.
///
/// @notice Resumes all token operations. Only the admin (or SuperAdmin/Pauser role holder) can call this function.
/// @param env The Soroban environment.
/// @param caller The address requesting the unpause; must be admin or hold the Pauser role.
/// @return `Ok(())` on success, or an error if the caller is unauthorized or not paused.
pub fn unpause(env: Env, caller: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
let admin_address = admin::get_admin(&env);
if caller != admin_address && !admin::has_role(&env, admin::Role::Pauser, &caller) {
return Err(TokenError::ContractPaused);
}
if caller == admin_address {
admin_address.require_auth();
} else {
caller.require_auth();
}
if !bc_forge_lifecycle::is_paused(&env) {
return Err(TokenError::NotPaused);
}
bc_forge_lifecycle::set_paused(&env, false);
events::emit_unpaused(&env, &caller);
Ok(())
}
/// Upgrades the contract's executable to a new WASM hash.
///
/// @notice Upgrades the contract's executable code to `new_wasm_hash`. Only the SuperAdmin role holder can call this function.
/// @dev Gated to `Role::SuperAdmin` (or `Role::Admin`, which is a superset of every role) since a protocol upgrade can replace all contract logic.
/// @param env The Soroban environment.
/// @param upgrader The address calling the upgrade (must have SuperAdmin role).
/// @param new_wasm_hash The new WASM hash to deploy.
/// @return `Ok(())` on success, or an error if the caller is unauthorized.
pub fn upgrade(
env: Env,
upgrader: Address,
new_wasm_hash: BytesN<32>,
) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
admin::require_super_admin(&env, &upgrader);
events::emit_upgraded(&env, &upgrader, &new_wasm_hash);
env.deployer().update_current_contract_wasm(new_wasm_hash);
Ok(())
}
/// Pauses the contract as a specific caller.
///
/// @notice Pauses all token operations as the given caller. Used for governance or emergency scenarios where the caller differs from the admin.
/// @param env The Soroban environment.
/// @param caller The address requesting the pause.
/// @return `Ok(())` on success.
pub fn pause_as(env: Env, caller: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
if bc_forge_lifecycle::is_paused(&env) {
return Err(TokenError::AlreadyPaused);
}
bc_forge_lifecycle::pause(env.clone(), caller.clone());
events::emit_paused(&env, &caller);
Ok(())
}
/// Unpauses the contract as a specific caller.
///
/// @notice Resumes all token operations as the given caller. Used for governance or emergency scenarios where the caller differs from the admin.
/// @param env The Soroban environment.
/// @param caller The address requesting the unpause.
/// @return `Ok(())` on success.
pub fn unpause_as(env: Env, caller: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
if !bc_forge_lifecycle::is_paused(&env) {
return Err(TokenError::NotPaused);
}
bc_forge_lifecycle::unpause(env.clone(), caller.clone());
events::emit_unpaused(&env, &caller);
Ok(())
}
/// Sets the fee configuration.
///
/// @notice Configures the dynamic fee parameters for the token contract. Only the admin can call this function.
/// @dev Fee configuration affects all fee-based operations. Negative values for `base_fee` or `max_fee` are rejected.
/// @param env The Soroban environment.
/// @param caller The address calling this function (must have Admin role).
/// @param config The fee configuration to set.
/// @return `Ok(())` on success, or an error if the caller is unauthorized or the config contains negative values.
pub fn set_fee_config(env: Env, caller: Address, config: FeeConfig) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
admin::require_admin(&env, &caller);
if config.base_fee < 0 || config.max_fee < 0 {
return Err(TokenError::InvalidAmount);
}
Self::write_fee_config(&env, &config);
events::emit_fee_config_set(&env, &caller, &config);
Ok(())
}
/// Returns the current fee configuration.
///
/// @notice Returns the current fee configuration for the token contract.
/// @param env The Soroban environment.
/// @return The fee configuration, or `TokenError::FeeNotConfigured` if not set.
pub fn get_fee_config(env: Env) -> Result<FeeConfig, TokenError> {
Self::ensure_initialized(&env)?;
Self::read_fee_config(&env)
}
/// Sets the treasury address for collected fees.
///
/// @notice Configures the treasury address that receives collected fees. Only the admin can call this function.
/// @param env The Soroban environment.
/// @param caller The address calling this function (must have Admin role).
/// @param treasury The address to set as the treasury.
/// @return `Ok(())` on success, or an error if the caller is unauthorized.
pub fn set_treasury(env: Env, caller: Address, treasury: Address) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
admin::require_admin(&env, &caller);
Self::write_treasury(&env, &treasury);
events::emit_treasury_set(&env, &caller, &treasury);
Ok(())
}
/// Returns the current treasury address.
///
/// @notice Returns the treasury address for collected fees.
/// @param env The Soroban environment.
/// @return The treasury address, or `TokenError::FeeNotConfigured` if not set.
pub fn get_treasury(env: Env) -> Result<Address, TokenError> {
Self::ensure_initialized(&env)?;
Self::read_treasury(&env)
}
/// Sets a fee exemption for a specific address.
///
/// @notice Configures a fee exemption for the given address. Only the admin can call this function.
/// @param env The Soroban environment.
/// @param caller The address calling this function (must have Admin role).
/// @param address The address to exempt from fees.
/// @param exemption The fee exemption configuration.
/// @return `Ok(())` on success, or an error if the caller is unauthorized.
pub fn set_fee_exemption(
env: Env,
caller: Address,
address: Address,
exemption: FeeExemption,
) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
admin::require_admin(&env, &caller);
Self::write_fee_exemption(&env, &address, &exemption);
events::emit_fee_exemption_set(&env, &caller, &address, &exemption);
Ok(())
}
/// Removes a fee exemption for a specific address.
///
/// @notice Removes the fee exemption for the given address. Only the admin can call this function.
/// @param env The Soroban environment.
/// @param caller The address calling this function (must have Admin role).
/// @param address The address to remove the exemption from.
/// @return `Ok(())` on success, or an error if the caller is unauthorized.
pub fn remove_fee_exemption(
env: Env,
caller: Address,
address: Address,
) -> Result<(), TokenError> {
Self::ensure_initialized(&env)?;
admin::require_admin(&env, &caller);
Self::delete_fee_exemption(&env, &address);
events::emit_fee_exemption_removed(&env, &caller, &address);
Ok(())
}
/// Creates a multi-sig governance proposal (used to gate WASM upgrades).
///
/// @notice Creates an upgrade/governance proposal authored by `creator`.
/// @dev Thin wrapper over [`admin::create_proposal`]; creator must be an admin-pool member.
pub fn create_proposal(env: Env, creator: Address, description: String) -> u64 {
Self::ensure_initialized(&env).expect("token must be initialized");
admin::create_proposal(&env, creator, description)
}
/// Approves a multi-sig governance proposal.
///
/// @notice Records `admin`'s approval for `proposal_id`.
/// @dev Thin wrapper over [`admin::approve_proposal`].
pub fn approve_proposal(env: Env, admin: Address, proposal_id: u64) {
Self::ensure_initialized(&env).expect("token must be initialized");
admin::approve_proposal(&env, admin, proposal_id);
}
/// Returns whether a governance proposal has met its approval quorum.
pub fn is_proposal_ready(env: Env, proposal_id: u64) -> bool {
Self::ensure_initialized(&env).expect("token must be initialized");
admin::is_proposal_ready(&env, proposal_id)
}
/// Configures the multi-sig admin pool and approval threshold for upgrades.
pub fn set_admin_pool(env: Env, pool: Vec<Address>, threshold: u32) {
Self::ensure_initialized(&env).expect("token must be initialized");
admin::set_admin_pool(&env, pool, threshold);
}
/// Executes a quorum-approved WASM upgrade on this token contract.
///
/// @notice Applies `wasm_hash` after the referenced proposal meets quorum.
/// @dev Delegates to [`admin::execute_upgrade`].
pub fn execute_upgrade(
env: Env,
executor: Address,
proposal_id: u64,
wasm_hash: BytesN<32>,
) -> Result<(), admin::AdminError> {
Self::ensure_initialized(&env).expect("token must be initialized");
admin::execute_upgrade(&env, executor, proposal_id, wasm_hash)
}
}
#[contractimpl]
impl TokenInterface for BcForgeToken {
/// Returns the remaining allowance that `spender` is allowed to spend on behalf of `from`.
///
/// @inheritdoc TokenInterface
fn allowance(env: Env, from: Address, spender: Address) -> i128 {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
Self::allowance_amount(&env, &from, &spender)
}
/// Approves `spender` to spend `amount` tokens on behalf of `from`.
///
/// @notice Sets the allowance of `spender` over `from`'s tokens to `amount`. Emits an `approve` event.
/// @dev Requires `from` to authenticate the call. Negative amounts are rejected.
/// @param env The Soroban environment.
/// @param from The token owner address.
/// @param spender The address to approve spending.
/// @param amount The amount to approve.
/// @param exp The ledger until which the allowance is valid (0 = unlimited).
/// @return `()`
fn approve(env: Env, from: Address, spender: Address, amount: i128, exp: u32) {
Self::extend_instance_ttl_for_call(&env);
reentrancy_guard!(&env, "approve_guard", {
Self::panic_on_err(&env, Self::ensure_initialized(&env));
from.require_auth();
if amount < 0 {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
Self::write_allowance(&env, &from, &spender, amount, exp);
events::emit_approve(&env, &from, &spender, amount, exp);
});
}
/// Returns the token balance of the given address.
///
/// @notice Returns the balance of tokens held by `id`.
/// @param env The Soroban environment.
/// @param id The address to query the balance for.
/// @return The token balance of the given address.
fn balance(env: Env, id: Address) -> i128 {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
Self::read_balance(&env, &id)
}
/// Transfers tokens from `from` to `to`.
///
/// @notice Transfers `amount` tokens from `from` to `to`. Requires `from` to authenticate the call.
/// @dev Rejects with [`TokenError::ContractPaused`] while the lifecycle module reports the
/// contract paused. Checks rate limits before transferring. Emits a `transfer` event on success.
/// @param env The Soroban environment.
/// @param from The sender address.
/// @param to The recipient address.
/// @param amount The amount to transfer.
fn transfer(env: Env, from: Address, to: Address, amount: i128) {
Self::extend_instance_ttl_for_call(&env);
reentrancy_guard!(&env, "transfer_guard", {
Self::panic_on_err(&env, Self::ensure_initialized(&env));
// #762 – tie pause state into token transfers via the lifecycle modifier.
// A contract-error panic is required here rather than the lifecycle crate's
// plain `require_not_paused` panic: a non-contract panic unwinds through the
// reentrancy guard's Drop, which performs storage writes mid-unwind and masks
// the failure as Context(InvalidAction) for try_ callers.
Self::panic_on_err(&env, Self::ensure_not_paused(&env));
from.require_auth();
if amount <= 0 {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
if !crate::rate_limit::check_transfer_rate_limit(&env, &from, amount) {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
Self::panic_on_err(&env, Self::move_balance(&env, &from, &to, amount));
events::emit_transfer(&env, &from, &to, amount);
});
}
/// Transfers tokens from `from` to `to` on behalf of `spender`.
///
/// @notice Transfers `amount` tokens from `from` to `to` using the allowance mechanism. Requires `spender` to authenticate the call.
/// @dev Rejects with [`TokenError::ContractPaused`] while paused. Checks rate limits and
/// sufficient allowance before transferring. Deducts the allowance after a successful
/// transfer. Emits a `transfer_from` event.
/// @param env The Soroban environment.
/// @param spender The address calling the function (must have sufficient allowance).
/// @param from The address to transfer tokens from.
/// @param to The recipient address.
/// @param amount The amount to transfer.
fn transfer_from(env: Env, spender: Address, from: Address, to: Address, amount: i128) {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
// #762 – tie pause state into token transfers via the lifecycle modifier.
// See the comment in `transfer` for why this is not `require_not_paused`.
Self::panic_on_err(&env, Self::ensure_not_paused(&env));
spender.require_auth();
if amount <= 0 {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
if !crate::rate_limit::check_transfer_from_rate_limit(&env, &spender, amount) {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
let allowance = Self::allowance_amount(&env, &from, &spender);
if allowance < amount {
soroban_sdk::panic_with_error!(&env, TokenError::InsufficientAllowance);
}
let allowance_data = Self::read_allowance_data(&env, &from, &spender);
Self::panic_on_err(&env, Self::move_balance(&env, &from, &to, amount));
Self::write_allowance(
&env,
&from,
&spender,
allowance - amount,
allowance_data.expiration_ledger,
);
events::emit_transfer_from(&env, &spender, &from, &to, amount, allowance - amount);
}
/// Burns tokens from the caller's own balance.
///
/// @notice Permanently removes `amount` tokens from `from`'s balance, reducing total supply by the same amount.
/// @dev Checks rate limits and sufficient balance before burning. Emits a `burn` event.
/// @param env The Soroban environment.
/// @param from The address whose tokens are burned.
/// @param amount The amount to burn.
fn burn(env: Env, from: Address, amount: i128) {
Self::extend_instance_ttl_for_call(&env);
Self::panic_on_err(&env, Self::ensure_initialized(&env));
Self::panic_on_err(&env, Self::ensure_not_paused(&env));
from.require_auth();
if amount <= 0 {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
// Check rate limits for burn operation
if !crate::rate_limit::check_burn_rate_limit(&env, &from, amount) {
soroban_sdk::panic_with_error!(&env, TokenError::InvalidAmount);
}
let balance = Self::read_balance(&env, &from);
if balance < amount {