-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathlib.rs
More file actions
1068 lines (940 loc) · 43.6 KB
/
Copy pathlib.rs
File metadata and controls
1068 lines (940 loc) · 43.6 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]
use soroban_sdk::{
contract, contractimpl, contracttype, panic_with_error, token, Address, Env, Map, String,
Symbol, Vec,
};
// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------
/// Storage keys used for persistent and instance storage.
#[derive(Clone)]
#[contracttype]
pub enum DataKey {
/// Admin address with privileged access.
Admin,
/// Pause flag for emergency stop.
Paused,
/// Platform fee in basis points (0–10_000).
FeeBps,
/// Address that receives platform fees.
FeeRecipient,
/// Maximum number of creators that can register. `0` disables the limit.
MaxCreators,
/// Maximum number of tips per creator that will be recorded. `0`
/// disables the limit.
MaxTipsPerCreator,
/// Minimum tip amount in token base units. `0` disables the minimum.
MinTipAmount,
/// Total number of currently-registered creators. Maintained alongside
/// `MaxCreators` for efficient cap enforcement.
CreatorCount,
/// Creator profile keyed by the creator's `Address`.
Profile(Address),
/// Reverse lookup: `Symbol` (username) → `Address` (creator).
UsernameToAddress(Symbol),
/// Balance of a given token held for a creator.
/// Encoded as `(creator Address, token Address)`.
Balance(Address, Address),
/// Total number of tips ever received by a creator.
TipCount(Address),
/// Single tip record identified by `(creator Address, index)`.
Tip(Address, u64),
/// Set of tokens a creator has received tips in.
/// Stored as a `Map<Address, ()>` so that per-token membership checks,
/// inserts, and removals run in O(log n) instead of the O(n) linear
/// scan required by a `Vec<Address>`.
CreatorTokens(Address),
}
/// Public profile information for a creator.
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct CreatorProfile {
pub username: Symbol,
pub display_name: String,
pub bio: String,
pub registered_at: u64,
}
/// A single tip that has been sent to a creator.
#[derive(Clone, Debug, Eq, PartialEq)]
#[contracttype]
pub struct Tip {
pub from: Address,
pub token: Address,
pub amount: i128,
pub message: String,
pub timestamp: u64,
}
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
/// All error variants raised by the StellarTip contract.
///
/// # Panic vs. return semantics
///
/// Every variant is raised via `panic_with_error!(env, TipError::Variant)`.
/// Soroban treats this as a host-level trap: **all storage writes and all
/// emitted events in the same transaction are rolled back atomically**.
/// Clients that "fire and forget" (submit without waiting for confirmation)
/// may observe a failed transaction with no on-chain side effects — the
/// supporter's funds are never moved, the creator's balance is unchanged, and
/// no events are emitted.
///
/// # Client recovery
///
/// Use `simulateTransaction` before broadcasting to surface errors before any
/// fees are charged. For detailed per-variant retry guidance see
/// [`docs/client-failure-handling.md`](../docs/client-failure-handling.md).
mod error {
use soroban_sdk::contracterror;
/// Contract error codes. Each variant maps to a Soroban `contractError`
/// integer discriminant visible in the RPC response as `#N`.
///
/// Variants are grouped below by the retry policy a client should adopt:
///
/// **Never retry (deterministic):** `#1`, `#3`, `#6`, `#8`, `#9`, `#11`,
/// `#12`, `#13`, `#15`.
///
/// **Retry after condition lifts:** `#2`, `#4`, `#5`, `#10`, `#14`, `#16`.
///
/// **Dead code (currently unreachable):** `#7`.
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum TipError {
/// `#1` — Raised by `register()` when the caller's address already has
/// a registered profile.
///
/// **When to panic:** inside `register()` after a successful
/// `env.storage().persistent().has(&DataKey::Profile(caller))` check.
///
/// **Client recovery:** the address is already a creator; skip
/// re-registration. Never retry.
CreatorAlreadyExists = 1,
/// `#2` — Raised when a function requires a registered creator profile
/// (e.g. `tip()`, `get_profile()`) but none exists for the given address.
///
/// **When to panic:** inside `tip()` and profile-lookup helpers after
/// `env.storage().persistent().has(&DataKey::Profile(creator))` returns
/// `false`.
///
/// **Client recovery:** verify the recipient address or username; re-fetch
/// the profile before retrying.
CreatorNotFound = 2,
/// `#3` — Raised by `register()` when the requested username is already
/// claimed by a different address.
///
/// **When to panic:** inside `register()` after
/// `env.storage().instance().has(&DataKey::UsernameToAddress(username))`
/// returns `true`.
///
/// **Client recovery:** prompt the user to choose a different username.
/// Never retry with the same username.
UsernameTaken = 3,
/// `#4` — Raised by `withdraw()` when the requested withdrawal amount
/// exceeds the creator's recorded on-contract balance for the given token.
///
/// **When to panic:** inside `withdraw()` after reading
/// `DataKey::Balance(creator, token)` and finding it less than `amount`.
///
/// **Client recovery:** re-read the balance via `get_balance()` and
/// reduce the withdrawal amount accordingly.
InsufficientBalance = 4,
/// `#5` — Raised when the underlying Stellar Asset Contract (SAC)
/// `transfer()` call fails (e.g. the supporter's wallet has insufficient
/// funds, the asset is frozen, or the SAC rejects the transfer).
///
/// **When to panic:** inside `tip()` after the SAC `transfer()` invocation
/// returns an error.
///
/// **Client recovery:** check the user's wallet balance and asset status;
/// surface a wallet-level error to the user; retry only after the
/// underlying condition is resolved.
TransferFailed = 5,
/// `#6` — Raised when `amount` is zero or negative.
///
/// **When to panic:** inside `tip()` as the first argument guard.
///
/// **Client recovery:** validate `amount > 0` before building the
/// transaction. Never retry with the same value.
InvalidAmount = 6,
/// `#7` — Defined for completeness; **currently unreachable** in the
/// live implementation. No production code path raises this variant.
///
/// **Client recovery:** treat as an unexpected internal error if ever
/// encountered.
NoTips = 7,
/// `#8` — Raised by any state-changing function when `init()` has not
/// yet been called (the `Admin` storage key is absent).
///
/// **When to panic:** inside `check_initialized_and_not_paused()`.
///
/// **Client recovery:** contact the platform operator; the contract has
/// not been set up. Never retry.
NotInitialized = 8,
/// `#9` — Raised by `init()` when called a second time (the `Admin`
/// storage key already exists).
///
/// **When to panic:** at the top of `init()`.
///
/// **Client recovery:** the contract is already live; no action needed.
/// Never retry.
AlreadyInitialized = 9,
/// `#10` — Raised by any user-facing state-changing function when the
/// contract is in emergency-pause state (`DataKey::Paused == true`).
///
/// **When to panic:** inside `check_initialized_and_not_paused()`.
///
/// **Client recovery:** poll `is_paused()` with exponential backoff;
/// notify the user and retry only after the contract is unpaused by the
/// admin.
Paused = 10,
/// `#11` — Raised by admin-gated functions when the `caller` is not the
/// current admin address stored in `DataKey::Admin`.
///
/// **When to panic:** in every admin function after
/// `caller.require_auth()` succeeds but the stored admin address does not
/// match.
///
/// **Client recovery:** never expose admin functions to non-admin users.
/// Never retry.
NotAuthorized = 11,
/// `#12` — Raised by `register()` and `update_profile()` when
/// `display_name` or `bio` exceed their maximum byte lengths
/// (`MAX_DISPLAY_NAME_LEN = 64` and `MAX_BIO_LEN = 256` respectively).
///
/// **When to panic:** inside `validate_input()`.
///
/// **Client recovery:** enforce length limits in the UI before
/// submission. Never retry with the same values.
InvalidInput = 12,
/// `#13` — Raised by `unregister()` when the creator still holds a
/// non-zero balance for at least one token.
///
/// **When to panic:** inside `unregister()` after iterating
/// `DataKey::CreatorTokens(caller)` and finding a positive balance.
///
/// **Client recovery:** direct the user to call `withdraw()` for every
/// token until all balances reach zero, then retry `unregister()`.
BalanceNotEmpty = 13,
/// `#14` — Raised when an admin-configured cap (`MaxCreators` or
/// `MaxTipsPerCreator`) has been reached.
///
/// **When to panic:** inside `register()` when
/// `CreatorCount >= MaxCreators`, or inside `tip()` when
/// `TipCount(creator) >= MaxTipsPerCreator`.
///
/// **Client recovery:** notify the user that the platform's capacity
/// limit has been reached; retry only after the admin raises the cap via
/// `set_max_creators()` or `set_max_tips_per_creator()`.
CapExceeded = 14,
/// `#15` — Raised when a tip is attempted with `fee_bps > 0` but the
/// `FeeRecipient` storage key is absent (contract misconfiguration).
///
/// **When to panic:** inside `tip()` after reading
/// `DataKey::FeeRecipient` and finding no value despite a non-zero fee.
///
/// **Client recovery:** contact the platform operator; this indicates a
/// contract state corruption or incomplete initialisation. Never retry.
FeeRecipientNotSet = 15,
/// `#16` — Raised when `amount` is positive but below the configured
/// `MinTipAmount` floor set by the admin.
///
/// **When to panic:** inside `tip()` after the `amount > 0` guard but
/// before the SAC transfer, when
/// `amount < env.storage().instance().get(&DataKey::MinTipAmount)`.
///
/// **Client recovery:** fetch the current minimum via
/// `get_min_tip_amount()` and re-present the updated floor to the user.
/// **Do not** blindly retry with the same amount; re-quote first.
BelowMinimum = 16,
}
}
use error::TipError;
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/// Current contract version for client compatibility.
///
/// v3 introduces a configurable minimum tip amount (`MinTipAmount`) to prevent
/// dust attacks, along with `set_min_tip_amount()`, `get_min_tip_amount()`, and
/// a new `init()` parameter. Clients should use `get_contract_version()` to
/// detect the deployed shape.
pub const CONTRACT_VERSION: u32 = 3;
/// Maximum platform fee in basis points (100% = 10_000 bps).
const MAX_FEE_BPS: u32 = 10_000;
/// Display name max length in bytes.
const MAX_DISPLAY_NAME_LEN: u32 = 64;
/// Bio max length in bytes.
const MAX_BIO_LEN: u32 = 256;
/// Default cap on total registered creators when one isn't provided by the
/// admin at initialization. Sized to give plenty of headroom for early growth
/// while protecting against unbounded instance-storage bloat.
pub const DEFAULT_MAX_CREATORS: u32 = 10_000;
/// Default cap on tip history length per creator when one isn't provided.
/// Bounds the per-creator persistent-storage footprint.
pub const DEFAULT_MAX_TIPS_PER_CREATOR: u32 = 10_000;
/// Default minimum tip amount in token base units.
///
/// A value of `1` is equivalent to the existing `amount > 0` guard and
/// preserves all prior behaviour. This default provides no meaningful dust
/// protection on its own — admins should raise it to a token-appropriate
/// threshold after deployment. `0` disables the minimum entirely.
pub const DEFAULT_MIN_TIP_AMOUNT: i128 = 1;
/// TTL threshold (ledgers) before extension is triggered.
/// ~17_280 ledgers per day; 15 days.
const TTL_THRESHOLD: u32 = 17_280 * 15;
/// TTL extension target (ledgers).
/// ~30 days.
const TTL_EXTEND: u32 = 17_280 * 30;
// ---------------------------------------------------------------------------
// Events
// ---------------------------------------------------------------------------
/// Emitted when a new creator registers.
const EVENT_CREATOR_REGISTERED: Symbol = soroban_sdk::symbol_short!("CREG");
/// Emitted when a tip is sent.
const EVENT_TIP_SENT: Symbol = soroban_sdk::symbol_short!("TIP");
/// Emitted when a creator withdraws tokens.
const EVENT_WITHDRAW: Symbol = soroban_sdk::symbol_short!("WDRW");
/// Emitted when a creator updates their profile.
const EVENT_PROFILE_UPDATED: Symbol = soroban_sdk::symbol_short!("PUPD");
/// Emitted when a creator unregisters.
const EVENT_CREATOR_UNREGISTERED: Symbol = soroban_sdk::symbol_short!("UREG");
/// Emitted when the contract is paused.
const EVENT_PAUSED: Symbol = soroban_sdk::symbol_short!("PAUS");
/// Emitted when the contract is unpaused.
const EVENT_UNPAUSED: Symbol = soroban_sdk::symbol_short!("UNPA");
/// Emitted when the platform fee is changed.
const EVENT_FEE_CHANGED: Symbol = soroban_sdk::symbol_short!("FEEC");
/// Emitted when the admin is changed.
const EVENT_ADMIN_CHANGED: Symbol = soroban_sdk::symbol_short!("ADMC");
/// Emitted when the fee recipient is changed.
const EVENT_FEE_RECIPIENT_CHANGED: Symbol = soroban_sdk::symbol_short!("FERC");
/// Emitted when the admin-configured creator cap is updated.
const EVENT_MAX_CREATORS_CHANGED: Symbol = soroban_sdk::symbol_short!("CAPMC");
/// Emitted when the admin-configured per-creator tip cap is updated.
const EVENT_MAX_TIPS_CHANGED: Symbol = soroban_sdk::symbol_short!("CAPMT");
/// Emitted when the admin-configured minimum tip amount is updated.
const EVENT_MIN_TIP_CHANGED: Symbol = soroban_sdk::symbol_short!("MINTC");
/// Emitted when the contract is initialized.
const EVENT_INIT: Symbol = soroban_sdk::symbol_short!("INIT");
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Extend the TTL of the contract instance storage.
fn extend_instance_ttl(env: &Env) {
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND);
}
/// Extend the TTL of a persistent storage entry.
fn extend_persistent_ttl(env: &Env, key: &DataKey) {
env.storage().persistent().extend_ttl(key, TTL_THRESHOLD, TTL_EXTEND);
}
/// Verify the contract is initialized and not paused.
fn check_initialized_and_not_paused(env: &Env) {
if !env.storage().instance().has(&DataKey::Admin) {
panic_with_error!(env, TipError::NotInitialized);
}
let is_paused: bool = env.storage().instance().get(&DataKey::Paused).unwrap_or(false);
if is_paused {
panic_with_error!(env, TipError::Paused);
}
extend_instance_ttl(env);
}
/// Validate string length constraints.
fn validate_input(env: &Env, _username: Option<Symbol>, display_name: &String, bio: &String) {
// Username is a Symbol which is already limited by the Soroban SDK
// to ScSymbol's max length (32 bytes), so we skip an explicit check here.
let _ = _username;
if display_name.len() > MAX_DISPLAY_NAME_LEN {
panic_with_error!(env, TipError::InvalidInput);
}
if bio.len() > MAX_BIO_LEN {
panic_with_error!(env, TipError::InvalidInput);
}
}
// ---------------------------------------------------------------------------
// Contract
// ---------------------------------------------------------------------------
#[contract]
pub struct TipContract;
#[contractimpl]
impl TipContract {
// -----------------------------------------------------------------------
// Initialization
// -----------------------------------------------------------------------
/// Initialize the contract with an admin, fee recipient, platform fee,
/// storage-bloat caps, and a minimum tip amount.
///
/// `max_creators` and `max_tips_per_creator` are the hard caps enforced on
/// `register()` and `tip()` respectively. A value of `0` disables the
/// corresponding cap ("unlimited"). The defaults
/// [`DEFAULT_MAX_CREATORS`] and [`DEFAULT_MAX_TIPS_PER_CREATOR`] are
/// sensible starting points when no admin preference is known.
///
/// `min_tip_amount` is the minimum token amount accepted by `tip()`.
/// A value of `0` disables the minimum. [`DEFAULT_MIN_TIP_AMOUNT`] (= 1)
/// preserves prior behaviour; raise it post-deployment for meaningful dust
/// protection.
///
/// # Arguments
/// * `caller` – Address that becomes the admin (must authorize).
/// * `fee_recipient` – Address that receives platform fees.
/// * `fee_bps` – Platform fee in basis points (0–10_000).
/// * `max_creators` – Cap on total registered creators (`0` = unlimited).
/// * `max_tips_per_creator` – Cap on tip history per creator (`0` = unlimited).
/// * `min_tip_amount` – Minimum tip in token base units (`0` = no minimum).
pub fn init(
env: Env,
caller: Address,
fee_recipient: Address,
fee_bps: u32,
max_creators: u32,
max_tips_per_creator: u32,
min_tip_amount: i128,
) {
caller.require_auth();
if env.storage().instance().has(&DataKey::Admin) {
panic_with_error!(env, TipError::AlreadyInitialized);
}
if fee_bps > MAX_FEE_BPS {
panic_with_error!(env, TipError::InvalidInput);
}
if min_tip_amount < 0 {
panic_with_error!(env, TipError::InvalidInput);
}
if fee_recipient == env.current_contract_address() {
panic_with_error!(env, TipError::InvalidInput);
}
env.storage().instance().set(&DataKey::Admin, &caller);
env.storage().instance().set(&DataKey::FeeRecipient, &fee_recipient);
env.storage().instance().set(&DataKey::FeeBps, &fee_bps);
env.storage().instance().set(&DataKey::Paused, &false);
env.storage().instance().set(&DataKey::MaxCreators, &max_creators);
env.storage().instance().set(&DataKey::MaxTipsPerCreator, &max_tips_per_creator);
env.storage().instance().set(&DataKey::MinTipAmount, &min_tip_amount);
env.storage().instance().set(&DataKey::CreatorCount, &0u32);
extend_instance_ttl(&env);
env.events().publish((EVENT_INIT, caller), (fee_recipient, fee_bps));
}
// -----------------------------------------------------------------------
// Admin functions
// -----------------------------------------------------------------------
/// Transfer admin privileges to a new address.
pub fn set_admin(env: Env, caller: Address, new_admin: Address) {
caller.require_auth();
let current_admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != current_admin {
panic_with_error!(env, TipError::NotAuthorized);
}
if new_admin == caller
|| new_admin
== Address::from_string(&String::from_str(
&env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
))
{
panic_with_error!(env, TipError::InvalidInput);
}
env.storage().instance().set(&DataKey::Admin, &new_admin);
extend_instance_ttl(&env);
env.events().publish((EVENT_ADMIN_CHANGED, caller), new_admin);
}
/// Pause the contract (emergency stop). Only admin can call.
pub fn pause(env: Env, caller: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
env.storage().instance().set(&DataKey::Paused, &true);
extend_instance_ttl(&env);
env.events().publish((EVENT_PAUSED, caller), ());
}
/// Unpause the contract. Only admin can call.
pub fn unpause(env: Env, caller: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
env.storage().instance().set(&DataKey::Paused, &false);
extend_instance_ttl(&env);
env.events().publish((EVENT_UNPAUSED, caller), ());
}
/// Set the platform fee percentage. Only admin can call.
pub fn set_fee_percentage(env: Env, caller: Address, fee_bps: u32) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
if fee_bps > MAX_FEE_BPS {
panic_with_error!(env, TipError::InvalidInput);
}
env.storage().instance().set(&DataKey::FeeBps, &fee_bps);
extend_instance_ttl(&env);
env.events().publish((EVENT_FEE_CHANGED, caller), fee_bps);
}
/// Set the fee recipient address. Only admin can call.
pub fn set_fee_recipient(env: Env, caller: Address, fee_recipient: Address) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
if fee_recipient == env.current_contract_address() {
panic_with_error!(env, TipError::InvalidInput);
}
env.storage().instance().set(&DataKey::FeeRecipient, &fee_recipient);
extend_instance_ttl(&env);
env.events().publish((EVENT_FEE_RECIPIENT_CHANGED, caller), fee_recipient);
}
/// Update the maximum number of creators that can register. A value of
/// `0` disables the cap (unlimited). Only admin can call.
///
/// Lowering the cap below the current creator count does **not**
/// retroactively remove any creator; it only blocks new registrations
/// until the count drops (via `unregister`) back below the cap.
pub fn set_max_creators(env: Env, caller: Address, max_creators: u32) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
env.storage().instance().set(&DataKey::MaxCreators, &max_creators);
extend_instance_ttl(&env);
env.events().publish((EVENT_MAX_CREATORS_CHANGED, caller), max_creators);
}
/// Update the maximum number of tips recorded per creator. A value of
/// `0` disables the cap (unlimited). Only admin can call.
///
/// Lowering the cap below the current tip count for any creator does
/// **not** delete historical tips; it only blocks new tips for that
/// creator until the admin raises the cap again.
pub fn set_max_tips_per_creator(env: Env, caller: Address, max_tips: u32) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
env.storage().instance().set(&DataKey::MaxTipsPerCreator, &max_tips);
extend_instance_ttl(&env);
env.events().publish((EVENT_MAX_TIPS_CHANGED, caller), max_tips);
}
/// Update the minimum tip amount in token base units. A value of `0`
/// disables the minimum entirely. Only admin can call.
///
/// Raising the minimum does **not** affect existing tip records; it only
/// gates future calls to `tip()`.
pub fn set_min_tip_amount(env: Env, caller: Address, min_tip_amount: i128) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic_with_error!(env, TipError::NotInitialized));
if caller != admin {
panic_with_error!(env, TipError::NotAuthorized);
}
if min_tip_amount < 0 {
panic_with_error!(env, TipError::InvalidInput);
}
env.storage().instance().set(&DataKey::MinTipAmount, &min_tip_amount);
extend_instance_ttl(&env);
env.events().publish((EVENT_MIN_TIP_CHANGED, caller), min_tip_amount);
}
// -----------------------------------------------------------------------
// Registration
// -----------------------------------------------------------------------
/// Register a new creator profile.
///
/// # Arguments
/// * `username` – A unique `Symbol` identifier (e.g. `"jane"`).
/// * `display_name` – Human-readable display name.
/// * `bio` – Short biography text.
pub fn register(
env: Env,
caller: Address,
username: Symbol,
display_name: String,
bio: String,
) {
caller.require_auth();
check_initialized_and_not_paused(&env);
validate_input(&env, Some(username.clone()), &display_name, &bio);
// Per-call checks first so the caller sees the most specific error
// (e.g. `CreatorAlreadyExists`) before any global cap is consulted.
// Each address can only register once.
if env.storage().instance().has(&DataKey::Profile(caller.clone())) {
panic_with_error!(env, TipError::CreatorAlreadyExists);
}
// Each username must be unique.
if env.storage().instance().has(&DataKey::UsernameToAddress(username.clone())) {
panic_with_error!(env, TipError::UsernameTaken);
}
// Enforce the global creator cap (skip if `MaxCreators == 0`).
let max_creators: u32 = env.storage().instance().get(&DataKey::MaxCreators).unwrap_or(0);
let creator_count: u32 = env.storage().instance().get(&DataKey::CreatorCount).unwrap_or(0);
if max_creators > 0 && creator_count >= max_creators {
panic_with_error!(env, TipError::CapExceeded);
}
let profile = CreatorProfile {
username: username.clone(),
display_name,
bio,
registered_at: env.ledger().timestamp(),
};
env.storage().instance().set(&DataKey::Profile(caller.clone()), &profile);
env.storage().instance().set(&DataKey::UsernameToAddress(username), &caller);
// TipCount moved to persistent storage for durability.
env.storage().persistent().set(&DataKey::TipCount(caller.clone()), &0u64);
extend_persistent_ttl(&env, &DataKey::TipCount(caller.clone()));
// Bump the global creator count last, after every other check has
// succeeded, so we never dirty it on a failed registration.
env.storage().instance().set(&DataKey::CreatorCount, &(creator_count + 1));
env.events()
.publish((EVENT_CREATOR_REGISTERED, caller), (profile.username, profile.registered_at));
}
/// Update a creator's display name and bio.
pub fn update_profile(env: Env, caller: Address, display_name: String, bio: String) {
caller.require_auth();
check_initialized_and_not_paused(&env);
validate_input(&env, None, &display_name, &bio);
let mut profile: CreatorProfile = env
.storage()
.instance()
.get(&DataKey::Profile(caller.clone()))
.unwrap_or_else(|| panic_with_error!(env, TipError::CreatorNotFound));
profile.display_name = display_name;
profile.bio = bio;
env.storage().instance().set(&DataKey::Profile(caller.clone()), &profile);
extend_instance_ttl(&env);
env.events().publish(
(EVENT_PROFILE_UPDATED, caller),
(profile.username, profile.display_name.clone()),
);
}
/// Unregister a creator. Requires all token balances to be zero.
pub fn unregister(env: Env, caller: Address) {
caller.require_auth();
check_initialized_and_not_paused(&env);
let profile: CreatorProfile = env
.storage()
.instance()
.get(&DataKey::Profile(caller.clone()))
.unwrap_or_else(|| panic_with_error!(env, TipError::CreatorNotFound));
// Ensure all balances are zero.
let tokens_key = DataKey::CreatorTokens(caller.clone());
if let Some(tokens) = env.storage().persistent().get::<_, Map<Address, ()>>(&tokens_key) {
for token in tokens.keys() {
let balance = env
.storage()
.persistent()
.get::<_, i128>(&DataKey::Balance(caller.clone(), token))
.unwrap_or(0);
if balance > 0 {
panic_with_error!(env, TipError::BalanceNotEmpty);
}
}
env.storage().persistent().remove(&tokens_key);
}
let tip_count_key = DataKey::TipCount(caller.clone());
env.storage().persistent().remove(&tip_count_key);
env.storage().instance().remove(&DataKey::UsernameToAddress(profile.username));
env.storage().instance().remove(&DataKey::Profile(caller.clone())); // Decrement the global creator count now that the profile is gone.
let current_count: u32 = env.storage().instance().get(&DataKey::CreatorCount).unwrap_or(0);
if current_count > 0 {
env.storage().instance().set(&DataKey::CreatorCount, &(current_count - 1));
}
env.events().publish((EVENT_CREATOR_UNREGISTERED, caller), ());
}
// -----------------------------------------------------------------------
// Tipping
// -----------------------------------------------------------------------
/// Send a tip to a registered creator.
///
/// The caller authorises a transfer of `amount` of `token` to this
/// contract, which credits the creator's internal balance and records the
/// tip for history purposes.
///
/// Returns the index of the newly created `Tip` record.
pub fn tip(
env: Env,
from: Address,
creator: Address,
token: Address,
amount: i128,
message: String,
) -> u64 {
from.require_auth();
check_initialized_and_not_paused(&env);
if amount <= 0 {
panic_with_error!(env, TipError::InvalidAmount);
}
let min_tip_amount: i128 =
env.storage().instance().get(&DataKey::MinTipAmount).unwrap_or(0);
if min_tip_amount > 0 && amount < min_tip_amount {
panic_with_error!(env, TipError::BelowMinimum);
}
// Verify the creator exists.
if !env.storage().instance().has(&DataKey::Profile(creator.clone())) {
panic_with_error!(env, TipError::CreatorNotFound);
}
// Enforce the per-creator tip-history cap. The `TipCount` value
// already lives in persistent storage, so we read it once and use
// it both for the cap check and as the new tip's index below.
let max_tips: u32 = env.storage().instance().get(&DataKey::MaxTipsPerCreator).unwrap_or(0);
let tip_count_key = DataKey::TipCount(creator.clone());
let index: u64 = env.storage().persistent().get(&tip_count_key).unwrap_or(0);
if max_tips > 0 && index >= max_tips as u64 {
panic_with_error!(env, TipError::CapExceeded);
}
let fee_bps: u32 = env.storage().instance().get(&DataKey::FeeBps).unwrap_or(0);
let fee = (amount * (fee_bps as i128)) / (MAX_FEE_BPS as i128);
let creator_amount = amount - fee;
// Fail-fast: if a non-zero fee is configured but the fee recipient is
// not configured (corrupted / unset storage), abort before touching
// external token contracts.
let opt_fee_recipient: Option<Address> =
env.storage().instance().get(&DataKey::FeeRecipient);
if fee_bps > 0 && opt_fee_recipient.is_none() {
panic_with_error!(env, TipError::FeeRecipientNotSet);
}
// 1. Transfer tokens from sender → this contract.
let token_client = token::Client::new(&env, &token);
token_client.transfer(&from, &env.current_contract_address(), &amount);
// 2. Forward fee to recipient.
if fee > 0 {
// Safe to unwrap: validated above when fee_bps > 0. Use
// `unwrap_or_else` defensively to surface a clean contract error
// rather than a raw panic if storage ever goes missing between
// the check and here.
let fee_recipient: Address = opt_fee_recipient
.unwrap_or_else(|| panic_with_error!(env, TipError::FeeRecipientNotSet));
token_client.transfer(&env.current_contract_address(), &fee_recipient, &fee);
}
// 3. Credit the creator's internal balance.
let balance_key = DataKey::Balance(creator.clone(), token.clone());
let current_balance: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0_i128);
env.storage().persistent().set(&balance_key, &(current_balance + creator_amount));
extend_persistent_ttl(&env, &balance_key);
// 4. Track token for creator. The token set is stored as a
// `Map<Address, ()>` so membership checks and inserts run in
// O(log n) regardless of how many tokens the creator already has.
let tokens_key = DataKey::CreatorTokens(creator.clone());
let mut tokens: Map<Address, ()> =
env.storage().persistent().get(&tokens_key).unwrap_or_else(|| Map::new(&env));
if !tokens.contains_key(token.clone()) {
tokens.set(token.clone(), ());
env.storage().persistent().set(&tokens_key, &tokens);
}
extend_persistent_ttl(&env, &tokens_key);
// 5. Record the tip. (Note: `index` and `tip_count_key` were read
// above so we can enforce the per-creator tip cap before any token
// transfer or storage write occurs.)
let tip = Tip {
from: from.clone(),
token: token.clone(),
amount,
message,
timestamp: env.ledger().timestamp(),
};
env.storage().persistent().set(&DataKey::Tip(creator.clone(), index), &tip);
extend_persistent_ttl(&env, &DataKey::Tip(creator.clone(), index));
env.storage().persistent().set(&tip_count_key, &(index + 1));
extend_persistent_ttl(&env, &tip_count_key);
// 6. Emit event.
env.events().publish((EVENT_TIP_SENT, from.clone()), (creator, token, amount, fee, index));
index
}
// -----------------------------------------------------------------------
// Withdrawal
// -----------------------------------------------------------------------
/// Withdraw a given amount of a specific token from the caller's
/// accumulated tips. The caller must be a registered creator.
pub fn withdraw(env: Env, caller: Address, token: Address, amount: i128) {
caller.require_auth();
check_initialized_and_not_paused(&env);
// Verify caller is a registered creator.
if !env.storage().instance().has(&DataKey::Profile(caller.clone())) {
panic_with_error!(env, TipError::CreatorNotFound);
}
if amount <= 0 {
panic_with_error!(env, TipError::InvalidAmount);
}
let balance_key = DataKey::Balance(caller.clone(), token.clone());
let current_balance: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0);
if current_balance < amount {
panic_with_error!(env, TipError::InsufficientBalance);
}
// Transfer tokens from this contract to the creator.
let token_client = token::Client::new(&env, &token);
token_client.transfer(&env.current_contract_address(), &caller, &amount);
// Update balance.
let remaining = current_balance - amount;
let tokens_key = DataKey::CreatorTokens(caller.clone());
if remaining > 0 {
env.storage().persistent().set(&balance_key, &remaining);
extend_persistent_ttl(&env, &balance_key);
extend_persistent_ttl(&env, &tokens_key);
} else {
env.storage().persistent().remove(&balance_key);
// Remove the token from the creator's tracked token set in
// O(log n). The host-backed `Map` performs this lookup and
// removal directly without scanning every entry.
let mut tokens: Map<Address, ()> =
env.storage().persistent().get(&tokens_key).unwrap_or_else(|| Map::new(&env));
if tokens.remove(token.clone()).is_some() {
if tokens.is_empty() {
env.storage().persistent().remove(&tokens_key);
} else {
env.storage().persistent().set(&tokens_key, &tokens);
extend_persistent_ttl(&env, &tokens_key);
}
}
}
// Emit event.
env.events().publish((EVENT_WITHDRAW, caller.clone()), (token, amount));
}
// -----------------------------------------------------------------------
// View functions
// -----------------------------------------------------------------------
/// Return the `CreatorProfile` for the given address, or `None` if the
/// address is not yet registered.
pub fn get_profile(env: Env, address: Address) -> Option<CreatorProfile> {
env.storage().instance().get(&DataKey::Profile(address))
}
/// Return the creator `Address` that owns the given username, or `None`.
pub fn get_creator_from_username(env: Env, username: Symbol) -> Option<Address> {
env.storage().instance().get(&DataKey::UsernameToAddress(username))
}
/// Return the current balance of a specific token held for a creator.
pub fn get_balance(env: Env, creator: Address, token: Address) -> i128 {
env.storage().persistent().get(&DataKey::Balance(creator, token)).unwrap_or(0)
}
/// Return the total number of tips a creator has ever received.
pub fn get_tip_count(env: Env, creator: Address) -> u64 {
env.storage().persistent().get(&DataKey::TipCount(creator)).unwrap_or(0)
}
/// Return a specific `Tip` record by its index.
pub fn get_tip(env: Env, creator: Address, index: u64) -> Option<Tip> {
env.storage().persistent().get(&DataKey::Tip(creator, index))
}
/// Return a paginated list of tips for a creator.
pub fn get_tips(env: Env, creator: Address, start: u64, limit: u64) -> Vec<Tip> {
let mut results = Vec::new(&env);
let count: u64 =
env.storage().persistent().get(&DataKey::TipCount(creator.clone())).unwrap_or(0);
let end = (start + limit).min(count);
for i in start..end {
let key = DataKey::Tip(creator.clone(), i);
if let Some(tip) = env.storage().persistent().get(&key) {
results.push_back(tip);
}
}
results
}
/// Return the `CreatorProfile` for a given username.
pub fn get_profile_by_username(env: Env, username: Symbol) -> Option<CreatorProfile> {
if let Some(addr) = env.storage().instance().get(&DataKey::UsernameToAddress(username)) {
env.storage().instance().get(&DataKey::Profile(addr))
} else {
None
}
}
/// Return whether the given address is a registered creator.
pub fn is_creator(env: Env, address: Address) -> bool {
env.storage().instance().has(&DataKey::Profile(address))
}
/// Return whether a given username has already been taken.
pub fn is_username_taken(env: Env, username: Symbol) -> bool {
env.storage().instance().has(&DataKey::UsernameToAddress(username))
}
/// Return the list of tokens a creator has received tips in.
pub fn get_all_tokens(env: Env, creator: Address) -> Vec<Address> {
match env
.storage()
.persistent()
.get::<_, Map<Address, ()>>(&DataKey::CreatorTokens(creator))
{