# Writing a smart contract in Rust

### Sample contract functionality

The sample contract serves as a demonstration of general QVM logic.

It is capable of:

* registering users into the database
* storing the last registered user's name in the database
* echoing the previous user's name to STDOUT
* incrementing the total registered user count
* storing above counter in the database

### Sample smart contract code

```rust
use std::env;

fn get_env(key: String, default: String) -> String {
    env::var(key).unwrap_or(default)
}

fn atoi(val: String) -> i32 {
    val.parse().unwrap_or(0)
}

fn main() {
    let args: Vec<String> = env::args().collect();
    // THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
    if args.len() == 3 && args[1] == "register" {
        // GET THE CURRENT USER'S NAME OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
        let previous_name = get_env("DB_USER_CURRENT".to_string(),"unknown".to_string());

        // GET THE TOTAL USER COUNT
        let total_user_count= atoi(get_env("DB_TOTALUSERS".to_string(),"0".to_string()));

        // WRITE PREVIOUS USER NAME TO STDOUT
        println!("OUT=prevname: {}", previous_name);

        // UPDATE CURRENT USER NAME BY WRITING IT TO DB
        println!("DBW=USER_CURRENT={}", args[2]);

        // STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
        println!("DBW=USER_{}={}", total_user_count, args[2]);

        // INCREMENT THE TOTAL USER COUNT
        println!("DBW=TOTALUSERS={}", total_user_count+1);

        std::process::exit(0);
    }

    if args.len() >= 2 {
        eprintln!("Wrong CMD: {}", args[1]);
        std::process::exit(1);
    }
    eprintln!("Wrong args!");
    std::process::exit(1);
}
```

### Save the smart contract

Open a text editor and save above sample contract as `main.rs` file.

{% content-ref url="/pages/OxVPW9omyYNTCfkgHCj4" %}
[Compiling a smart contract in Rust](/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/rust-smart-contract/compiling-a-smart-contract-in-rust.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learn.qanplatform.com/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/rust-smart-contract/writing-a-smart-contract-in-rust.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
