account
Account Management Module
account.rs
account.rs This module provides a simple in-memory account management system using Rust, intended for use in a backend running on the Internet Computer (IC) or a similar environment.
Imports and Type Definitions
use std::collections::HashSet;
type Address = String;HashSetis used to store account addresses without duplicates.Addressis defined as a type alias forString, representing a user’s account address.
State Structure
#[derive(Default)]
struct State {
accounts: HashSet<Address>,
}Stateholds the current set of accounts in memory.#[derive(Default)]automatically generates a default constructor for theStatestruct, initializingaccountsas an empty set.
Thread-local State
thread_local!ensures that each thread has its own copy of the state, which is required for safe mutable access in a concurrent environment.RefCellallows interior mutability, meaning theStatecan be modified even when it is behind an immutable reference.
Create Account Function
Purpose: Adds a new account address if it doesn’t already exist.
Logic:
Borrow the state mutably.
Check if the given address is already in the set.
If it exists, return
"Already exists".If not, insert it into the set and return
"Account created".
This function could be exposed as an update method in an IC canister (the
#[ic_cdk::update]attribute is currently commented out).
Get Accounts Function
Purpose: Returns a list of all registered account addresses.
Logic:
Borrow the state immutably.
Convert the
HashSetof addresses into aVec<String>.Return the vector to the caller.
Last updated