diff --git a/Cargo.toml b/Cargo.toml index 4116214..c6c06d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -118,6 +118,7 @@ members = [ "contracts/token_streaming", "contracts/unlock_keys", "contracts/circuit_breaker", + "contracts/attendance_nft", ] [workspace.dependencies] diff --git a/contracts/attendance_nft/Cargo.toml b/contracts/attendance_nft/Cargo.toml new file mode 100644 index 0000000..4152418 --- /dev/null +++ b/contracts/attendance_nft/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "attendance-nft" +version = "0.1.0" +edition = "2021" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +soroban-sdk = { workspace = true } + +[dev-dependencies] +soroban-sdk = { workspace = true, features = ["testutils"] } + +[features] +testutils = ["soroban-sdk/testutils"] diff --git a/contracts/attendance_nft/src/lib.rs b/contracts/attendance_nft/src/lib.rs new file mode 100644 index 0000000..9729519 --- /dev/null +++ b/contracts/attendance_nft/src/lib.rs @@ -0,0 +1,308 @@ +#![no_std] + +use soroban_sdk::{ + contract, contractimpl, contracttype, symbol_short, Address, Env, String, Vec, +}; + +#[cfg(test)] +mod test; + +// ─── Storage Keys ───────────────────────────────────────────────────────────── + +#[contracttype] +#[derive(Clone)] +pub enum DataKey { + /// Singleton admin address. + Admin, + /// Global token / event counters. + Counters, + /// Event metadata keyed by event_id. + Event(u32), + /// Attendance NFT metadata keyed by token_id. + Token(u32), + /// Set of token_ids owned by an address. + OwnerTokens(Address), + /// Guard: has the given (player, event_id) already checked in? + CheckedIn(Address, u32), +} + +// ─── Error Codes ────────────────────────────────────────────────────────────── + +#[contracttype] +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +#[repr(u32)] +pub enum AttendanceError { + AlreadyInitialized = 1, + NotAdmin = 2, + EventNotFound = 3, + WindowNotOpen = 4, + AlreadyCheckedIn = 5, + TransferNotAllowed = 6, + TokenNotFound = 7, + InvalidWindow = 8, +} + +impl From for soroban_sdk::Error { + fn from(e: AttendanceError) -> Self { + soroban_sdk::Error::from_contract_error(e as u32) + } +} + +// ─── Data Structs ───────────────────────────────────────────────────────────── + +/// Global counters kept in instance storage. +#[contracttype] +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Counters { + pub next_event_id: u32, + pub next_token_id: u32, + pub total_supply: u32, +} + +/// An organizer-defined event with a check-in window. +#[contracttype] +#[derive(Clone, Debug)] +pub struct Event { + pub event_id: u32, + pub name: String, + pub window_start: u64, + pub window_end: u64, + pub organizer: Address, +} + +/// Non-transferable attendance NFT. +#[contracttype] +#[derive(Clone, Debug)] +pub struct AttendanceToken { + pub token_id: u32, + pub event_id: u32, + pub owner: Address, + pub checked_in_at: u64, +} + +// ─── Contract ───────────────────────────────────────────────────────────────── + +#[contract] +pub struct AttendanceNFT; + +#[contractimpl] +impl AttendanceNFT { + // ── Initialisation ──────────────────────────────────────────────────────── + + /// Bootstrap the contract with an admin address. + /// Can only be called once. + pub fn initialize(env: Env, admin: Address) { + if env.storage().instance().has(&DataKey::Admin) { + panic!("Already initialized"); + } + + env.storage().instance().set(&DataKey::Admin, &admin); + env.storage().instance().set( + &DataKey::Counters, + &Counters { + next_event_id: 1, + next_token_id: 1, + total_supply: 0, + }, + ); + + env.events() + .publish((symbol_short!("init"),), admin); + } + + // ── Event management ────────────────────────────────────────────────────── + + /// Create a new event with a check-in window. + /// Only the admin (organizer role) may call this. + pub fn create_event( + env: Env, + name: String, + window_start: u64, + window_end: u64, + ) -> u32 { + let admin: Address = env + .storage() + .instance() + .get(&DataKey::Admin) + .expect("Not initialized"); + admin.require_auth(); + + if window_start >= window_end { + panic!("Invalid check-in window"); + } + + let mut counters: Counters = env + .storage() + .instance() + .get(&DataKey::Counters) + .expect("Not initialized"); + + let event_id = counters.next_event_id; + counters.next_event_id += 1; + + let event = Event { + event_id, + name: name.clone(), + window_start, + window_end, + organizer: admin.clone(), + }; + + let key = DataKey::Event(event_id); + env.storage().persistent().set(&key, &event); + env.storage() + .persistent() + .extend_ttl(&key, 100_000, 500_000); + + env.storage().instance().set(&DataKey::Counters, &counters); + + env.events() + .publish((symbol_short!("evt_new"),), (event_id, name)); + + event_id + } + + /// Return event metadata. + pub fn get_event(env: Env, event_id: u32) -> Option { + env.storage() + .persistent() + .get(&DataKey::Event(event_id)) + } + + // ── Check-in ────────────────────────────────────────────────────────────── + + /// Player calls this during the check-in window to receive an attendance + /// NFT. Panics if: + /// - the event does not exist + /// - the current ledger timestamp is outside the window + /// - the caller has already checked in to this event + pub fn check_in(env: Env, player: Address, event_id: u32) -> u32 { + player.require_auth(); + + // Verify event exists + let event: Event = env + .storage() + .persistent() + .get(&DataKey::Event(event_id)) + .expect("Event not found"); + + // Enforce check-in window + let now = env.ledger().timestamp(); + if now < event.window_start || now > event.window_end { + panic!("Check-in window is not open"); + } + + // Prevent double check-in + let guard_key = DataKey::CheckedIn(player.clone(), event_id); + if env.storage().persistent().has(&guard_key) { + panic!("Already checked in"); + } + + // Record check-in guard + env.storage().persistent().set(&guard_key, &true); + env.storage() + .persistent() + .extend_ttl(&guard_key, 100_000, 500_000); + + // Mint the non-transferable attendance token + let mut counters: Counters = env + .storage() + .instance() + .get(&DataKey::Counters) + .expect("Not initialized"); + + let token_id = counters.next_token_id; + counters.next_token_id += 1; + counters.total_supply += 1; + + let token = AttendanceToken { + token_id, + event_id, + owner: player.clone(), + checked_in_at: now, + }; + + let token_key = DataKey::Token(token_id); + env.storage().persistent().set(&token_key, &token); + env.storage() + .persistent() + .extend_ttl(&token_key, 100_000, 500_000); + + // Update owner → token list + let mut owned = Self::get_owned_internal(&env, player.clone()); + owned.push_back(token_id); + let owned_key = DataKey::OwnerTokens(player.clone()); + env.storage().persistent().set(&owned_key, &owned); + env.storage() + .persistent() + .extend_ttl(&owned_key, 100_000, 500_000); + + env.storage().instance().set(&DataKey::Counters, &counters); + + env.events() + .publish((symbol_short!("checkin"),), (event_id, player, token_id)); + + token_id + } + + // ── Transfer — explicitly blocked ───────────────────────────────────────── + + /// Transfer is intentionally disabled; attendance tokens are soulbound. + pub fn transfer(_env: Env, _from: Address, _to: Address, _token_id: u32) { + panic!("Attendance tokens cannot be transferred"); + } + + // ── Query helpers ───────────────────────────────────────────────────────── + + /// Return the attendance token metadata. + pub fn get_token(env: Env, token_id: u32) -> Option { + env.storage() + .persistent() + .get(&DataKey::Token(token_id)) + } + + /// Return the owner of a given token. + pub fn owner_of(env: Env, token_id: u32) -> Address { + let token: AttendanceToken = env + .storage() + .persistent() + .get(&DataKey::Token(token_id)) + .expect("Token not found"); + token.owner + } + + /// Return all token ids owned by an address. + pub fn tokens_of(env: Env, owner: Address) -> Vec { + Self::get_owned_internal(&env, owner) + } + + /// Return whether a player has checked in to a specific event. + pub fn has_checked_in(env: Env, player: Address, event_id: u32) -> bool { + env.storage() + .persistent() + .has(&DataKey::CheckedIn(player, event_id)) + } + + /// Total number of attendance tokens minted across all events. + pub fn total_supply(env: Env) -> u32 { + let counters: Counters = env + .storage() + .instance() + .get(&DataKey::Counters) + .unwrap_or(Counters { + next_event_id: 1, + next_token_id: 1, + total_supply: 0, + }); + counters.total_supply + } + + // ── Internal helpers ────────────────────────────────────────────────────── + + fn get_owned_internal(env: &Env, owner: Address) -> Vec { + env.storage() + .persistent() + .get(&DataKey::OwnerTokens(owner)) + .unwrap_or(Vec::new(env)) + } +} diff --git a/contracts/attendance_nft/src/test.rs b/contracts/attendance_nft/src/test.rs new file mode 100644 index 0000000..d58defe --- /dev/null +++ b/contracts/attendance_nft/src/test.rs @@ -0,0 +1,308 @@ +#![cfg(test)] + +use super::*; +use soroban_sdk::{ + testutils::{Address as _, Ledger}, + Address, Env, String, +}; + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +fn setup() -> (Env, AttendanceNFTClient<'static>, Address) { + let env = Env::default(); + env.mock_all_auths(); + + let contract_id = env.register_contract(None, AttendanceNFT); + let client = AttendanceNFTClient::new(&env, &contract_id); + + let admin = Address::generate(&env); + client.initialize(&admin); + + (env, client, admin) +} + +/// Advance the ledger clock to `ts`. +fn set_time(env: &Env, ts: u64) { + env.ledger().with_mut(|li| li.timestamp = ts); +} + +// ─── Initialisation tests ───────────────────────────────────────────────────── + +#[test] +fn test_initialize_succeeds() { + let (_env, _client, _admin) = setup(); + // If we get here without panicking the initialisation worked. +} + +#[test] +#[should_panic(expected = "Already initialized")] +fn test_double_initialize_panics() { + let (env, client, _admin) = setup(); + let other_admin = Address::generate(&env); + client.initialize(&other_admin); // must panic +} + +// ─── Event creation tests ────────────────────────────────────────────────────── + +#[test] +fn test_create_event_returns_incrementing_ids() { + let (env, client, _admin) = setup(); + + let name1 = String::from_str(&env, "DevCon 2025"); + let name2 = String::from_str(&env, "Hackathon Night"); + + let id1 = client.create_event(&name1, &1000u64, &2000u64); + let id2 = client.create_event(&name2, &3000u64, &4000u64); + + assert_eq!(id1, 1u32); + assert_eq!(id2, 2u32); +} + +#[test] +fn test_get_event_returns_correct_metadata() { + let (env, client, admin) = setup(); + + let name = String::from_str(&env, "Summit"); + let start = 500u64; + let end = 1500u64; + + let event_id = client.create_event(&name, &start, &end); + + let event = client.get_event(&event_id).expect("event should exist"); + assert_eq!(event.event_id, event_id); + assert_eq!(event.name, name); + assert_eq!(event.window_start, start); + assert_eq!(event.window_end, end); + assert_eq!(event.organizer, admin); +} + +#[test] +#[should_panic(expected = "Invalid check-in window")] +fn test_create_event_invalid_window_panics() { + let (env, client, _admin) = setup(); + let name = String::from_str(&env, "Bad Event"); + // start == end → invalid + client.create_event(&name, &1000u64, &1000u64); +} + +#[test] +#[should_panic] +fn test_create_event_requires_admin_auth() { + let (env, _client, _admin) = setup(); + + // Build a *new* client that does NOT mock auths so the require_auth fires. + let env2 = Env::default(); // no mock_all_auths + let contract_id = env2.register_contract(None, AttendanceNFT); + let client2 = AttendanceNFTClient::new(&env2, &contract_id); + let admin2 = Address::generate(&env); + env2.mock_all_auths(); + client2.initialize(&admin2); + + // Now drop mock_all_auths so the next call lacks auth. + // We can't easily "un-mock", so we use a fresh env without mocking. + let env3 = Env::default(); + let contract_id3 = env3.register_contract(None, AttendanceNFT); + let client3 = AttendanceNFTClient::new(&env3, &contract_id3); + // initialize without mocking – require_auth on admin will fire first + client3.initialize(&Address::generate(&env3)); + // create_event without mocking auth → should panic + client3.create_event( + &String::from_str(&env3, "Fail"), + &100u64, + &200u64, + ); +} + +// ─── Check-in tests ─────────────────────────────────────────────────────────── + +#[test] +fn test_checkin_inside_window_mints_token() { + let (env, client, _admin) = setup(); + + let name = String::from_str(&env, "Genesis Event"); + let event_id = client.create_event(&name, &1000u64, &2000u64); + + // Set the clock inside the window + set_time(&env, 1500); + + let player = Address::generate(&env); + let token_id = client.check_in(&player, &event_id); + + assert_eq!(token_id, 1u32); + assert_eq!(client.total_supply(), 1u32); + assert_eq!(client.owner_of(&token_id), player); + + let token = client.get_token(&token_id).expect("token should exist"); + assert_eq!(token.token_id, token_id); + assert_eq!(token.event_id, event_id); + assert_eq!(token.owner, player); + assert_eq!(token.checked_in_at, 1500u64); +} + +#[test] +fn test_checkin_records_guard_flag() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "E"), &100u64, &900u64); + + set_time(&env, 500); + let player = Address::generate(&env); + + assert!(!client.has_checked_in(&player, &event_id)); + client.check_in(&player, &event_id); + assert!(client.has_checked_in(&player, &event_id)); +} + +#[test] +fn test_tokens_of_returns_all_owned_tokens() { + let (env, client, _admin) = setup(); + + let event_id1 = + client.create_event(&String::from_str(&env, "E1"), &100u64, &900u64); + let event_id2 = + client.create_event(&String::from_str(&env, "E2"), &100u64, &900u64); + + set_time(&env, 500); + let player = Address::generate(&env); + + let t1 = client.check_in(&player, &event_id1); + let t2 = client.check_in(&player, &event_id2); + + let owned = client.tokens_of(&player); + assert_eq!(owned.len(), 2); + assert_eq!(owned.get(0).unwrap(), t1); + assert_eq!(owned.get(1).unwrap(), t2); +} + +#[test] +fn test_multiple_players_same_event() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "Multi"), &0u64, &9999u64); + + set_time(&env, 100); + let alice = Address::generate(&env); + let bob = Address::generate(&env); + + let t_alice = client.check_in(&alice, &event_id); + let t_bob = client.check_in(&bob, &event_id); + + assert_ne!(t_alice, t_bob); + assert_eq!(client.owner_of(&t_alice), alice); + assert_eq!(client.owner_of(&t_bob), bob); + assert_eq!(client.total_supply(), 2u32); +} + +// ─── Window enforcement tests ────────────────────────────────────────────────── + +#[test] +#[should_panic(expected = "Check-in window is not open")] +fn test_checkin_before_window_panics() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "Future"), &1000u64, &2000u64); + + // Clock is before the window + set_time(&env, 500); + + let player = Address::generate(&env); + client.check_in(&player, &event_id); +} + +#[test] +#[should_panic(expected = "Check-in window is not open")] +fn test_checkin_after_window_panics() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "Past"), &1000u64, &2000u64); + + // Clock is after the window + set_time(&env, 3000); + + let player = Address::generate(&env); + client.check_in(&player, &event_id); +} + +// ─── Double check-in prevention ─────────────────────────────────────────────── + +#[test] +#[should_panic(expected = "Already checked in")] +fn test_double_checkin_same_event_panics() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "Once"), &0u64, &9999u64); + + set_time(&env, 100); + let player = Address::generate(&env); + + client.check_in(&player, &event_id); + client.check_in(&player, &event_id); // must panic +} + +#[test] +fn test_same_player_can_attend_different_events() { + let (env, client, _admin) = setup(); + + let e1 = + client.create_event(&String::from_str(&env, "E1"), &0u64, &9999u64); + let e2 = + client.create_event(&String::from_str(&env, "E2"), &0u64, &9999u64); + + set_time(&env, 100); + let player = Address::generate(&env); + + let t1 = client.check_in(&player, &e1); + let t2 = client.check_in(&player, &e2); + + assert_ne!(t1, t2); + assert_eq!(client.total_supply(), 2u32); +} + +// ─── Non-transferability tests ──────────────────────────────────────────────── + +#[test] +#[should_panic(expected = "Attendance tokens cannot be transferred")] +fn test_transfer_always_panics() { + let (env, client, _admin) = setup(); + + let event_id = + client.create_event(&String::from_str(&env, "Soul"), &0u64, &9999u64); + + set_time(&env, 100); + let alice = Address::generate(&env); + let bob = Address::generate(&env); + + let token_id = client.check_in(&alice, &event_id); + + // Any attempt to transfer must panic. + client.transfer(&alice, &bob, &token_id); +} + +// ─── Edge-case / unknown event ──────────────────────────────────────────────── + +#[test] +#[should_panic(expected = "Event not found")] +fn test_checkin_unknown_event_panics() { + let (env, client, _admin) = setup(); + + set_time(&env, 500); + let player = Address::generate(&env); + client.check_in(&player, &999u32); // event does not exist +} + +#[test] +fn test_get_event_nonexistent_returns_none() { + let (_env, client, _admin) = setup(); + assert!(client.get_event(&999u32).is_none()); +} + +#[test] +fn test_get_token_nonexistent_returns_none() { + let (_env, client, _admin) = setup(); + assert!(client.get_token(&999u32).is_none()); +}