Sign In / Up

Creating Candid Files for Your Rust Smart Contract

In this video, we continue building our decentralized application by creating the Candid file (.did) for the smart contract we completed in lib.rs. This step ensures our front-end knows how to communicate with the back-end logic on the Internet Computer.

1. Purpose of the Candid File

The Candid file defines:

  • Types (structs and enums)
  • Function signatures (queries and updates)

These declarations bridge communication between the Rust-based backend and the Motoko or frontend code.

2. Defining Types

Proposal Type

type Proposal = record {
  description: text;
  approve: nat32;
  reject: nat32;
  pass: nat32;
  is_active: bool;
  voted: vec principal;
  owner: principal;
};

CreateProposal Type

type CreateProposal = record {
  description: text;
  is_active: bool;
};

Result and Error Handling

To mimic Rust’s Result type:

type Result = variant {
  ok: null;
  err: VoteError;
};

VoteError Enum

type VoteError = variant {
  AlreadyVoted;
  ProposalNotActive;
  NoSuchProposal;
  AccessRejected;
};

Choice Enum

type Choice = variant {
  Approve;
  Reject;
  Pass;
};

3. Declaring Service Functions

We then define the public functions that can be called from the frontend:

Query Functions

service : {
  get_proposal: (nat64) -> opt Proposal query;
  get_proposal_count: () -> nat64 query;

Update Functions

 create_proposal: (nat64, CreateProposal) -> opt Proposal;
  edit_proposal: (nat64, CreateProposal) -> Result;
  end_proposal: (nat64) -> Result;
  vote: (nat64, Choice) -> Result;
};

4. Key Notes on Candid Syntax

  • Use nat32, nat64 for Rust’s u32, u64.
  • Use text instead of string.
  • Define records for structs and variants for enums.
  • Types must be defined before being used in function signatures.

5. Conclusion

Your Candid file acts as the contract’s public interface. With the types and function signatures correctly defined, your frontend can now interact seamlessly with the backend. In the next video, we’ll move on to testing the smart contract.

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.