Skip to main content

crowdfunding_neo/
lib.rs

1use core::slice;
2use neo_devpack::serde::{Deserialize, Serialize};
3use neo_devpack::{codec, prelude::*};
4
5const CAMPAIGN_KEY: &[u8] = b"crowd:campaign";
6const CONTRIBUTION_PREFIX: &[u8] = b"crowd:contrib:";
7
8#[derive(Clone, Serialize, Deserialize)]
9struct Campaign {
10    owner: NeoByteString,
11    token: NeoByteString,
12    target: i64,
13    deadline: i64,
14    total_raised: i64,
15    finalized: bool,
16    successful: bool,
17}
18
19neo_manifest_overlay!(
20    r#"{
21    "name": "NeoCrowdfund",
22    "supportedstandards": ["NEP-17"],
23    "features": { "storage": true }
24}"#
25);
26
27#[neo_event]
28pub struct CampaignConfigured {
29    pub owner: NeoByteString,
30    pub target: NeoInteger,
31    pub deadline: NeoInteger,
32}
33
34#[neo_event]
35pub struct ContributionReceived {
36    pub contributor: NeoByteString,
37    pub amount: NeoInteger,
38    pub total_raised: NeoInteger,
39}
40
41#[neo_event]
42pub struct CampaignFinalized {
43    pub successful: NeoBoolean,
44    pub total_raised: NeoInteger,
45}
46
47#[neo_event]
48pub struct RefundIssued {
49    pub contributor: NeoByteString,
50    pub amount: NeoInteger,
51}
52
53#[no_mangle]
54#[neo_safe]
55#[allow(improper_ctypes_definitions)]
56pub extern "C" fn getCampaign() -> NeoByteString {
57    storage_context()
58        .and_then(|ctx| load_campaign(&ctx))
59        .map(|campaign| serialize_value(&campaign))
60        .unwrap_or_else(|| NeoByteString::new(Vec::new()))
61}
62
63#[no_mangle]
64#[neo_safe]
65pub extern "C" fn contributionOf(address_ptr: i64, address_len: i64) -> i64 {
66    let Some(ctx) = storage_context() else {
67        return 0;
68    };
69    let Some(address) = read_address(address_ptr, address_len) else {
70        return 0;
71    };
72    load_contribution(&ctx, &address)
73}
74
75#[no_mangle]
76pub extern "C" fn configure(
77    owner_ptr: i64,
78    owner_len: i64,
79    token_ptr: i64,
80    token_len: i64,
81    target: i64,
82    deadline: i64,
83) -> i64 {
84    if target <= 0 || deadline <= 0 {
85        return 0;
86    }
87
88    let Some(ctx) = storage_context() else {
89        return 0;
90    };
91    if load_campaign(&ctx).is_some() {
92        return 0;
93    }
94
95    let Some(owner) = read_address(owner_ptr, owner_len) else {
96        return 0;
97    };
98    if !ensure_witness(&owner) {
99        return 0;
100    }
101    let Some(token) = read_address(token_ptr, token_len) else {
102        return 0;
103    };
104    if addresses_equal(&owner, &token) {
105        return 0;
106    }
107
108    let campaign = Campaign {
109        owner: owner.clone(),
110        token: token.clone(),
111        target,
112        deadline,
113        total_raised: 0,
114        finalized: false,
115        successful: false,
116    };
117
118    if store_campaign(&ctx, &campaign).is_err() {
119        return 0;
120    }
121
122    CampaignConfigured {
123        owner,
124        target: NeoInteger::new(target),
125        deadline: NeoInteger::new(deadline),
126    }
127    .emit()
128    .ok();
129
130    1
131}
132
133#[no_mangle]
134pub extern "C" fn finalize(current_time: i64) -> i64 {
135    let Some(ctx) = storage_context() else {
136        return 0;
137    };
138    let Some(mut campaign) = load_campaign(&ctx) else {
139        return 0;
140    };
141    if campaign.finalized {
142        return 0;
143    }
144
145    if current_time < campaign.deadline {
146        return 0;
147    }
148    if campaign.total_raised < campaign.target {
149        return 0;
150    }
151
152    let successful = campaign.total_raised >= campaign.target;
153    if successful {
154        let contract_hash = match NeoRuntime::get_executing_script_hash() {
155            Ok(hash) => hash,
156            Err(_) => return 0,
157        };
158        if !call_transfer(
159            &campaign.token,
160            &contract_hash,
161            &campaign.owner,
162            campaign.total_raised,
163        ) {
164            return 0;
165        }
166    }
167
168    campaign.finalized = true;
169    campaign.successful = successful;
170
171    if store_campaign(&ctx, &campaign).is_err() {
172        return 0;
173    }
174
175    CampaignFinalized {
176        successful: NeoBoolean::new(successful),
177        total_raised: NeoInteger::new(campaign.total_raised),
178    }
179    .emit()
180    .ok();
181
182    1
183}
184
185#[no_mangle]
186pub extern "C" fn claimRefund(contrib_ptr: i64, contrib_len: i64) -> i64 {
187    let Some(ctx) = storage_context() else {
188        return 0;
189    };
190    let Some(campaign) = load_campaign(&ctx) else {
191        return 0;
192    };
193    if !campaign.finalized || campaign.successful {
194        return 0;
195    }
196
197    let Some(contributor) = read_address(contrib_ptr, contrib_len) else {
198        return 0;
199    };
200    if !ensure_witness(&contributor) {
201        return 0;
202    }
203
204    let amount = load_contribution(&ctx, &contributor);
205    if amount <= 0 {
206        return 0;
207    }
208
209    let contract_hash = match NeoRuntime::get_executing_script_hash() {
210        Ok(hash) => hash,
211        Err(_) => return 0,
212    };
213
214    if !call_transfer(&campaign.token, &contract_hash, &contributor, amount) {
215        return 0;
216    }
217
218    if delete_contribution(&ctx, &contributor).is_err() {
219        return 0;
220    }
221
222    RefundIssued {
223        contributor,
224        amount: NeoInteger::new(amount),
225    }
226    .emit()
227    .ok();
228
229    1
230}
231
232#[allow(improper_ctypes_definitions)]
233#[no_mangle]
234pub extern "C" fn onNEP17Payment(from: NeoByteString, amount: i64, data: NeoByteString) {
235    if amount <= 0 {
236        return;
237    }
238
239    let Some(ctx) = storage_context() else {
240        return;
241    };
242    let Some(mut campaign) = load_campaign(&ctx) else {
243        return;
244    };
245    if campaign.finalized {
246        return;
247    }
248
249    let Ok(call_hash) = NeoRuntime::get_calling_script_hash() else {
250        return;
251    };
252    if !addresses_equal(&call_hash, &campaign.token) {
253        return;
254    }
255
256    if !data.is_empty() && data.as_slice() != b"contribute" {
257        return;
258    }
259
260    let new_total = match campaign.total_raised.checked_add(amount) {
261        Some(value) => value,
262        None => return,
263    };
264    campaign.total_raised = new_total;
265
266    let existing = load_contribution(&ctx, &from);
267    if store_contribution(&ctx, &from, existing + amount).is_err() {
268        return;
269    }
270
271    if store_campaign(&ctx, &campaign).is_err() {
272        return;
273    }
274
275    ContributionReceived {
276        contributor: from,
277        amount: NeoInteger::new(amount),
278        total_raised: NeoInteger::new(new_total),
279    }
280    .emit()
281    .ok();
282}
283
284fn storage_context() -> Option<NeoStorageContext> {
285    NeoStorage::get_context().ok()
286}
287
288fn load_campaign(ctx: &NeoStorageContext) -> Option<Campaign> {
289    load_from_storage(ctx, CAMPAIGN_KEY)
290}
291
292fn store_campaign(ctx: &NeoStorageContext, campaign: &Campaign) -> NeoResult<()> {
293    store_to_storage(ctx, CAMPAIGN_KEY, campaign)
294}
295
296fn contribution_key(address: &NeoByteString) -> Vec<u8> {
297    let mut key = CONTRIBUTION_PREFIX.to_vec();
298    key.extend_from_slice(address.as_slice());
299    key
300}
301
302fn load_contribution(ctx: &NeoStorageContext, address: &NeoByteString) -> i64 {
303    load_from_storage(ctx, &contribution_key(address)).unwrap_or(0i64)
304}
305
306fn store_contribution(
307    ctx: &NeoStorageContext,
308    address: &NeoByteString,
309    amount: i64,
310) -> NeoResult<()> {
311    store_to_storage(ctx, &contribution_key(address), &amount)
312}
313
314fn delete_contribution(ctx: &NeoStorageContext, address: &NeoByteString) -> NeoResult<()> {
315    let key = NeoByteString::from_slice(&contribution_key(address));
316    NeoStorage::delete(ctx, &key)
317}
318
319fn read_address(ptr: i64, len: i64) -> Option<NeoByteString> {
320    let bytes = read_bytes(ptr, len)?;
321    if bytes.len() != 20 {
322        return None;
323    }
324    Some(NeoByteString::from_slice(&bytes))
325}
326
327/// Reads bytes from a raw pointer.
328///
329/// # Safety
330///
331/// The caller must ensure that:
332/// - `ptr` is a valid, non-null pointer allocated by the NeoVM runtime
333/// - `len` bytes starting at `ptr` are valid for reads
334///
335/// These invariants are guaranteed when called from NeoVM contract entry points.
336fn read_bytes(ptr: i64, len: i64) -> Option<Vec<u8>> {
337    if ptr == 0 || len <= 0 {
338        return None;
339    }
340    let len = len as usize;
341    // SAFETY: We've validated ptr is non-null and len is positive.
342    // The pointer validity is guaranteed by the NeoVM runtime.
343    let slice = unsafe { slice::from_raw_parts(ptr as *const u8, len) };
344    Some(slice.to_vec())
345}
346
347fn ensure_witness(account: &NeoByteString) -> bool {
348    NeoRuntime::check_witness(account)
349        .map(|flag| flag.as_bool())
350        .unwrap_or(false)
351}
352
353fn addresses_equal(left: &NeoByteString, right: &NeoByteString) -> bool {
354    left.as_slice() == right.as_slice()
355}
356
357fn call_transfer(
358    token: &NeoByteString,
359    from: &NeoByteString,
360    to: &NeoByteString,
361    amount: i64,
362) -> bool {
363    let mut args = NeoArray::new();
364    args.push(NeoValue::from(from.clone()));
365    args.push(NeoValue::from(to.clone()));
366    args.push(NeoValue::from(NeoInteger::new(amount)));
367
368    match NeoContractRuntime::call(token, &NeoString::from_str("transfer"), &args) {
369        Ok(value) => value
370            .as_boolean()
371            .map(|flag| flag.as_bool())
372            .unwrap_or(false),
373        Err(_) => false,
374    }
375}
376
377fn load_from_storage<T>(ctx: &NeoStorageContext, key: &[u8]) -> Option<T>
378where
379    T: for<'de> Deserialize<'de>,
380{
381    let key_bytes = NeoByteString::from_slice(key);
382    let data = NeoStorage::get(ctx, &key_bytes).ok()?;
383    if data.is_empty() {
384        return None;
385    }
386    codec::deserialize(data.as_slice()).ok()
387}
388
389fn store_to_storage<T>(ctx: &NeoStorageContext, key: &[u8], value: &T) -> NeoResult<()>
390where
391    T: Serialize,
392{
393    let encoded = codec::serialize(value)?;
394    let key_bytes = NeoByteString::from_slice(key);
395    let value_bytes = NeoByteString::from_slice(&encoded);
396    NeoStorage::put(ctx, &key_bytes, &value_bytes)
397}
398
399fn serialize_value<T: Serialize>(value: &T) -> NeoByteString {
400    match codec::serialize(value) {
401        Ok(bytes) => NeoByteString::from_slice(&bytes),
402        Err(_) => NeoByteString::new(Vec::new()),
403    }
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use std::sync::{Mutex, OnceLock};
410
411    fn test_lock() -> &'static Mutex<()> {
412        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
413        LOCK.get_or_init(|| Mutex::new(()))
414    }
415
416    fn address(byte: u8) -> Vec<u8> {
417        vec![byte; 20]
418    }
419
420    fn reset_state() {
421        let ctx = storage_context().unwrap();
422        NeoStorage::delete(&ctx, &NeoByteString::from_slice(CAMPAIGN_KEY)).ok();
423        if let Ok(iter) = NeoStorage::find(&ctx, &NeoByteString::from_slice(CONTRIBUTION_PREFIX)) {
424            let mut iterator = iter;
425            while iterator.has_next() {
426                if let Some(entry) = iterator.next() {
427                    if let Some(key) = entry
428                        .as_struct()
429                        .and_then(|st| st.get_field("key"))
430                        .and_then(NeoValue::as_byte_string)
431                    {
432                        NeoStorage::delete(&ctx, &key).ok();
433                    }
434                }
435            }
436        }
437    }
438
439    fn configure_sample(target: i64, deadline: i64) -> Campaign {
440        reset_state();
441        let owner = address(0x44);
442        let token = address(0x00);
443
444        let status = configure(
445            owner.as_ptr() as i64,
446            owner.len() as i64,
447            token.as_ptr() as i64,
448            token.len() as i64,
449            target,
450            deadline,
451        );
452        assert_eq!(status, 1);
453
454        let campaign_bytes = getCampaign();
455        codec::deserialize(campaign_bytes.as_slice()).expect("campaign decode")
456    }
457
458    #[test]
459    fn configure_and_view_campaign() {
460        let _guard = test_lock().lock().unwrap();
461        let campaign = configure_sample(1_000, 100);
462        assert_eq!(campaign.target, 1_000);
463        assert_eq!(campaign.total_raised, 0);
464    }
465
466    #[test]
467    fn contribution_updates_total() {
468        let _guard = test_lock().lock().unwrap();
469        let campaign = configure_sample(1_000, 100);
470        let ctx = storage_context().unwrap();
471        let contributor = campaign.owner.clone();
472
473        onNEP17Payment(contributor.clone(), 400, NeoByteString::new(Vec::new()));
474
475        let updated = load_campaign(&ctx).unwrap();
476        assert_eq!(updated.total_raised, 400);
477        assert_eq!(load_contribution(&ctx, &contributor), 400);
478    }
479
480    #[test]
481    fn finalize_successful_campaign() {
482        let _guard = test_lock().lock().unwrap();
483        let campaign = configure_sample(500, 100);
484        let ctx = storage_context().unwrap();
485        let contributor = campaign.owner.clone();
486        onNEP17Payment(contributor, 600, NeoByteString::new(Vec::new()));
487
488        let status = finalize(0);
489        assert_eq!(status, 1);
490
491        let stored = load_campaign(&ctx).unwrap();
492        assert!(stored.finalized);
493        assert!(stored.successful);
494    }
495
496    #[test]
497    fn refunds_after_failed_campaign() {
498        let _guard = test_lock().lock().unwrap();
499        let campaign = configure_sample(800, 10);
500        let ctx = storage_context().unwrap();
501        let contributor = campaign.owner.clone();
502        onNEP17Payment(contributor.clone(), 300, NeoByteString::new(Vec::new()));
503
504        assert_eq!(finalize(10), 1);
505        let stored = load_campaign(&ctx).unwrap();
506        assert!(stored.finalized);
507        assert!(!stored.successful);
508
509        let contributor_bytes = contributor.as_slice().to_vec();
510        assert_eq!(
511            claimRefund(
512                contributor_bytes.as_ptr() as i64,
513                contributor_bytes.len() as i64
514            ),
515            1
516        );
517        assert_eq!(load_contribution(&ctx, &contributor), 0);
518    }
519}