forked from ritik4ever/stellar-goal-vault
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
974 lines (865 loc) · 33 KB
/
Copy pathlib.rs
File metadata and controls
974 lines (865 loc) · 33 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
#![no_std]
use soroban_sdk::{
contract, contractimpl, contracttype, symbol_short, token::Client as TokenClient, Address, Env,
String, Vec,
};
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
/// Default minimum contribution in stroops (100). Overridable via initialize().
const MIN_CONTRIBUTION: i128 = 100;
/// Maximum number of distinct tokens a campaign can accept.
/// This prevents unbounded Vec storage growth attacks where an adversary
/// creates a campaign with thousands of token addresses, inflating the
/// ledger entry size and forcing other validators to pay higher fees for
/// processing oversized entries. A limit of 10 is sufficient for realistic
/// multi-token donation campaigns while keeping storage costs predictable.
const MAX_ACCEPTED_TOKENS: u32 = 10;
/// Default platform fee in basis points (50 = 0.5%). Admin can override
/// via [`set_fee`]. Set to 0 to disable the fee mechanism entirely.
const DEFAULT_PLATFORM_FEE_BPS: i128 = 50;
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Campaign {
pub creator: Address,
pub accepted_tokens: Vec<Address>,
pub target_amount: i128,
pub pledged_amount: i128,
pub deadline: u64,
pub claimed: bool,
pub canceled: bool,
pub metadata: String,
pub contributor_count: u32,
pub created_at: u64,
}
#[contracttype]
pub enum DataKey {
NextCampaignId,
ContractVersion,
DeploymentTimestamp,
Campaign(u64),
Contribution(u64, Address, Address), // (campaign_id, contributor, token)
CampaignTokenBalance(u64, Address), // (campaign_id, token)
/// Maximum total contribution any single contributor may make to a
/// campaign across all tokens. Absent (or zero) means no cap.
ContributorCap(u64), // campaign_id → i128
Admin,
Paused,
MinContribution,
ExtensionRequest(u64),
ExtensionVote(u64, Address),
HasContributed(u64, Address), // (campaign_id, contributor)
/// Tracks which (old_contract_id, campaign_id) pairs have already been migrated.
MigratedId(Address, u64),
/// Track contributor addresses for a campaign (used in refund_all).
Contributors(u64),
/// Platform fee in basis points (e.g. 50 = 0.5%). Defaults to
/// [`DEFAULT_PLATFORM_FEE_BPS`] when absent. 0 disables the fee.
PlatformFeeBps,
/// Address that receives platform fees on campaign claims. When absent no
/// fee is deducted regardless of [`PlatformFeeBps`].
FeeRecipient,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DeployInfo {
pub version: String,
pub deployed_at: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignCreated {
pub campaign_id: u64,
pub creator: Address,
pub token: Address,
pub target_amount: i128,
pub deadline: u64,
pub metadata: String,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignPledged {
pub campaign_id: u64,
pub contributor: Address,
pub token: Address,
pub amount: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignClaimed {
pub campaign_id: u64,
pub creator: Address,
pub token: Address,
pub amount: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignRefunded {
pub campaign_id: u64,
pub contributor: Address,
pub token: Address,
pub amount: i128,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CampaignCanceled {
pub campaign_id: u64,
pub creator: Address,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractPaused {
pub contract_version: String,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractUnpaused {
pub contract_version: String,
}
/// Emitted when a campaign creator updates the campaign metadata (issue #185).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MetadataUpdated {
pub campaign_id: u64,
pub creator: Address,
pub old_metadata: String,
pub new_metadata: String,
}
/// Stored when a contributor requests a deadline extension (issue #192).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExtensionRequest {
pub new_deadline: u64,
pub requested_by: Address,
pub approval_count: u32,
}
/// Emitted when a deadline extension is requested (issue #192).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExtensionRequested {
pub campaign_id: u64,
pub requested_by: Address,
pub new_deadline: u64,
}
/// Emitted when a platform fee is deducted from a campaign claim.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FeeCollected {
pub campaign_id: u64,
pub token: Address,
pub fee_amount: i128,
pub fee_recipient: Address,
}
#[contract]
pub struct StellarGoalVaultContract;
const MAX_CAMPAIGN_DURATION_SECONDS: u64 = 60 * 60 * 24 * 180;
#[contractimpl]
impl StellarGoalVaultContract {
/// Sets the admin address and the minimum contribution floor (in stroops).
/// Panics if already initialized or min_contribution is not positive.
pub fn initialize(env: Env, admin: Address, min_contribution: i128) {
if env.storage().instance().has(&DataKey::Admin) {
panic!("already initialized");
}
if min_contribution <= 0 {
panic!("min_contribution must be positive");
}
admin.require_auth();
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage().instance().set(&DataKey::Paused, &false);
env.storage().instance().set(&DataKey::MinContribution, &min_contribution);
}
/// Returns the current minimum contribution threshold in stroops.
/// Falls back to the compile-time default (100) if initialize() was not called.
pub fn get_min_contribution(env: Env) -> i128 {
env.storage()
.instance()
.get(&DataKey::MinContribution)
.unwrap_or(MIN_CONTRIBUTION)
}
/// Pauses or unpauses all state-mutating entry points. Admin only.
pub fn set_paused(env: Env, caller: Address, paused: bool) {
caller.require_auth();
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
if caller != admin {
panic!("caller is not admin");
}
env.storage().instance().set(&DataKey::Paused, &paused);
let version = String::from_str(&env, CONTRACT_VERSION);
if paused {
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Pause")),
ContractPaused { contract_version: version },
);
} else {
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Unpause")),
ContractUnpaused { contract_version: version },
);
}
}
pub fn get_paused(env: Env) -> bool {
env.storage().instance().get(&DataKey::Paused).unwrap_or(false)
}
pub fn get_admin(env: Env) -> Address {
env.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"))
}
/// Sets the platform fee in basis points (e.g. 50 = 0.5%).
/// Only the admin can call this. Pass 0 to disable the fee.
pub fn set_fee(env: Env, admin: Address, bps: i128) {
admin.require_auth();
let stored_admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
if admin != stored_admin {
panic!("caller is not admin");
}
if bps < 0 {
panic!("fee must be non-negative");
}
env.storage().instance().set(&DataKey::PlatformFeeBps, &bps);
}
/// Sets the address that receives platform fees on campaign claims.
/// Only the admin can call this.
pub fn set_fee_recipient(env: Env, admin: Address, recipient: Address) {
admin.require_auth();
let stored_admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
if admin != stored_admin {
panic!("caller is not admin");
}
env.storage()
.instance()
.set(&DataKey::FeeRecipient, &recipient);
}
/// Returns the current platform fee in basis points. Defaults to
/// [`DEFAULT_PLATFORM_FEE_BPS`] (50) when not explicitly configured.
pub fn get_platform_fee_bps(env: Env) -> i128 {
env.storage()
.instance()
.get(&DataKey::PlatformFeeBps)
.unwrap_or(DEFAULT_PLATFORM_FEE_BPS)
}
/// Returns the fee recipient address, or `None` if not set.
pub fn get_fee_recipient(env: Env) -> Option<Address> {
env.storage().instance().get(&DataKey::FeeRecipient)
}
/// Creator can cancel an active campaign, allowing contributors to refund.
pub fn cancel_campaign(env: Env, campaign_id: u64, creator: Address) {
require_not_paused(&env);
creator.require_auth();
let mut campaign = read_campaign(&env, campaign_id);
if campaign.creator != creator {
panic!("creator mismatch");
}
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign already canceled");
}
campaign.canceled = true;
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Cancel")),
CampaignCanceled { campaign_id, creator },
);
}
pub fn create_campaign(
env: Env,
creator: Address,
accepted_tokens: Vec<Address>,
target_amount: i128,
deadline: u64,
metadata: String,
max_per_contributor: i128,
) -> u64 {
creator.require_auth();
if target_amount <= 0 {
panic!("target amount must be positive");
}
if deadline <= env.ledger().timestamp() {
panic!("deadline must be in the future");
}
if deadline - env.ledger().timestamp() > MAX_CAMPAIGN_DURATION_SECONDS {
panic!("deadline exceeds maximum campaign duration");
}
if accepted_tokens.len() == 0 {
panic!("accepted_tokens must not be empty");
}
let mut i = 0;
while i < accepted_tokens.len() {
let mut j = i + 1;
while j < accepted_tokens.len() {
if accepted_tokens.get(i).unwrap() == accepted_tokens.get(j).unwrap() {
panic!("duplicate token addresses");
}
j += 1;
}
i += 1;
}
if accepted_tokens.len() > MAX_ACCEPTED_TOKENS {
panic!("too many accepted tokens");
}
if max_per_contributor < 0 {
panic!("max_per_contributor must not be negative");
}
let mut next_id: u64 = env
.storage()
.persistent()
.get(&DataKey::NextCampaignId)
.unwrap_or(0);
next_id += 1;
let created_at = env.ledger().timestamp();
let campaign = Campaign {
creator: creator.clone(),
accepted_tokens: accepted_tokens.clone(),
target_amount,
pledged_amount: 0,
deadline,
claimed: false,
canceled: false,
metadata: metadata.clone(),
contributor_count: 0,
created_at,
};
env.storage()
.persistent()
.set(&DataKey::NextCampaignId, &next_id);
env.storage()
.persistent()
.set(&DataKey::Campaign(next_id), &campaign);
// Store the per-contributor cap only when a positive limit is set.
// Absent key is equivalent to cap == 0 (no limit).
if max_per_contributor > 0 {
env.storage()
.persistent()
.set(&DataKey::ContributorCap(next_id), &max_per_contributor);
}
// For backward compatibility, publish the first token in the event
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Create")),
CampaignCreated {
campaign_id: next_id,
creator,
token: accepted_tokens.get(0).unwrap(),
target_amount,
deadline,
metadata,
},
);
next_id
}
pub fn contribute(env: Env, campaign_id: u64, contributor: Address, token: Address, amount: i128) {
require_not_paused(&env);
contributor.require_auth();
let min_contribution: i128 = env
.storage()
.instance()
.get(&DataKey::MinContribution)
.unwrap_or(MIN_CONTRIBUTION);
if amount < min_contribution {
panic!("contribution below minimum");
}
let mut campaign = read_campaign(&env, campaign_id);
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign canceled");
}
if env.ledger().timestamp() >= campaign.deadline {
panic!("campaign deadline reached");
}
if campaign.pledged_amount + amount > campaign.target_amount {
panic!("campaign funding cap exceeded");
}
if !campaign.accepted_tokens.iter().any(|t| t == token) {
panic!("token not accepted by this campaign");
}
let token_client = TokenClient::new(&env, &token);
let contract_address = env.current_contract_address();
token_client.transfer(&contributor, &contract_address, &amount);
// Update campaign pledged amount (valuation)
campaign.pledged_amount += amount;
// Only increment contributor_count on first-time pledge
let has_contributed_key = DataKey::HasContributed(campaign_id, contributor.clone());
let has_contributed: bool = env.storage().persistent().get(&has_contributed_key).unwrap_or(false);
if !has_contributed {
campaign.contributor_count += 1;
env.storage().persistent().set(&has_contributed_key, &true);
// Track contributor for refund_all
let contributors_key = DataKey::Contributors(campaign_id);
let mut contributors: Vec<Address> = env.storage().persistent().get(&contributors_key).unwrap_or_else(|| Vec::new(&env));
contributors.push_back(contributor.clone());
env.storage().persistent().set(&contributors_key, &contributors);
}
// Write updated campaign back to storage
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
let balance_key = DataKey::CampaignTokenBalance(campaign_id, token.clone());
let current_balance: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0);
env.storage()
.persistent()
.set(&balance_key, &(current_balance + amount));
let contribution_key = DataKey::Contribution(campaign_id, contributor.clone(), token.clone());
let current_contribution: i128 = env.storage().persistent().get(&contribution_key).unwrap_or(0);
env.storage()
.persistent()
.set(&contribution_key, &(current_contribution + amount));
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Pledge")),
CampaignPledged {
campaign_id,
contributor,
token,
amount,
},
);
}
/// Updates the campaign metadata. Only the original creator can call this,
/// and only before the campaign deadline. Emits a MetadataUpdated event
/// containing both old and new values (issue #185).
pub fn update_metadata(env: Env, campaign_id: u64, creator: Address, new_metadata: String) {
require_not_paused(&env);
creator.require_auth();
let mut campaign = read_campaign(&env, campaign_id);
if campaign.creator != creator {
panic!("creator mismatch");
}
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign canceled");
}
if env.ledger().timestamp() >= campaign.deadline {
panic!("campaign deadline reached");
}
let old_metadata = campaign.metadata.clone();
campaign.metadata = new_metadata.clone();
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("MetaUpd")),
MetadataUpdated {
campaign_id,
creator,
old_metadata,
new_metadata,
},
);
}
/// Requests a deadline extension for a campaign. The caller must be an
/// existing contributor. The requester auto-approves their own request.
/// new_deadline must be later than the current deadline and within
/// MAX_CAMPAIGN_DURATION_SECONDS of the campaign's creation (issue #192).
pub fn request_deadline_extension(
env: Env,
campaign_id: u64,
caller: Address,
new_deadline: u64,
) {
require_not_paused(&env);
caller.require_auth();
let campaign = read_campaign(&env, campaign_id);
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign canceled");
}
if new_deadline <= campaign.deadline {
panic!("new deadline must be after current deadline");
}
if new_deadline > campaign.created_at + MAX_CAMPAIGN_DURATION_SECONDS {
panic!("new deadline exceeds maximum campaign duration");
}
// Caller must be a contributor
let is_contributor = campaign.accepted_tokens.iter().any(|token| {
let key = DataKey::Contribution(campaign_id, caller.clone(), token.clone());
let amount: i128 = env.storage().persistent().get(&key).unwrap_or(0);
amount > 0
});
if !is_contributor {
panic!("caller is not a contributor");
}
let request = ExtensionRequest {
new_deadline,
requested_by: caller.clone(),
approval_count: 1, // requester auto-approves
};
env.storage()
.persistent()
.set(&DataKey::ExtensionRequest(campaign_id), &request);
// Mark requester as having voted
env.storage()
.persistent()
.set(&DataKey::ExtensionVote(campaign_id, caller.clone()), &true);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("ExtReq")),
ExtensionRequested {
campaign_id,
requested_by: caller,
new_deadline,
},
);
}
/// Votes to approve a pending deadline extension. The caller must be an
/// existing contributor and must not have already voted. When approvals
/// exceed 50% of the contributor count, the new deadline is applied and
/// the pending request is cleared (issue #192).
pub fn approve_extension(env: Env, campaign_id: u64, caller: Address) {
require_not_paused(&env);
caller.require_auth();
let mut campaign = read_campaign(&env, campaign_id);
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign canceled");
}
// Caller must be a contributor
let is_contributor = campaign.accepted_tokens.iter().any(|token| {
let key = DataKey::Contribution(campaign_id, caller.clone(), token.clone());
let amount: i128 = env.storage().persistent().get(&key).unwrap_or(0);
amount > 0
});
if !is_contributor {
panic!("caller is not a contributor");
}
let vote_key = DataKey::ExtensionVote(campaign_id, caller.clone());
let already_voted: bool = env.storage().persistent().get(&vote_key).unwrap_or(false);
if already_voted {
panic!("already voted");
}
let request_key = DataKey::ExtensionRequest(campaign_id);
let mut request: ExtensionRequest = env
.storage()
.persistent()
.get(&request_key)
.unwrap_or_else(|| panic!("no extension request"));
env.storage().persistent().set(&vote_key, &true);
request.approval_count += 1;
// Majority threshold: approval_count * 2 > contributor_count
if campaign.contributor_count > 0 && request.approval_count * 2 > campaign.contributor_count {
campaign.deadline = request.new_deadline;
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
env.storage().persistent().remove(&request_key);
} else {
env.storage().persistent().set(&request_key, &request);
}
}
/// Returns the pending extension request for a campaign, if one exists.
pub fn get_extension_request(env: Env, campaign_id: u64) -> Option<ExtensionRequest> {
env.storage()
.persistent()
.get(&DataKey::ExtensionRequest(campaign_id))
}
pub fn claim(env: Env, campaign_id: u64, creator: Address) {
require_not_paused(&env);
creator.require_auth();
let mut campaign = read_campaign(&env, campaign_id);
if campaign.creator != creator {
panic!("creator mismatch");
}
if campaign.claimed {
panic!("campaign already claimed");
}
if campaign.canceled {
panic!("campaign canceled");
}
if env.ledger().timestamp() < campaign.deadline {
panic!("campaign is still active");
}
if campaign.pledged_amount < campaign.target_amount {
panic!("campaign is not funded");
}
campaign.claimed = true;
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
let contract_address = env.current_contract_address();
let fee_bps: i128 = env
.storage()
.instance()
.get(&DataKey::PlatformFeeBps)
.unwrap_or(DEFAULT_PLATFORM_FEE_BPS);
let fee_recipient: Option<Address> = env.storage().instance().get(&DataKey::FeeRecipient);
let take_fee = fee_bps > 0;
for token in campaign.accepted_tokens.iter() {
let balance_key = DataKey::CampaignTokenBalance(campaign_id, token.clone());
let balance: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0);
if balance > 0 {
let token_client = TokenClient::new(&env, &token);
if take_fee {
if let Some(ref recipient) = fee_recipient {
let fee_amount = balance * fee_bps / 10000;
let creator_amount = balance - fee_amount;
if fee_amount > 0 {
token_client.transfer(&contract_address, recipient, &fee_amount);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Fee")),
FeeCollected {
campaign_id,
token: token.clone(),
fee_amount,
fee_recipient: recipient.clone(),
},
);
}
token_client.transfer(&contract_address, &creator, &creator_amount);
} else {
token_client.transfer(&contract_address, &creator, &balance);
}
} else {
token_client.transfer(&contract_address, &creator, &balance);
}
// Clear the balance
env.storage().persistent().set(&balance_key, &0_i128);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Claim")),
CampaignClaimed {
campaign_id,
creator: creator.clone(),
token: token.clone(),
amount: balance,
},
);
}
}
}
pub fn refund(env: Env, campaign_id: u64, contributor: Address) {
require_not_paused(&env);
contributor.require_auth();
let mut campaign = read_campaign(&env, campaign_id);
if campaign.claimed {
panic!("campaign already claimed");
}
if !campaign.canceled && env.ledger().timestamp() < campaign.deadline {
panic!("campaign is still active");
}
if !campaign.canceled && campaign.pledged_amount >= campaign.target_amount {
panic!("funded campaigns cannot be refunded");
}
let total_refunded = refund_contributor(&env, &mut campaign, campaign_id, &contributor);
if total_refunded == 0 {
panic!("nothing to refund");
}
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
}
pub fn refund_all(env: Env, campaign_id: u64) {
require_not_paused(&env);
let mut campaign = read_campaign(&env, campaign_id);
if campaign.claimed {
panic!("campaign already claimed");
}
if !campaign.canceled && env.ledger().timestamp() < campaign.deadline {
panic!("campaign is still active");
}
if !campaign.canceled && campaign.pledged_amount >= campaign.target_amount {
panic!("funded campaigns cannot be refunded");
}
let contributors_key = DataKey::Contributors(campaign_id);
let contributors: Vec<Address> = env
.storage()
.persistent()
.get(&contributors_key)
.unwrap_or_else(|| Vec::new(&env));
let mut any_refunded = false;
for contributor in contributors.iter() {
let refunded = refund_contributor(&env, &mut campaign, campaign_id, &contributor);
if refunded > 0 {
any_refunded = true;
}
}
if !any_refunded {
panic!("nothing to refund");
}
env.storage()
.persistent()
.set(&DataKey::Campaign(campaign_id), &campaign);
}
pub fn get_campaign(env: Env, campaign_id: u64) -> Campaign {
read_campaign(&env, campaign_id)
}
pub fn get_contribution(env: Env, campaign_id: u64, contributor: Address, token: Address) -> i128 {
env.storage()
.persistent()
.get(&DataKey::Contribution(campaign_id, contributor, token))
.unwrap_or(0)
}
pub fn get_campaign_token_balance(env: Env, campaign_id: u64, token: Address) -> i128 {
env.storage()
.persistent()
.get(&DataKey::CampaignTokenBalance(campaign_id, token))
.unwrap_or(0)
}
pub fn get_contributor_count(env: Env, campaign_id: u64) -> u32 {
read_campaign(&env, campaign_id).contributor_count
}
pub fn get_next_campaign_id(env: Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::NextCampaignId)
.unwrap_or(0)
}
/// Returns how many campaigns have been created. Uses the same counter as
/// [`Self::get_next_campaign_id`] ([`DataKey::NextCampaignId`]): sequential ids `1..=count`.
pub fn get_campaign_count(env: Env) -> u64 {
Self::get_next_campaign_id(env)
}
pub fn get_version(env: Env) -> String {
let stored_version: Option<String> =
env.storage().instance().get(&DataKey::ContractVersion);
match stored_version {
Some(version) => version,
None => {
let version = String::from_str(&env, CONTRACT_VERSION);
env.storage()
.instance()
.set(&DataKey::ContractVersion, &version);
version
}
}
}
/// Migrate campaign records from an old contract instance to this one.
///
/// Only the admin may call this. Already-migrated source IDs (tracked per
/// `old_contract_id`) are silently skipped (idempotent). A `Migrated`
/// event is emitted for each campaign that is newly imported.
///
/// `source_ids` – original campaign IDs from the old contract (used as
/// dedup keys; must have the same length as `campaigns`).
/// `campaigns` – the campaign structs pre-fetched from the old contract
/// by the admin off-chain before calling this function.
pub fn migrate(
env: Env,
admin: Address,
old_contract_id: Address,
source_ids: Vec<u64>,
campaigns: Vec<Campaign>,
) {
admin.require_auth();
let stored_admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.expect("not initialized");
assert!(admin == stored_admin, "only admin can call migrate");
assert!(
source_ids.len() == campaigns.len(),
"source_ids and campaigns must have the same length"
);
for i in 0..source_ids.len() {
let source_id = source_ids.get(i).unwrap();
let migration_key = DataKey::MigratedId(old_contract_id.clone(), source_id);
if env.storage().persistent().has(&migration_key) {
continue; // already migrated — skip
}
let campaign = campaigns.get(i).unwrap();
let next_id: u64 = env
.storage()
.persistent()
.get(&DataKey::NextCampaignId)
.unwrap_or(0);
env.storage()
.persistent()
.set(&DataKey::Campaign(next_id), &campaign);
env.storage()
.persistent()
.set(&DataKey::NextCampaignId, &(next_id + 1));
// Mark as migrated so this call is idempotent
env.storage().persistent().set(&migration_key, &true);
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Migrated")),
(old_contract_id.clone(), source_id, next_id),
);
}
}
pub fn get_deploy_info(env: Env) -> DeployInfo {
let version = Self::get_version(env.clone());
let deployed_at: u64 = match env.storage().instance().get(&DataKey::DeploymentTimestamp) {
Some(ts) => ts,
None => {
let ts = env.ledger().timestamp();
env.storage().instance().set(&DataKey::DeploymentTimestamp, &ts);
ts
}
};
DeployInfo {
version,
deployed_at,
}
}
}
fn require_not_paused(env: &Env) {
if env
.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
{
panic!("contract is paused");
}
}
fn read_campaign(env: &Env, campaign_id: u64) -> Campaign {
env.storage()
.persistent()
.get(&DataKey::Campaign(campaign_id))
.unwrap_or_else(|| panic!("campaign not found"))
}
fn refund_contributor(
env: &Env,
campaign: &mut Campaign,
campaign_id: u64,
contributor: &Address,
) -> i128 {
let mut total_refunded = 0_i128;
let contract_address = env.current_contract_address();
for token in campaign.accepted_tokens.iter() {
let contribution_key =
DataKey::Contribution(campaign_id, contributor.clone(), token.clone());
let amount: i128 = env.storage().persistent().get(&contribution_key).unwrap_or(0);
if amount > 0 {
let token_client = TokenClient::new(env, &token);
token_client.transfer(&contract_address, contributor, &amount);
env.storage().persistent().set(&contribution_key, &0_i128);
let balance_key = DataKey::CampaignTokenBalance(campaign_id, token.clone());
let balance: i128 = env.storage().persistent().get(&balance_key).unwrap_or(0);
env.storage()
.persistent()
.set(&balance_key, &(balance - amount));
campaign.pledged_amount -= amount;
total_refunded += amount;
env.events().publish(
(symbol_short!("Goal"), symbol_short!("Refund")),
CampaignRefunded {
campaign_id,
contributor: contributor.clone(),
token: token.clone(),
amount,
},
);
}
}
total_refunded
}