-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathlib.rs
More file actions
3221 lines (2847 loc) · 114 KB
/
Copy pathlib.rs
File metadata and controls
3221 lines (2847 loc) · 114 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
#![no_std]
pub mod quote_view_errors;
use soroban_sdk::{contract, contracterror, contractimpl, contracttype, Address, Env, String, Vec};
pub mod events;
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
/// Contract error variants.
///
/// # Stability and Ordering
///
/// **IMPORTANT**: New error variants MUST be appended to the end of this enum and NEVER
/// inserted mid-enum. The numeric discriminant values are part of the contract's ABI and
/// are exposed to clients, indexers, and monitoring tools.
///
/// ## Consequences of Reordering
///
/// If a variant is inserted mid-enum or existing variants are reordered:
/// - Existing clients that match on numeric error codes will break
/// - Indexers and monitoring tools will misinterpret error types
/// - Historical error logs will become inconsistent with current definitions
/// - Contract upgrades will introduce silent behavioral changes
///
/// ## Safe Extension Pattern
///
/// ✅ **Correct**: Append new variants at the end
/// ```rust,ignore
/// pub enum ContractError {
/// AlreadyRegistered = 1,
/// NotRegistered = 2,
/// // ... existing variants ...
/// InvalidHandleCharacter = 14,
/// NewError = 15, // ✅ Safe: appended at end
/// }
/// ```
///
/// ❌ **Incorrect**: Insert mid-enum
/// ```rust,ignore
/// pub enum ContractError {
/// AlreadyRegistered = 1,
/// NewError = 2, // ❌ BREAKS ABI: shifts all subsequent variants
/// NotRegistered = 3, // was 2, now 3 - breaks existing clients
/// // ...
/// }
/// ```
pub enum ContractError {
AlreadyRegistered = 1,
NotRegistered = 2,
Overflow = 3,
InsufficientPayment = 4,
KeyPriceNotSet = 5,
NotPositiveAmount = 6,
FeeConfigNotSet = 7,
InvalidFeeConfig = 8,
InsufficientBalance = 9,
SellUnderflow = 10,
ProtocolFeeExceedsCap = 11,
HandleTooShort = 12,
HandleTooLong = 13,
InvalidHandleCharacter = 14,
ZeroAddress = 15,
SlippageExceeded = 16,
ProtocolPaused = 17,
Unauthorized = 18,
NoDividendClaimable = 19,
ZeroDistributionAmount = 20,
NoKeyHolders = 21,
AllocationLocked = 22,
AlreadyClaimed = 23,
SupplyCapExceeded = 24,
InsufficientSupply = 25,
SelfTransfer = 26,
ZeroTransferAmount = 27,
InsufficientTreasuryBalance = 28,
BatchClaimExceedsLimit = 29,
InvalidCoCreatorShare = 30,
WhitelistOnly = 31,
WhitelistTooLarge = 32,
}
pub mod fee {
use crate::ContractError;
use soroban_sdk::contracttype;
/// Basis points per 100% (10000 = 100%).
pub const BPS_MAX: u32 = 10_000;
/// Maximum safe amount to prevent overflow in fee calculations.
pub const MAX_SAFE_AMOUNT: i128 = i128::MAX / BPS_MAX as i128;
/// Maximum protocol share when configuring fees via [`assert_valid_fee_bps`].
///
/// Caps the on-chain configured protocol take at 50% so fee settings stay within
/// expected economic bounds before they affect market logic.
pub const PROTOCOL_BPS_MAX: u32 = 5_000;
#[derive(Clone, Eq, PartialEq)]
#[contracttype]
pub struct FeeConfig {
pub creator_bps: u32,
pub protocol_bps: u32,
}
/// Validates creator and protocol basis points for storage and fee-setting entrypoints.
pub fn validate_fee_bps(creator_bps: u32, protocol_bps: u32) -> bool {
let Some(sum) = creator_bps.checked_add(protocol_bps) else {
return false;
};
if sum != BPS_MAX {
return false;
}
if protocol_bps > PROTOCOL_BPS_MAX {
return false;
}
true
}
/// Shared guard for fee config updates that need structured contract errors.
pub fn assert_valid_fee_bps(creator_bps: u32, protocol_bps: u32) -> Result<(), ContractError> {
let Some(sum) = creator_bps.checked_add(protocol_bps) else {
return Err(ContractError::InvalidFeeConfig);
};
if sum != BPS_MAX {
return Err(ContractError::InvalidFeeConfig);
}
if protocol_bps > PROTOCOL_BPS_MAX {
return Err(ContractError::ProtocolFeeExceedsCap);
}
Ok(())
}
/// Computes the fee split for a given total amount.
///
/// Returns `(creator_amount, protocol_amount)`. Remainder from integer division
/// is assigned to the creator. Ensures creator_amount + protocol_amount == total.
pub fn compute_fee_split(total: i128, _creator_bps: u32, protocol_bps: u32) -> (i128, i128) {
if total <= 0 {
return (0, 0);
}
let protocol_amount = (total * protocol_bps as i128) / BPS_MAX as i128;
let creator_amount = total - protocol_amount;
(creator_amount, protocol_amount)
}
/// Safely applies a percentage-based fee to an amount.
///
/// Returns `None` if the multiplication overflows. Rounding is performed via
/// floor division towards zero.
pub fn apply_percentage_fee(amount: i128, bps: u32) -> Option<i128> {
if amount <= 0 {
return Some(0);
}
checked_div_i128(amount.checked_mul(bps as i128)?, BPS_MAX as i128)
}
/// Computes the net buyback cost after deducting the protocol fee.
///
/// Returns `None` if the fee computation overflows or the subtraction overflows.
/// The result is `gross_price - protocol_fee` where `protocol_fee` is calculated
/// via `apply_percentage_fee`. This mirrors the fee logic used for regular buys.
pub fn compute_net_buyback_cost(gross_price: i128, protocol_fee_bps: u32) -> Option<i128> {
let protocol_fee = apply_percentage_fee(gross_price, protocol_fee_bps)?;
gross_price.checked_sub(protocol_fee)
}
///
/// Returns `None` if the fee computation or addition overflows. This helper
/// exists so the buyback path shares the same bps math used in regular buys
/// instead of reimplementing the protocol fee arithmetic inline.
pub fn compute_buyback_cost(gross_price: i128, protocol_fee_bps: u32) -> Option<i128> {
let protocol_fee = apply_percentage_fee(gross_price, protocol_fee_bps)?;
gross_price.checked_add(protocol_fee)
}
/// Computes the net buyback cost after deducting the protocol fee.
///
/// Takes the gross buyback price and subtracts the protocol fee portion,
/// returning the net amount that remains after fee deduction. Uses the same
/// `apply_percentage_fee` helper as the regular buy and buyback fee paths
/// so the bps arithmetic stays consistent across the contract.
///
/// Returns `None` if the fee computation or subtraction would underflow.
///
/// Computes the fee split safely, returning `None` if multiplication or subtraction overflows.
pub fn checked_compute_fee_split(
total: i128,
_creator_bps: u32,
protocol_bps: u32,
) -> Option<(i128, i128)> {
if total <= 0 {
return Some((0, 0));
}
let protocol_amount = apply_percentage_fee(total, protocol_bps)?;
let creator_amount = checked_sub_i128(total, protocol_amount)?;
Some((creator_amount, protocol_amount))
}
/// Splits `total` into `(remainder, shared_amount)` by basis points.
///
/// Remainder from integer division stays with the primary recipient so the
/// two outputs always sum to `total`.
pub fn checked_split_bps_amount(total: i128, share_bps: u32) -> Option<(i128, i128)> {
if total <= 0 {
return Some((0, 0));
}
let shared_amount = apply_percentage_fee(total, share_bps)?;
let remainder = checked_sub_i128(total, shared_amount)?;
Some((remainder, shared_amount))
}
/// Performs checked integer multiplication for quote math helpers.
pub fn checked_mul_i128(a: i128, b: i128) -> Option<i128> {
a.checked_mul(b)
}
/// Performs checked integer division for quote math helpers.
pub fn checked_div_i128(dividend: i128, divisor: i128) -> Option<i128> {
if divisor == 0 {
return None;
}
dividend.checked_div(divisor)
}
/// Performs checked integer subtraction for quote math helpers.
pub fn checked_sub_i128(left: i128, right: i128) -> Option<i128> {
left.checked_sub(right)
}
/// Performs checked integer addition for quote math helpers.
pub fn checked_add_i128(left: i128, right: i128) -> Option<i128> {
left.checked_add(right)
}
/// Computes the checked sum of creator and protocol fee components.
///
/// Returns `None` if the addition would overflow. Use this helper wherever
/// fee components are combined before being compared against a price or total,
/// to keep the overflow guard consistent across buy and sell quote paths.
///
/// # Naming convention
///
/// Quote helpers in this module follow a `checked_*` prefix convention:
/// - `checked_*` functions return `Option<T>` and propagate `None` on overflow.
/// - `compute_*` functions return the result directly (may panic on overflow in
/// debug builds; use only where inputs are already validated).
/// - `apply_*` functions apply a rate or percentage to a single amount.
///
/// `checked_fee_sum` belongs to the `checked_*` family: it is the canonical
/// helper for summing two fee components before they are used in total-amount
/// arithmetic, replacing ad-hoc inline `checked_add` calls at each call site.
pub fn checked_fee_sum(creator_fee: i128, protocol_fee: i128) -> Option<i128> {
creator_fee.checked_add(protocol_fee)
}
/// Safely accumulates a value into an accumulator, returning an error on overflow.
///
/// This helper is used in quote accumulator paths (e.g., dividend distribution) where
/// adding a per-key-net amount to the current accumulator must not overflow.
/// Unlike `checked_fee_sum` which returns `Option<T>`, this returns a `ContractError`
/// for use at call sites that need structured error handling.
///
/// # Motivation
///
/// Accumulator updates happen during dividend distribution and similar paths.
/// The pattern `accumulator.checked_add(delta).ok_or(ContractError::Overflow)?`
/// appears repeatedly. This helper centralizes the pattern and makes overflow
/// handling explicit.
///
/// # Example
///
/// ```ignore
/// let new_accum = fee::checked_accumulate(current_accumulator, per_key_net)?;
/// env.storage().persistent().set(&acc_key, &new_accum);
/// ```
pub fn checked_accumulate(current: i128, delta: i128) -> Result<i128, ContractError> {
current.checked_add(delta).ok_or(ContractError::Overflow)
}
}
pub mod constants {
use super::DataKey;
use soroban_sdk::Address;
pub mod storage {
use super::{creator_key, key_balance_key, DataKey};
use soroban_sdk::Address;
pub const FEE_CONFIG: DataKey = DataKey::FeeConfig;
pub const KEY_PRICE: DataKey = DataKey::KeyPrice;
pub const TREASURY_ADDRESS: DataKey = DataKey::TreasuryAddress;
pub const ADMIN_ADDRESS: DataKey = DataKey::AdminAddress;
pub const PROTOCOL_FEE_RECIPIENT: DataKey = DataKey::ProtocolFeeRecipient;
pub const PROTOCOL_FEE_RECIPIENT_BALANCE: DataKey = DataKey::ProtocolFeeRecipientBalance;
pub const PROTOCOL_STATE_VERSION: DataKey = DataKey::ProtocolStateVersion;
pub const PAUSED: DataKey = DataKey::Paused;
pub const CURVE_SLOPE: DataKey = DataKey::CurveSlope;
pub const TREASURY_BALANCE: DataKey = DataKey::TreasuryBalance;
pub fn curve_preset(creator: &Address) -> DataKey {
DataKey::CurvePreset(creator.clone())
}
pub fn creator_fee_balance(creator: &Address) -> DataKey {
DataKey::CreatorFeeBalance(creator.clone())
}
pub fn co_creator(creator: &Address) -> DataKey {
DataKey::CoCreator(creator.clone())
}
pub fn co_creator_fee_balance(creator: &Address, co_creator: &Address) -> DataKey {
DataKey::CoCreatorFeeBalance(creator.clone(), co_creator.clone())
}
pub fn whitelist(creator: &Address) -> DataKey {
DataKey::Whitelist(creator.clone())
}
pub fn creator(creator: &Address) -> DataKey {
creator_key(creator)
}
pub fn key_balance(creator: &Address, holder: &Address) -> DataKey {
key_balance_key(creator, holder)
}
pub fn dividend_accumulator(creator: &Address) -> DataKey {
DataKey::DividendPerKeyAccumulated(creator.clone())
}
pub fn holder_dividend_checkpoint(creator: &Address, holder: &Address) -> DataKey {
DataKey::HolderDividendCheckpoint(creator.clone(), holder.clone())
}
pub fn holder_dividend_pending(creator: &Address, holder: &Address) -> DataKey {
DataKey::HolderDividendPending(creator.clone(), holder.clone())
}
pub fn locked_allocation(creator: &Address) -> DataKey {
DataKey::LockedAllocation(creator.clone())
}
pub fn max_supply(creator: &Address) -> DataKey {
DataKey::MaxSupply(creator.clone())
}
}
fn creator_key(creator: &Address) -> DataKey {
DataKey::Creator(creator.clone())
}
fn key_balance_key(creator: &Address, holder: &Address) -> DataKey {
DataKey::KeyBalance(creator.clone(), holder.clone())
}
pub mod creator_reads {
pub const DETAILS: &str = "get_creator_details";
pub const FEE_BPS: &str = "get_creator_fee_bps";
pub const FEE_CONFIG: &str = "get_creator_fee_config";
pub const FEE_RECIPIENT: &str = "get_creator_fee_recipient";
pub const FEE_RECIPIENT_BALANCE: &str = "get_creator_fee_balance";
pub const CO_CREATOR: &str = "get_co_creator";
pub const CO_CREATOR_FEE_BALANCE: &str = "get_co_creator_fee_balance";
pub const HOLDER_KEY_COUNT: &str = "get_holder_key_count";
pub const PROFILE: &str = "get_creator";
pub const SUPPLY: &str = "get_creator_supply";
pub const TREASURY_SHARE: &str = "get_creator_treasury_share";
pub const NAME: &str = "get_key_name";
pub const SYMBOL: &str = "get_key_symbol";
}
/// Default values for fee bounds used across validation paths and test fixtures.
///
/// These constants represent the canonical starting point for a fee configuration.
/// Keeping them here ensures a single source of truth: any adjustment to the
/// default split only needs to happen in one place.
pub mod fee_bounds {
/// Default creator share in basis points (90%).
pub const DEFAULT_CREATOR_BPS: u32 = 9_000;
/// Default protocol share in basis points (10%).
pub const DEFAULT_PROTOCOL_BPS: u32 = 1_000;
}
}
/// Stable, non-optional view of the protocol fee configuration.
///
/// Returned by [`CreatorKeysContract::get_protocol_fee_view`] for indexer-friendly consumption.
/// When `is_configured` is `false`, both bps fields are `0` and no fee config has been stored.
#[derive(Clone)]
#[contracttype]
pub struct ProtocolFeeView {
pub creator_bps: u32,
pub protocol_bps: u32,
pub is_configured: bool,
}
/// Stable, non-optional view of creator details.
///
/// Returned by [`CreatorKeysContract::get_creator_details`] and
/// [`CreatorKeysContract::get_creators_batch`] for indexer-friendly consumption.
/// When `is_registered` is `false`, default values are returned for all other fields,
/// including `registered_at: 0`.
///
/// # Field Stability
///
/// Fields are append-only. Do not reorder existing fields; the Soroban XDR encoder
/// serialises struct fields in declaration order and downstream indexers rely on
/// positional stability.
#[derive(Clone)]
#[contracttype]
pub struct CreatorDetailsView {
pub creator: Address,
pub handle: String,
pub supply: u32,
pub is_registered: bool,
/// Ledger sequence number at the time the creator registered.
///
/// Set to `env.ledger().sequence()` inside [`CreatorKeysContract::register_creator`].
/// Returns `0` for unregistered addresses so callers never receive an `Option`.
/// Clients can use this field to sort a marketplace grid chronologically without
/// maintaining a separate off-chain index.
pub registered_at: u32,
}
/// Stable, non-optional view of a creator's fee configuration.
///
/// Returned by [`CreatorKeysContract::get_creator_fee_config`] for indexer-friendly consumption.
/// When `is_registered` is `false`, the creator does not exist and both bps fields are `0`.
/// When `is_configured` is `false`, the creator exists but no global fee config has been set.
#[derive(Clone)]
#[contracttype]
pub struct CreatorFeeView {
pub creator_bps: u32,
pub protocol_bps: u32,
pub is_registered: bool,
pub is_configured: bool,
}
/// Stable, non-optional view of a holder's key count for a creator.
///
/// Returned by [`CreatorKeysContract::get_holder_key_count`] for indexer-friendly consumption.
/// When `creator_exists` is `false`, the creator is not registered and `key_count` is `0`.
/// When `creator_exists` is `true` but the holder has no keys, `key_count` is `0`.
#[derive(Clone)]
#[contracttype]
pub struct HolderKeyCountView {
pub creator: Address,
pub holder: Address,
pub key_count: u32,
pub creator_exists: bool,
}
/// Stable, non-optional view of a buy or sell quote.
///
/// Returned by [`CreatorKeysContract::get_buy_quote`] and [`CreatorKeysContract::get_sell_quote`].
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct QuoteResponse {
pub price: i128,
pub creator_fee: i128,
pub protocol_fee: i128,
pub total_amount: i128,
}
/// Shared result type for read-only quote methods.
pub type QuoteViewResult = Result<QuoteResponse, ContractError>;
/// Initial protocol state version for read-only consumers.
///
/// The actual version is stored in storage and incremented on config updates.
/// This constant is only the starting value.
pub const PROTOCOL_STATE_VERSION_INITIAL: u32 = 1;
/// Decimal precision used by creator key values.
///
/// Matches the standard Soroban token decimal convention (7 decimal places).
pub const KEY_DECIMALS: u32 = 7;
/// TTL extension for creator storage entries on each trade.
///
/// This value is added to the TTL of all creator-related storage keys
/// (creator config, supply, holder map, fee config) after every successful
/// buy or sell operation to prevent active creator state from expiring.
pub const CREATOR_TTL_LEDGERS: u32 = 6311520; // ~2 years at 5s per ledger
pub const HANDLE_LEN_MIN: u32 = 3;
pub const HANDLE_LEN_MAX: u32 = 32;
pub const MAX_WHITELIST_SIZE: u32 = 500;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[contracttype]
pub enum CurvePreset {
Linear = 0,
Quadratic = 1,
Flat = 2,
}
/// Canonical storage key schema for persistent protocol state.
///
/// For quote-related key usage and invariants, see
/// [`docs/quote-storage-keys.md`](../../docs/quote-storage-keys.md).
#[derive(Clone)]
#[contracttype]
pub enum DataKey {
Creator(Address),
FeeConfig,
KeyPrice,
KeyBalance(Address, Address),
TreasuryAddress,
AdminAddress,
ProtocolFeeRecipient,
ProtocolFeeRecipientBalance,
CreatorFeeBalance(Address),
ProtocolStateVersion,
Paused,
DividendPerKeyAccumulated(Address),
HolderDividendCheckpoint(Address, Address),
HolderDividendPending(Address, Address),
LockedAllocation(Address),
MaxSupply(Address),
CurveSlope,
CurvePreset(Address),
TreasuryBalance,
CoCreator(Address),
CoCreatorFeeBalance(Address, Address),
Whitelist(Address),
}
/// Time-locked key allocation for creator self-vesting.
///
/// When a creator registers, they may optionally lock a portion of keys
/// that cannot be claimed until a specified ledger height is reached.
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct LockedAllocation {
pub amount: u32,
pub unlock_ledger: u32,
pub claimed: bool,
}
/// Optional immutable collaborator split configured at creator registration.
///
/// `share_bps` is the co-creator's share of the creator fee, not of the full
/// trade price. It must be in the inclusive range `1..=9999`.
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct CoCreatorConfig {
pub address: Address,
pub share_bps: u32,
}
/// Required creator identity fields for registration.
///
/// Grouping these fields keeps the public contract entrypoint under Clippy's
/// argument-count threshold without changing validation or storage behavior for
/// any registration option.
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct RegisterCreatorParams {
pub creator: Address,
pub handle: String,
}
/// Optional whitelist window configured at creator registration.
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct WhitelistConfig {
pub addresses: Vec<Address>,
pub window_ledgers: u32,
}
/// Read-only status for a creator's whitelist window.
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct WhitelistStatus {
pub active: bool,
pub expires_at_ledger: u32,
pub remaining_ledgers: u32,
}
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct CreatorProfile {
pub creator: Address,
pub handle: String,
pub supply: u32,
pub holder_count: u32,
pub fee_recipient: Address,
/// Ledger sequence number captured at registration time via `env.ledger().sequence()`.
///
/// Stored as the last field so existing serialised profiles written before this
/// field was added deserialise correctly — the Soroban persistent storage layer
/// reads structs by field index, so appending is the only safe extension pattern.
pub registered_at: u32,
}
#[derive(Clone, Debug, PartialEq)]
#[contracttype]
pub struct ClaimResult {
pub creator: Address,
pub amount_claimed: i128,
}
fn validate_whitelist_config(config: &WhitelistConfig) -> Result<(), ContractError> {
if config.addresses.len() > MAX_WHITELIST_SIZE {
return Err(ContractError::WhitelistTooLarge);
}
Ok(())
}
fn read_whitelist_config(env: &Env, creator: &Address) -> Option<WhitelistConfig> {
env.storage()
.persistent()
.get::<DataKey, WhitelistConfig>(&constants::storage::whitelist(creator))
}
fn whitelist_status(env: &Env, profile: &CreatorProfile) -> WhitelistStatus {
let Some(config) = read_whitelist_config(env, &profile.creator) else {
return WhitelistStatus {
active: false,
expires_at_ledger: 0,
remaining_ledgers: 0,
};
};
let expires_at_ledger = profile.registered_at.saturating_add(config.window_ledgers);
let current_ledger = env.ledger().sequence();
let remaining_ledgers = expires_at_ledger.saturating_sub(current_ledger);
WhitelistStatus {
active: remaining_ledgers > 0,
expires_at_ledger,
remaining_ledgers,
}
}
fn assert_whitelist_allows_buy(
env: &Env,
profile: &CreatorProfile,
buyer: &Address,
) -> Result<(), ContractError> {
let status = whitelist_status(env, profile);
if !status.active {
return Ok(());
}
let Some(config) = read_whitelist_config(env, &profile.creator) else {
return Ok(());
};
for address in config.addresses.iter() {
if address == *buyer {
return Ok(());
}
}
Err(ContractError::WhitelistOnly)
}
/// Reads a creator profile from storage, returning `None` for unregistered creators.
///
/// Use this helper wherever repeated creator read logic is needed to keep
/// missing-creator behavior consistent across the contract.
pub fn read_creator_profile(env: &Env, creator: &Address) -> Option<CreatorProfile> {
let key = constants::storage::creator(creator);
env.storage()
.persistent()
.get::<DataKey, CreatorProfile>(&key)
}
/// Reads a registered creator profile, returning an error when the creator is missing.
///
/// Use this helper for methods that require an existing creator and should return
/// a structured contract error instead of a default value.
pub fn read_registered_creator_profile(
env: &Env,
creator: &Address,
) -> Result<CreatorProfile, ContractError> {
read_creator_profile(env, creator).ok_or(ContractError::NotRegistered)
}
/// Reads the key balance (supply) for a creator, returning `0` for unregistered creators.
///
/// Use this helper wherever repeated key balance read logic is needed to keep
/// missing-balance behavior consistent across the contract.
pub fn read_key_balance(env: &Env, creator: &Address) -> u32 {
read_creator_profile(env, creator)
.map(|p| p.supply)
.unwrap_or(0)
}
/// Reads an empty string for use as a default in read-only view methods.
///
/// Use this helper wherever an empty string is needed to maintain consistency
/// and reduce duplication of string allocation logic.
pub fn read_none_string(env: &Env) -> String {
String::from_str(env, "")
}
/// Reads the handle for a creator, returning an empty string for unregistered creators.
///
/// Use this helper wherever repeated handle read logic is needed to maintain
/// missing-handle behavior consistency across the contract.
pub fn read_creator_handle(env: &Env, creator: &Address) -> String {
read_creator_profile(env, creator)
.map(|p| p.handle)
.unwrap_or_else(|| read_none_string(env))
}
/// Reads accrued creator fee balance for a creator, returning `0` when none is stored.
pub fn read_creator_fee_recipient_balance(env: &Env, creator: &Address) -> i128 {
let key = constants::storage::creator_fee_balance(creator);
env.storage().persistent().get(&key).unwrap_or(0)
}
/// Credits `amount` to the creator fee recipient balance for `creator`.
fn credit_creator_fee_recipient_balance(
env: &Env,
creator: &Address,
amount: i128,
) -> Result<(), ContractError> {
if amount <= 0 {
return Ok(());
}
let key = constants::storage::creator_fee_balance(creator);
let current = read_creator_fee_recipient_balance(env, creator);
let updated = current.checked_add(amount).ok_or(ContractError::Overflow)?;
env.storage().persistent().set(&key, &updated);
Ok(())
}
fn read_co_creator_config(env: &Env, creator: &Address) -> Option<CoCreatorConfig> {
let key = constants::storage::co_creator(creator);
env.storage()
.persistent()
.get::<DataKey, CoCreatorConfig>(&key)
}
fn validate_co_creator_config(env: &Env, config: &CoCreatorConfig) -> Result<(), ContractError> {
validate_non_zero_address(env, &config.address)?;
if !(1..fee::BPS_MAX).contains(&config.share_bps) {
return Err(ContractError::InvalidCoCreatorShare);
}
Ok(())
}
/// Reads accrued fee balance for a creator's configured co-creator.
pub fn read_co_creator_fee_balance(env: &Env, creator: &Address, co_creator: &Address) -> i128 {
let key = constants::storage::co_creator_fee_balance(creator, co_creator);
env.storage().persistent().get(&key).unwrap_or(0)
}
fn credit_co_creator_fee_balance(
env: &Env,
creator: &Address,
co_creator: &Address,
amount: i128,
) -> Result<(), ContractError> {
if amount <= 0 {
return Ok(());
}
let key = constants::storage::co_creator_fee_balance(creator, co_creator);
let current = read_co_creator_fee_balance(env, creator, co_creator);
let updated = current.checked_add(amount).ok_or(ContractError::Overflow)?;
env.storage().persistent().set(&key, &updated);
Ok(())
}
fn credit_creator_fee(env: &Env, creator: &Address, amount: i128) -> Result<(), ContractError> {
if amount <= 0 {
return Ok(());
}
let Some(config) = read_co_creator_config(env, creator) else {
return credit_creator_fee_recipient_balance(env, creator, amount);
};
let co_creator = config.address;
let (creator_recipient_amount, co_creator_amount) =
fee::checked_split_bps_amount(amount, config.share_bps).ok_or(ContractError::Overflow)?;
credit_creator_fee_recipient_balance(env, creator, creator_recipient_amount)?;
credit_co_creator_fee_balance(env, creator, &co_creator, co_creator_amount)?;
if co_creator_amount > 0 {
env.events().publish(
events::co_creator_fee_earned_topics(creator, &co_creator),
events::CoCreatorFeeEarned {
creator_id: creator.clone(),
co_creator,
amount: co_creator_amount,
ledger: env.ledger().sequence(),
},
);
}
Ok(())
}
fn is_valid_handle_byte(byte: u8) -> bool {
byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'
}
fn validate_creator_handle(handle: &String) -> Result<(), ContractError> {
let len = handle.len();
if len < HANDLE_LEN_MIN {
return Err(ContractError::HandleTooShort);
}
if len > HANDLE_LEN_MAX {
return Err(ContractError::HandleTooLong);
}
let mut bytes = [0u8; HANDLE_LEN_MAX as usize];
handle.copy_into_slice(&mut bytes[..len as usize]);
if bytes[..len as usize]
.iter()
.any(|byte| !is_valid_handle_byte(*byte))
{
return Err(ContractError::InvalidHandleCharacter);
}
Ok(())
}
fn is_paused(env: &Env) -> bool {
env.storage()
.persistent()
.get::<DataKey, bool>(&constants::storage::PAUSED)
.unwrap_or(false)
}
fn assert_not_paused(env: &Env) -> Result<(), ContractError> {
if is_paused(env) {
return Err(ContractError::ProtocolPaused);
}
Ok(())
}
fn assert_is_admin(env: &Env, caller: &Address) -> Result<(), ContractError> {
let admin: Address = env
.storage()
.persistent()
.get(&constants::storage::ADMIN_ADDRESS)
.ok_or(ContractError::Unauthorized)?;
if *caller != admin {
return Err(ContractError::Unauthorized);
}
Ok(())
}
fn read_protocol_fee_config(env: &Env) -> Option<fee::FeeConfig> {
env.storage()
.persistent()
.get(&constants::storage::FEE_CONFIG)
}
/// Validates that an address is not the Stellar zero address.
///
/// The zero address (`GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF`)
/// is the all-zero public key. Setting it as a fee recipient would silently
/// burn all protocol fees. This helper rejects it at the point of assignment.
fn validate_non_zero_address(env: &Env, addr: &Address) -> Result<(), ContractError> {
let zero_str = String::from_str(
env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
);
let zero_addr = Address::from_string(&zero_str);
if *addr == zero_addr {
return Err(ContractError::ZeroAddress);
}
Ok(())
}
fn read_required_protocol_fee_config(env: &Env) -> Result<fee::FeeConfig, ContractError> {
read_protocol_fee_config(env).ok_or(ContractError::FeeConfigNotSet)
}
fn read_protocol_fee_recipient_balance(env: &Env) -> i128 {
env.storage()
.persistent()
.get(&constants::storage::PROTOCOL_FEE_RECIPIENT_BALANCE)
.unwrap_or(0)
}
fn credit_protocol_fee_recipient_balance(env: &Env, amount: i128) -> Result<(), ContractError> {
if amount <= 0 {
return Ok(());
}
let updated = read_protocol_fee_recipient_balance(env)
.checked_add(amount)
.ok_or(ContractError::Overflow)?;
env.storage().persistent().set(
&constants::storage::PROTOCOL_FEE_RECIPIENT_BALANCE,
&updated,
);
Ok(())
}
/// Reads the accumulated treasury balance, returning `0` when none is stored.
pub fn read_treasury_balance(env: &Env) -> i128 {
env.storage()
.persistent()
.get(&constants::storage::TREASURY_BALANCE)
.unwrap_or(0)
}
/// Credits `amount` to the protocol treasury balance.
fn credit_treasury_balance(env: &Env, amount: i128) -> Result<(), ContractError> {
if amount <= 0 {
return Ok(());
}
let updated = read_treasury_balance(env)
.checked_add(amount)
.ok_or(ContractError::Overflow)?;
env.storage()
.persistent()
.set(&constants::storage::TREASURY_BALANCE, &updated);
Ok(())
}
fn assert_buy_price_slippage(price: i128, max_price: Option<i128>) -> Result<(), ContractError> {
if let Some(max) = max_price {
if price > max {
return Err(ContractError::SlippageExceeded);
}
}
Ok(())
}
fn assert_buyback_total_cost_slippage(
total_cost: i128,
max_total_cost: Option<i128>,
) -> Result<(), ContractError> {
if let Some(max) = max_total_cost {
if total_cost > max {
return Err(ContractError::SlippageExceeded);
}
}
Ok(())
}
fn compute_sell_proceeds(env: &Env, price: i128) -> Result<i128, ContractError> {
let (creator_fee, protocol_fee) =
CreatorKeysContract::compute_fees_for_payment(env.clone(), price)?;
let fees = fee::checked_fee_sum(creator_fee, protocol_fee).ok_or(ContractError::Overflow)?;
fee::checked_sub_i128(price, fees).ok_or(ContractError::SellUnderflow)
}
fn assert_sell_proceeds_slippage(
env: &Env,
price: i128,
min_proceeds: Option<i128>,
) -> Result<(), ContractError> {
if let Some(min) = min_proceeds {
let proceeds = compute_sell_proceeds(env, price)?;
if proceeds < min {
return Err(ContractError::SlippageExceeded);
}
}
Ok(())
}
fn accrue_sell_trade_fees(env: &Env, creator: &Address, price: i128) -> Result<(), ContractError> {
if read_protocol_fee_config(env).is_none() {
return Ok(());
}
let (creator_fee, protocol_fee) =
CreatorKeysContract::compute_fees_for_payment(env.clone(), price)?;
credit_creator_fee(env, creator, creator_fee)?;
credit_treasury_balance(env, protocol_fee)?;
if env
.storage()
.persistent()
.get::<DataKey, Address>(&constants::storage::PROTOCOL_FEE_RECIPIENT)
.is_some()
{
credit_protocol_fee_recipient_balance(env, protocol_fee)?;
}
Ok(())
}
/// Resolves and validates the shared inputs required by read-only quote methods.
///
/// Reads the key price and creator profile from storage, returning the
/// bonding-curve-adjusted price. Returns the appropriate [`ContractError`] on
/// failure. When the adjusted price is zero, returns `Ok(None)`.
fn resolve_quote_inputs(env: &Env, creator: &Address) -> Result<Option<i128>, ContractError> {
let base_price: i128 = env
.storage()
.persistent()
.get(&constants::storage::KEY_PRICE)
.ok_or(ContractError::KeyPriceNotSet)?;
let Some(normalized) = normalize_quote_amount(base_price)? else {
return Ok(None);
};
let profile = read_registered_creator_profile(env, creator)?;
let curve_price = compute_bonding_curve_price(env, creator, normalized, profile.supply)?;
normalize_quote_amount(curve_price)
}