Sign In / Up

Implementing Query and Update Functions in Our Smart Contract

In the previous video, we completed the state setup and implemented our TraitLocal for managing the application state. In this video, we begin defining the core logic by implementing our first query and update functions using the Internet Computer's ic-cdk.

1. Creating Query Functions

get_proposal

This function retrieves a proposal by its unique u64 key.

#[query]
fn get_proposal(key: u64) -> Option<Proposal> {
    PROPOSAL_MAP.with(|p| p.borrow().get(&key).cloned())
}
  • We use with() to access the stable BTreeMap safely.
  • No mutation occurs; therefore, we use borrow() instead of borrow_mut().
  • If the key exists, we return the proposal; otherwise, it returns None.

get_proposal_count

Returns the total number of proposals stored.

#[query]
fn get_proposal_count() -> u64 {
    PROPOSAL_MAP.with(|p| p.borrow().len() as u64)
}
  • Uses len() to count the entries in the map.
  • This helps track the number of proposals at any time.

2. Creating an Update Function

create_proposal

This function adds a new proposal entry to the map.

#[update]
fn create_proposal(key: u64, proposal: CreateProposal) -> Option<Proposal> {
    let value = Proposal {
        description: proposal.description,
        approve: 0,
        reject: 0,
        pass: 0,
        is_active: proposal.is_active,
        voted: Vec::new(),
        owner: ic_cdk::caller(),
    };

    PROPOSAL_MAP.with(|p| {
        p.borrow_mut().insert(key, value)
    })
}
  • CreateProposal includes a description and active status.
  • We initialize vote counts to zero and create an empty vector for voters.
  • The proposal owner is automatically set using ic_cdk::caller(), capturing the caller's principal.
  • We insert the proposal into the map and return the previous value, if any.

3. Summary

In this session, we:

  • Implemented query functions to read from the stable map without changing the state.
  • Created our first update function, enabling users to submit proposals securely.
  • Used safe Rust patterns and the ic-cdk crate to maintain clean, modular, and type-safe code.

Lesson discussion

Swap insights and ask questions about “Build on Internet Computer with ICP Rust CDK”.

Be the first to start the discussion

Ask a question or share your thoughts about this lesson.