diff --git a/aptos-move/move-examples/claim/Move.toml b/aptos-move/move-examples/claim/Move.toml new file mode 100644 index 00000000000000..c1210acadcd065 --- /dev/null +++ b/aptos-move/move-examples/claim/Move.toml @@ -0,0 +1,9 @@ +[package] +name = "claim" +version = "0.0.0" + +[addresses] +claim = "_" + +[dependencies] +AptosStdlib = { local = "../../framework/aptos-stdlib" } diff --git a/aptos-move/move-examples/claim/sources/claim.move b/aptos-move/move-examples/claim/sources/claim.move new file mode 100644 index 00000000000000..b7af96911d3091 --- /dev/null +++ b/aptos-move/move-examples/claim/sources/claim.move @@ -0,0 +1,39 @@ +/// Module to allow efficiently check and claim spots in a limited claim list. +/// Developers can include this module in their application and just need to: +/// 1. Change the package name to their own package name. +/// 2. Add friend declarations for modules that need to depend on the claim_list module. +/// 3. Call is_claimed and claim functions in their own code. +module claim::claim_list { + use aptos_std::smart_table::{Self, SmartTable}; + + // Add friend declarations for modules that need to depend on claim_list. + + struct ClaimList has key { + // Key can also be replaced with address if the claim_list is tracked by user addresses. + codes_claimed: SmartTable, + } + + fun init_module(claim_list_signer: &signer) { + move_to(claim_list_signer, ClaimList { + codes_claimed: smart_table::new(), + }); + } + + public fun is_claimed(invite_code: u64): bool acquires ClaimList { + let codes_claimed = &borrow_global(@claim).codes_claimed; + smart_table::contains(codes_claimed, invite_code) + } + + public(friend) fun claim(invite_code: u64) acquires ClaimList { + let codes_claimed = &mut borrow_global_mut(@claim).codes_claimed; + smart_table::add(codes_claimed, invite_code, true); + } + + #[test_only] + friend claim::test_claim; + + #[test_only] + public fun init_for_test(claim: &signer) { + init_module(claim); + } +} diff --git a/aptos-move/move-examples/claim/sources/tests/test_claim.move b/aptos-move/move-examples/claim/sources/tests/test_claim.move new file mode 100644 index 00000000000000..f274d4b2a2ffd0 --- /dev/null +++ b/aptos-move/move-examples/claim/sources/tests/test_claim.move @@ -0,0 +1,12 @@ +#[test_only] +module claim::test_claim { + use claim::claim_list; + + #[test(claim = @0xcafe)] + fun test_claim(claim: &signer) { + claim_list::init_for_test(claim); + assert!(!claim_list::is_claimed(1), 0); + claim_list::claim(1); + assert!(claim_list::is_claimed(1), 1); + } +}